text
stringlengths
28
935k
meta
stringlengths
137
139
red_pajama_subset
stringclasses
1 value
\section{Reasoning for KGC} \label{sec:reasoning_for_KGC} This section introduces the reasoning methods for KGC in three main categories. Figure~\ref{fig:kgc-framework} presents the taxonomy of the KGC reasoning methods. \begin{table*}[t] \newcolumntype{?}{!{ \hspace{0.5pt} \vrule width 1pt \hspace{-2pt}}} \newcolumntype{k}{!{\hspace{-5pt}}} \newcolumntype{C}{>{\centering\arraybackslash}p{2em}} \centering \scriptsize \renewcommand\arraystretch{1.0} \caption{ \label{tb:overall_KGC} A summary of knowledge graph completion and recent advances. } \begin{tabular}{cclll} \toprule Category & Sub-category & Model & Mechanism \\ \midrule \multirow{25}{*}{\tabincell{c}{Neural \\ Reasoning}} & \multirow{7}{*}{\tabincell{c}{Translation\\-based \\ Models}} & TransE~\cite{bordes2013translating} & force $\textbf{h}+\textbf{r}$ to be close to $\textbf{t}$ \\ && TransH~\cite{Wang14} & project entities into the relation-specific hyperplane \\ && TransR~\cite{lin2015learning} & project entities and relations in separate spaces\\ && TransD~\cite{ji-2015} & determine the project matrices by both entities and relations \\ && TransG~\cite{xiao2015transg} & project a relation into multiple embeddings \\ && TransAt~\cite{qian2018translating} & project a relation by entities' categories and the relation's attributes \\ && RotatE~\cite{sun2018rotate} & map entities and relations to the complex vector space \\ \cmidrule{2-4} & \multirow{7}{*}{\tabincell{c}{Multiplicative \\Models}} & RESCAL~\cite{NickelICML11} & maximize the tensor product between two entities\\ && DisMult~\cite{yang2014embedding} & simplify the project matrix into a diagonal matrix\\ && ComplEx~\cite{pmlr-v48-trouillon16} & use complex embeddings to handle asymmetry\\ && HolE~\cite{NickelAAAI16} & use the circular correlation to represent entity pairs\\ && SimplE~\cite{NIPS2018_7682} & learn a head and tail embeddings for each entity\\ && ANALOGY~\cite{pmlr-v70-liu17d} & constrain relation matrixes to be normal matrixes \\ && DiHEdral~\cite{xu2019relation} & support the non-commutative property of a relation \\ \cmidrule{2-4} & \multirow{11}{*}{\tabincell{c}{Deep Learning \\ Models}} & ConvE~\cite{dettmers2018convolutional} & use the head and relation embeddings as the input of CNN \\ && ConvR~\cite{jiang2019adaptive} & extend global filters in ConvE to relation-specific filters \\ && ConvKB~\cite{nguyen2018novel} & use the head, relation and tail together as the input of CNN \\ && CapsE~\cite{Dai-2019} & use the capsule network as the convolution function \\ && RSN~\cite{pmlr-v97-guo19c} & use RNNs to capture long-term relational dependencies \\ && R-GCN~\cite{schlichtkrull2018modeling} & use relation-aware GCN as the encoder and DisMult as the decoder\\ && M-GNN~\cite{Wang-ijcai2019} & replace the mean aggregator in R-GCN with a MLP \\ && CompGCN~\cite{vashishth2019composition} & incorporate entity and relation embeddings into the aggregator function\\ && KBGAT~\cite{Deepak-ACL2019} & incorporate a triplet into the aggregator function\\ \midrule \multirow{4}{*}{\tabincell{c}{Symbolic \\ Reasoning}} & \multirow{4}{*}{\tabincell{c}{ - }} & AIME~\cite{galarraga2013amie} & generate rules by rule extending and rule pruning\\ && AIME+~\cite{galarraga2015fast} & improve the efficiency of AMIE\\ && RLvLR~\cite{omran2018scalable} & reduce the search space by the embedding technique\\ && RuLES~\cite{ho2018rule} & leverage the embedding technique to measure the quality of the rules \\ \midrule \multirow{25}{*}{\tabincell{c}{Neural-Symbolic \\ Reasoning}} & \multirow{4}{*}{\tabincell{c}{Symbolic-driven\\ Neural \\Reasoning}} & KALE~\cite{guo2016kale} & learn embeddings on the observed triples and the ground rules \\ && RUGE~\cite{guo2017ruge} & change the ground rules to the triplets derived by rules\\ && Wang et al.~\cite{wang2019logic} & transform a triple/ground rule into first-order logic\\ && IterE~\cite{zhang2019iere} & infer rules and update embeddings iteratively \\ \cmidrule{2-4} & \multirow{5}{*}{\tabincell{c}{Symbolic-driven\\ Probabilistic\\ Reasoning}} & MLN~\cite{richardson2006markov} & build a probabilistic graphic model for all the rules and learn their weights\\ && pLogicNet~\cite{qu2019policnet} & incorporate the embedding technique to infer marginal probabilities in MLN\\ && ProbLog~\cite{de2007problog} & build a local SLD-tree for a relation and learn rules that can support it \\ && SLPs~\cite{cussens2001parameter} & define a randomized procedure for traversing the SLD-tree in ProbLog \\ && ProPPR~\cite{wang2013programming} & change the randomized procedure in SLPs to a biased sampling strategy \\ \cmidrule{2-4} & \multirow{16}{*}{\tabincell{c}{Neural-driven\\ Symbolic\\ Reasoning}} & PRA~\cite{lao2010relational} & enumerate the paths between two entities \\ && Lao et al.~\cite{lao-etal-2012-reading} & perform PRA on the KG and the extended textural graph\\ && Neelakantan et al.~\cite{Neelakantan2015Compositional} & use RNN to encode the most confident path \\ && Chain-of-Reasoning~\cite{Das2017chain} & change the most confident path to multiple paths \\ && DeepPath~\cite{Xiong2017deeppath} & use RL to evaluate the sampled paths \\ && AnyBURL~\cite{meilicke2020AnyBURL} & generalize the sampled paths to abstract rules \\ && MINERVA~\cite{Das2017MINERVA} & use RL to directly find the answer \\ && MultiHop~\cite{Lin2018multi} & adopt soft reward and action dropout for MINERVA\\ && CPL~\cite{fu2019CPL} & leverage the text in addition to the KG when sampling\\ && M-walk~\cite{shen2018mwalk} & use Monte Carlo Tree Search when sampling\\ && DIVA~\cite{chen2018diva} & use VAE to unify path sampling and answer reasoning\\ && CogGraph~\cite{Du-2019} & sample multiple entities at each hop\\ && TensorLog~\cite{cohen2016tensorlog} & keep all the neighbors at each hop without sampling\\ && Neural LP~\cite{yang2017differentiable} & learn new rules based on TensorLog\\ && NLIL~\cite{yang2019learn} & deal with non-chain-like rules\\ && Neural-Num-LP~\cite{wang2019differentiable} & deal with numerical operations\\ \bottomrule \end{tabular} \normalsize \end{table*} \subsection{Neural Reasoning} \label{sec:neural_reasoning_for_KGC} \input{neural_reasoning.tex} \subsection{Symbolic Reasoning} \label{sec:symbolic_reasoning_for_KGC} \input{symbolic_reasoning.tex} \subsection{Neural-Symbolic Reasoning} \label{sec:neural_symbolic_reasoning_for_KGC} \input{neural_symbolic_reasoning.tex} \section{Reasoning for KGQA} \label{sec:reasoning_4_QA} In this section, we will introduce the reasoning methods for KGQA, which can also be categorized into the neural, the symbolic and the neural-symbolic reasoning methods. KGQA needs to deal with the natural language questions, which is more complex than reasoning for KGC. Thus according to the types of the questions, we can further categorize KGQA into simple-relation questions, multi-hop relation questions and complex-logic questions. Single-relation questions refer to questions that only involve a single topic entity and a single relation in KGs. Then the tail entities in KGs corresponding to the topic entity and the relation are extracted as the answers. Example questions of this type include: ``Who is the wife of Barack Obama" or ``Where is the Forbidden City". Multi-hop relation questions are path-based which means the answer can be found by walking along a path consisting of multiple intermediate relations and entities starting from the topic entity. Complex-logic questions contain several subject entities aggregated by conjunction ($\cap$), disjunction ($\cup$) or logical negation ($\neg$), which means the answer can be obtained by some operations, such as intersection of the results from multiple path queries (multi-hop questions). Questions may also have some complex constraints (Cf. Table~\ref{tb:constraints} for details). Figure~\ref{fig:kgqa-framework} presents the taxonomy of the KGQA reasoning methods and the links between the question types and the methods that can address them. \begin{table*}[t] \newcolumntype{?}{!{ \hspace{0.5pt} \vrule width 1pt \hspace{-2pt}}} \newcolumntype{k}{!{\hspace{-5pt}}} \newcolumntype{C}{>{\centering\arraybackslash}p{2em}} \centering \scriptsize \renewcommand\arraystretch{1.0} \caption{ \label{tb:overall_KGQA} A summary of knowledge graph question answering and recent advances. S: single-relation question, M: multi-hop relation question, C: complex-logic question. } \begin{tabular}{ccclll} \toprule Category & Sub-category & Question Type & Model & Mechanism \\ \midrule \multirow{6}{*}{\tabincell{c}{Neural \\ Reasoning}} & \multirow{6}{*}{\tabincell{c}{-}} &S & KEQA~\cite{huang2019knowledge} & train a topic entity learning model and query relation learning model\\ &&S & Liu et al.~\cite{lukovnikov2017neural} & train an end-to-end topic entity and query relation learning model\\ &&M & EmbedKGQA\cite{Saxena2020ImprovingMQ} & use RoBERTa to embed the question\\ &&C& GQE~\cite{Hamilton2018EmbeddingLQ} & deal with conjunctive logic queries \\ &&C& QUERY2BOX~\cite{ren2019query2box} & deal with disjunctive queries \\ &&C& EmQL~\cite{Sun2020FaithfulEF} & obtain faithful embeddings \\ \midrule \multirow{6}{*}{\tabincell{c}{Symbolic\\Reasoning}} & \multirow{3}{*}{\tabincell{c}{Semantic\\ Parsing}} &C & Kwiatkowksi et al.~\cite{kwiatkowksi2010inducing} & follow CCG to parse questions\\ &&C& Berant et al.~\cite{berant2013semantic} & follow $\lambda$-DCS to parse questions\\ &&C& Dubey et al.~\cite{dubey2016asknow} & follow NLQF to parse questions\\ \cmidrule{2-5} & \multirow{3}{*}{\tabincell{c}{Template-based \\ Parsing}} &C& UncertainTQA~\cite{Zheng2015HowTB} & link query graphs and SPARQLs as templates\\ &&C& QUINT~\cite{Abujabal2017AutomatedTG} & link query graphs and dependency parse trees as templates\\ &&C& TemplateQA~\cite{Zheng2018QuestionAO} & link natural language patterns and SPARQLs as templates\\ \midrule \multirow{9}{*}{\tabincell{c}{Neural \\ Symbolic\\Reasoning}} & \multirow{4}{*}{\tabincell{c}{Neural-Symbolic\\ Reasoning}} &S & Yih et al.~\cite{Yih2014} & link questions to KG and use CNN to encode the linked entities/relations\\ &&M& MULTIQUE~\cite{bhutani2020answering} & generate a sub query graph and use LSTM to qualify it\\ &&C& Bao et al.~\cite{bao2016constraint} & generate a multi-constraint query graph\\ &&C& Lan et al.~\cite{lan-jiang-2020-query} & incorporate constraints and extend relation paths simultaneously\\ \cmidrule{2-5} & \multirow{5}{*}{\tabincell{c}{End-to-end \\ Reasoning}} &M& IRN~\cite{zhou2018an} & extend a path based on question and entity/relation embeddings\\ &&M& SRN~\cite{qiu2020stepwise} & use RL to learn the path sampling strategy\\ &&M& Graft-Net~\cite{sun-etal-2018-open} &extract a subgraph and apply GNN to infer the answer in it\\ &&M& PullNet~\cite{SunACL2019} &use RL to learn the subgraph sampling strategy\\ &&M& VRN~\cite{zhang2018variational} &model the topic entities as hidden variables\\ \bottomrule \end{tabular} \normalsize \end{table*} \begin{figure}[t] \centering \includegraphics[width=0.47\textwidth]{Figures/KGQA-framework} \caption{\label{fig:kgqa-framework} The taxonomy of the KGQA reasoning methods. The dashlines link the question types to the methods that can address them.} \end{figure} \input{neural_reasoning_for_QA.tex} \input{symbolic_reasoning_for_QA.tex} \input{neural_symbolic_reasoning_for_QA.tex} \section{Conclusion and Future Directions} \label{sec:con} In this section, we first conclude this survey by casting KQC and KGQA in a unified reasoning framework and then discuss some potential future directions. \subsection{Conclusion} Generally, most of the reasoning methods for completion can be decomposed into two key components: rule finding and answer reasoning, where rule finding targets at inferring the rules from the observed triplets in KGs, and answer reasoning aims to predict the answer for the given head entity and the query relation. Different methods for KGC emphasize different components. In Figure~\ref{subfig:KGC}, going from left to right, the methods pay more and more attention to answer reasoning and less and less attention on rule finding. For example, on the far left, the pure symbolic reasoning methods such as AMIE only explain how to find rules from the data but without discussing the usage of the rules to reason answers. Then the path-based reasoning method PRA not only ad-hocly retrieves the paths by PageRank, but also trains a simple linear regression model based on the paths to reason answers. However, how to retrieve the paths is still the core problem to be solved in PRA. DIVA treats the two components equally in a unified model through formulating paths as hidden variables. Subsequently, DeepPath and MINERVA directly reason the answers by RL, without explicitly deriving the paths. Graph-based reasoning such as CogGraph extends a single path to a subgraph and matrix-based reasoning such as TensorLog and Neural LP extends the subgraph to the whole graph with attentions on different nodes at each hop. Although the explicit rule finding is missing, the path-based, graph-based, and matrix-based reasoning can still derive the paths according to the selections or attentions at each hop. At the same time, symbolic-driven probabilistic reasoning and symbolic-driven neural reasoning thoroughly take the answer reasoning as the target. The difference is that in the symbolic-driven probabilistic reasoning, the rules are used as the features to predict the answers, while in the symbolic-driven neural reasoning, the rules are used to generate more facts for learning high-quality embeddings. Finally, the neural reasoning methods get rid of the rules and reason answers entirely based on the embedding techniques. Most of the reasoning methods for KGQA can also be decomposed into rule finding and answer reasoning, where the former targets at parsing the rule, i.e., a path or a subgraph from the given question, and the latter aims to predict the answer for the given question. In Figure~\ref{subfig:KGQA}, the methods from the left to the right gradually pay more attention to answer reasoning and less attention to rule finding. Starting from the left, the pure symbolic methods and the neural-enhanced symbolic reasoning methods only parse the questions to obtain the executable queries, query paths, or subgraphs, where the neural-enhanced symbolic reasoning methods incorporate additional embedding techniques to evaluate the parsed paths or subgraphs. Then the graph-based reasoning methods Graft-Net and VRN retrieve the subgraphs heuristically and then reason the answers from the subgraphs by neural networks or graph convolution networks. Later, the path-based methods IRN and SRN and the graph-based method PullNet reason the paths/subgraphs and the answers in an end-to-end manner by RL or weak supervision techniques. The far right neural reasoning methods get rid of the paths/subgraphs entirely and directly measure the relationships between the answers and the given question. The pure symbolic methods can parse quite complex questions such as those with multiple constraints as they only parse the questions. However, the path/graph-based end-to-end methods need to extend the paths/subgraphs along with the relations in KGs, making it not easy to incorporate the complex logic questions. \subsection{Future Directions} Despite the existing researches on reasoning methods for KGC and KGQA, there are still unsolved challenges on these tasks such as reasoning for the few-shot relations in KGC and reasoning for the complex questions in KGQA. In addition, existing works mainly focus on leveraging the knowledge graph structures for reasoning, but only a few works investigate how to leverage the side information of the entities and the relations to benefit the reasoning task~\cite{fu2019CPL,sun-etal-2018-open,toutanova2015representing}, the performance of which can be still improved. Moreover, some other kinds of reasoning tasks on KGs such as dynamic reasoning and analogical reasoning are also worth studying. Finally, existing reasoning methods lack the transferability from one KG to others. We explain these future directions in detail as below. \vpara{Few-shot Reasoning.} Most of the neural-symbolic models heavily rely on a huge amount of training instances. However, the relationships between entities in KGs are far from complete, especially for the rare relations, making it extremely difficult to capture the underlying patterns of these rare relations. Few-shot learning is a paradigm proposed for learning in the scenario of lacking training instances, which has first shown the significant performance in computer vision~\cite{fei2006one}. Then, few-shot learning in KGs, which aims to discover the underlying patterns of a relation with which only a few triplets is associated, has been studied recently~\cite{Du-2019, xiong2018one}. Although these are good attempts, the poor performance of reasoning tasks reported by them indicates that few-shot reasoning is still an unsolved challenge. \vpara{Answering Complex Questions.} Existing neural-symbolic reasoning models are criticized as most of them can only answer the single-relation questions, or limited-hop relations (e.g., three-hop relations), let alone the questions with additional constraints. Ding et al.~\cite{ding2019cognitive} showed that the performance of the traditional reasoning models on question answering task decreases dramatically with the increase of the hops, as the search space increases exponentially with the hops, making it difficult to reason the correct answer from such big search space. Recently for question answering upon text corpus, neural-symbolic models incorporating human cognition have shown their superiority on reasoning capacity~\cite{ding2019cognitive}, as they consistently perform well with the increase of the hops in questions. Thus, a new way is called for to incorporate human cognition into neural-symbolic reasoning in KGs. Humans usually answer multi-hop questions following two reasoning systems, where the first system makes fast and intuitive thinking for collecting enough raw evidence, and the second system makes slow and logical thinking for reasoning among the collected raw data. How to model the two systems in a neural-symbolic reasoning framework in KGs effectively is a promising direction. \vpara{Reasoning upon Multi-sources.} Since the structure information comprised of entities and relations in a knowledge graph is far from complete, incorporating additional information from unstructured text data for reasoning is encouraged. Although some models such as Graft-Net~\cite{sun-etal-2018-open} and PullNet~\cite{SunACL2019} are the state-of-the-art reasoning models on both the structural and the textual information, it is still challenging to determine the correct evidence to be linked to the incomplete graph structure from the large textual data. Meanwhile, although the textual information can enrich the KGs, it contains much useless and redundant information, which may result in side effects on the reasoning tasks. \vpara{Dynamic Reasoning.} Dynamic reasoning aims at learning new logic rules and inferring new facts evolving with time. Existing reasoning methods are all devoted to reasoning in the static KGs, but they ignore the temporal information contained in knowledge. However, as we all know, the facts contained in KGs such as (Steve Jobs, CEO of, Apple inc.) are not always true over time. Besides, new knowledge is produced by humans continually, which may be injected into KGs dynamically. Thus, dynamic reasoning upon the dynamic KGs is demanded to self-correct KGs and mine new logic rules continually. \vpara{Analogical Reasoning.} Learning quickly is a hallmark of human intelligence, which involves figuring out the underlying patterns in a new domain by adopting the experience in old domains. It will be appreciated that if the reasoning models on KGs are able to perform the same adaptive learning by comparing the similarities between the new KGs and old KGs. We take academic knowledge graphs as examples to explain analogical reasoning. Suppose in these KGs for different academic fields such as computer vision (CV) and natural language processing (NLP), science problems and techniques are added as the nodes, and multiple relationships such as techniques solving problems and techniques citing techniques are added as the edges. Some deep learning techniques such as CNN~\cite{krizhevsky2017imagenet} and pre-training~\cite{liu2020} techniques originally proposed in the problems of CV are further adapted to the problems of NLP, and have shown their superior performance, which can be treated as typical analogical reasoning on the problems between CV and NLP. \vpara{Knowledge Graph Pre-training.} Neural reasoning methods for KGC such as TransE and ConvE reviewed in \secref{sec:neural_reasoning_for_KGC} produce entity embeddings and relation embeddings, which can be incorporated into the symbolic reasoning process to improve the capacity of fault-tolerance (Cf. ~\secref{sec:neural_driven_symbolic_reasoning} for details). However, these neural reasoning models treat the embeddings for all entities and relations in the given knowledge graph as parameters to be learned, which cannot be transferred to other knowledge graphs. Recently, the transferable pre-training graph neural networks have proved to be able to capture the graph structure characteristics across different graph data~\cite{hu2020gpt-gnn,qiu2020gcc}. Inspired by the success of the graph pre-training models, a knowledge graph pre-training model that can capture the transferable semantics of the entities and relations across different knowledge graphs is worth studying. \section{Introduction} \label{sec:intro} \IEEEPARstart{S}{ymbolism} and connectionism are two main paradigms of Artificial Intelligence. Symbolism assumes the basic units which compose the human intelligence are symbols, and the cognitive process is a series of explicit inferences upon symbolic representations~\cite{minsky1969introduction,haugeland1989artificial}. Generally, the models of symbolism have sound readability and interpretability. However, the finite and discrete symbolic representations are insufficient to depict all the intrinsic relationships among data, and also intolerant of ambiguous and noisy data. On the contrary, connectionism imitates the process of neuron connections and cooperation in human brains to build models~\cite{rosenblatt1958perceptron,rumelhart1986learning}. Different models of connectionism have been developed. Deep learning is a representative model of connectionism~\cite{bengio2007greedy,hinton2006fast}. Deep learning has reached unprecedented impact across research communities as it achieved superior performances on many tasks in different fields such as image classification in computer vision~\cite{chen2020simple,he2020momentum,he2016deep}, language modeling in natural language processing~\cite{brown2020language,devlin2018bert}, and link prediction in networks~\cite{kipf2016semi,velivckovic2017graph,you2020graph}.This indicates that deep learning models are capable of modeling the implicit correlations inside data. However, the models of connectionism cannot provide explicit inference evidence to explain the results, making it look like a black box. The problem of combining symbolism and connectionism has been researched since the 1980s~\cite{gallant1993neural,gallant1988connectionist,shavlik1991symbolic,towell1994refining,towell1994knowledge}, and has attracted much attention recent years~\cite{besold2017neural,de2011neural,garcez2019neural,garcez2012neural,lamb2020graph}. \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{Figures/reasoning_example} \caption{\label{fig:reasoning_example} Illustration of a knowledge graph~\cite{teru2019inductive} and examples of two reasoning tasks.} \end{figure} In this survey, we discuss how the above two principles are performed and intertwined for reasoning over knowledge graphs (KGs) such as Freebase~\cite{Bollacker2008}, DBpedia~\cite{Lehmann2015}, YAGO~\cite{Suchanek2007} and NELL~\cite{Carlson2010}, which are composed by a large number of (head, relation, and tail) triplets. Since KGs are naturally discrete symbolic representations to support explicit inferences and can be also represented into the continuous vector space by deep learning models such as the state-of-the-art TransE~\cite{bordes2013translating} to support implicit inferences, it is promising to effectively combine the ideas of symbolism and connectionsim on KG reasoning tasks. Specifically, we review the mechanisms of two typical KG reasoning tasks --- knowledge graph completion (KGC) and knowledge graph question answering (KGQA). KGC is to infer the answers, i.e., the tail entities given a head entity and a query relation~\cite{Das2017MINERVA,lao2010relational,Xiong2017deeppath,yang2017differentiable}. It is formulated as $(h, r, ?)$ where $h$ is the head entity, $r$ is the query relation, and $?$ is the tail entity that should satisfy $r$ with $h$. KGQA is similar to KGC except that the condition of the head entity $h$ and the query relation $r$ is replaced by a natural language question $q$~\cite{bao2016constraint,berant2013semantic,Saxena2020ImprovingMQ,sun-etal-2018-open}. Figure~\ref{fig:reasoning_example} illustrates the two reasoning tasks by examples, where the KGC example is to reason the tail entity ``L.A" given the query relation ``Lives\_in" and the head entity ``A. Davis", and the KGQA example is to reason the answer ``L.A" given the question ``Where do the spouses of the teammates of Lakers usually live?". Despite the abundant surveys about knowledge graph embedding~\cite{ji2020survey,rossi2020knowledge,Wang2017}, acquisition and applications~\cite{ji2020survey}, question answering~\cite{fu2020survey,Wu2019} and reasoning~\cite{CHEN2020}, none of them explicitly sort out the symbolic or the neural methods, or the way to intertwine them. All the aforementioned surveys separate the reasoning tasks of KGC and KGQA. This paper unifies the two tasks in one reasoning framework and categorize the reasoning mechanisms into symbolic, neural, and hybrid. We demonstrate the pros. and cons. of each category and also discuss the future directions for KG reasoning. All the surveyed papers are retrieved by Google Scholar according to the keywords ``knowledge graph reasoning", ``knowledge graph completion", ``knowledge graph question answering", etc., and are chosen to be included if they are published by authoritative conferences or journals or widely cited. The rest of the article is organized as follows. \secref{sec:preliminaries} introduces the background knowledge that is closely related to the surveyed techniques. \secref{sec:reasoning_for_KGC} reviews the three kinds of reasoning techniques for knowledge graph completion. \secref{sec:reasoning_4_QA} reviews question answering on KGs under a similar reasoning framework. \secref{sec:con} first summarizes all kinds of reasoning methods in a unified technique development trend and then ends with the discussion of the potential directions in the future. \subsubsection{Translation-based Models} Translation-based models usually learn embeddings by translating a head entity to a tail entity through the relation. For example, TransE~\cite{bordes2013translating}, a representative translation-based model, maps the entities and relations into the same vector space and forces the added embedding $\textbf{h}+\textbf{r}$ of a head entity $h$ and a relation $r$ to be close to the embedding $\textbf{t}$ of the corresponding tail entity $t$, i.e., minimizes the score of a triple as follows: \beq{ \label{eq:transe} s(h,r,t) = ||\mathbf{h}+\mathbf{r}-\mathbf{t}||_2^2. } Subsequently, various models have been proposed to improve the capability of TransE. For example, TransH deals with the flaws caused by the relations with the properties of reflexive, one-to-many, many-to-one, and many-to-many by projecting the entities into the relation-specific hyperplane, which enables different roles of an entity in different relations/triplets~\cite{Wang14}. Instead of projecting entities and relations into the same space, TransR builds entity and relation embeddings in separate entity space and relation space~\cite{lin2015learning}. TransD~\cite{ji-2015} determines the mapping matrices by both the entities and the relations with the hope to capture the diversity of entities and relations simultaneously. TransG~\cite{xiao2015transg} further addresses the ambiguity of a relation by incorporating a Bayesian non-parametric infinite mixture model to generate multiple translation components for a relation. TransAt~\cite{qian2018translating} determines a relation between two entities in two steps inspired by the human cognitive process. It first checks the categories of entities and then determines a specific relation by relation-related attributes through a relation-aware attention mechanism. To model and infer the symmetry/antisymmetry, inversion, and composition patterns together, RotatE~\cite{sun2018rotate} maps the entities and relations to the complex vector space and defines each relation as a rotation from the head entity to the target entity. \subsubsection{Multiplicative Models} Multiplicative models produce the entity and relation embeddings via tensor product as follows: \beq{ s(h,r,t) = \mathbf{h}^T \mathbf{M}_r \mathbf{t}, } \noindent where $\mathbf{M}_r$ is an asymmetric $d \times d$ matrix that models the interactions of the latent components in the $r$-th relation. Given a relation matrix $M_r$, a feature in the above tensor product is ``on" if and only if the corresponding features of both entities $h$ and $t$ are ``on", which can capture the relational patterns between entities. The representative tensor product-based models are RESCAL~\cite{NickelICML11}. However, the tensor product requires a large number of parameters as it models all pairwise interactions. To reduce the computational cost, DisMult~\cite{yang2014embedding} is proposed to use the diagonal matrix with the diagonal vector indicating the embedding of the relation $r$ to reduce the number of parameters. Based on DisMult, ComplEx~\cite{pmlr-v48-trouillon16} further handles asymmetry thanks to the capabilities of complex embeddings. Instead of tensor product, HolE~\cite{NickelAAAI16} uses the circular correlation of vectors to represent pairs of entities, i.e., $\mathbf{h} \star \mathbf{t}$ where each element $[\mathbf{h} \star \mathbf{t}]_k = \sum_{i=0}^{d-1} h_i t_{(k+i) \text{ mod } d}$. SimplE~\cite{NIPS2018_7682} is based on canonical Polyadic decomposition~\cite{Frank1927}, which learns an embedding vector for each relation, and a head embedding plus a tail embedding for each entity. To address the independence between the two embedding vectors of the entities, SimplE introduces the inverse of relations and calculates the average canonical Polyadia score of $(h,r,t)$ and $(t ,r^{-1}, h)$. In addition, ANALOGY~\cite{pmlr-v70-liu17d} supports analogical inference by constraining the relation matrix $\mathbf{M}_r$ to be the normal matrix in linear mapping, i.e. $\mathbf{M}_r^T\mathbf{M}_r = \mathbf{M}_r\mathbf{M}_r^T$. DihEdral~\cite{xu2019relation} employs finite non-Abelian group to account for relation compositions, which supports the non-commutative property of a relation. For example, one exchanges the order between \textit{parent\_of} and \textit{spouse\_of} will result in different relations (\textit{parent\_of} as opposed to \textit{parent\_in\_law\_of}), which indicates the non-commutative property of the relation. \subsubsection{Deep Learning Models} The deep learning models, such as the convolutional neural network (CNN), the recurrent neural network (RNN), and the graph neural network (GNN), are also leveraged as encode functions to embed entities and relations in KGs. For example, ConvE~\cite{dettmers2018convolutional} first concatenates a pair of head embedding and relation embedding and then applies 2D convolutions over those embeddings to predict the tail entity. ConvR~\cite{jiang2019adaptive} extends the global filters in ConvE to relation-specific filters, and InteractE~\cite{vashishth2020interacte} captures more interactions by additional convolution operations. Instead of only performing the convolutions on head and relation embeddings, ConvKB~\cite{nguyen2018novel} applies convolutions over the concatenated embeddings of the head entity, relation, and the tail entity together, which captures the translation relationship in a triplet. CapsE~\cite{Dai-2019} applies the capsule network~\cite{Sara-NIPS-2017} as the convolution function to encode the entities. RSN~\cite{pmlr-v97-guo19c} integrates RNNs with residual learning to capture the long-term relational dependencies in knowledge graphs. Recently, GNNs are also attempted to encode the neighboring entities and relations together beyond a single triplet. For example, to adapt to the multiple relations in knowledge graphs, R-GCN extends the transformation weights in GCN to relation-aware weights~\cite{schlichtkrull2018modeling}. To predict the relation between two entities, R-GCN uses relation-aware GCN as the encoder to represent each entity and then leverages DisMult~\cite{yang2014embedding} as the decoder to score a given triplet based on the encoded entities and the introduced diagonal matrix $\mathbf{M}_r$ for each relation. Instead of using DisMult as the decoder, SACN~\cite{ShangAAAI2019} uses a variant ConvE~\cite{dettmers2018convolutional} as the decoder, where the encoder is also a relation-aware GCN. M-GNN~\cite{Wang-ijcai2019} replaces the mean aggregator in each graph convolution layer in R-GCN with a multi-layer perceptron (MLP) to support the injective property, i.e., to map two entities to the same location only if they have identical neighborhood structures with identical embeddings on the corresponding neighbors. In addition to the relation-aware transformation weights, VR-GCN~\cite{ye2019vectorized} and CompGCN~\cite{vashishth2019composition} explicitly represent relations and further combine entity and relation embeddings by the operations like subtraction and multiplication. KBGAT~\cite{Deepak-ACL2019} enables triplet-aware weights by concatenating the embeddings of the head entity, tail entity, and the relation in a triplet to learn its weight. More details of knowledge graph embeddings can be found in~\cite{ji2020survey,rossi2020knowledge}. \vpara{Summary.} The neural reasoning methods utilize shallow embedding models, such as the translation-based models, the multiplicative-based models, or the deep neural network models including CNN, RNN, and GNN, to embed entities and relations in KGs, based on which they perform the reasoning task. These methods are fault-tolerant, as the reasoning is built on the semantic representations rather than the symbolic representations of entities and relations. However, these simple neural network models cannot infer the answers when the complex logic relations $\{\land, \lor, \neg \}$ exist between the head and the answer entities. Besides, the neural networks lack interpretation, as they cannot provide explicit rules for explaining the reasoning results. \subsection{Neural Reasoning} \label{sec:neural_reasoning_for_QA} Neural reasoning methods for question answering usually encode the entities and relations in KGs as well as the input questions into embeddings of the same space, based on which they infer the answers. Neural reasoning methods can deal with three kinds of questions: the single-relation questions, the multi-hop relation questions and the complex-logic questions. \vpara{Single-relation Question.} KEQA~\cite{huang2019knowledge} deals with the single-relation questions by finding several candidate triplets. The tail entity in the candidate triplets is chosen as the answer according to the embeddings of the triplet, the topic entity and the query relation in the question. Specifically, to find the candidate triplets, KEQA first trains a head entity learning model with Bidirectional LSTM as the key component to predict the entity token and the non-entity token in the question literals. It then extracts the topic entity based on the predicted tokens and searches the entities in KGs which are same to the topic entity or contain the topic entity as the candidate heads. All the triplets with head entity in the candidate heads are named as the candidate triplets. Next, to obtain the embeddings of the topic entity and the query relation, the authors propose another bi-directional LSTM which takes the sequential tokens in the question literals as input to predict the corresponding embedding. Finally, for each candidate triplet, KEQA minimizes the Euclidean distance of the predicted embedding between the candidate and the ground truth, in head entity, predicate, and answer. Liu et al.~\cite{lukovnikov2017neural} propose a similar end-to-end method to address the single-relation questions. For topic entity and single relation, both word-level information and character-level information from the question are considered. Other researches ~\cite{dai2016cfo,golub2016character,mohammed2017strong,ture2016no,yin2016simple} are the similar neural reasoning methods for single-relation KGQA. \hide{ \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{Figures/KEQA} \caption{\label{fig:KEQA} Illustration of the neural reasoning method KEQA for solving the single-relation questions~\cite{huang2019knowledge}.} \end{figure} } \vpara{Multi-hop Relation Question.} In addition to single-relation questions, EmbedKGQA~\cite{Saxena2020ImprovingMQ} is proposed to deal with the multi-hop relation questions. It employs ComplEx~\cite{Trouillon2016ComplexEF} to embed entities and relations in the complex space and applies the same ComplEx scoring function to predict the answers. Specifically, the input question $q$ is first embedded by RoBERTa~\cite{Liu-2019}, and then projected by a feed-forward neural network into the complex space. Then a score $\phi(\mathbf{h},\mathbf{q},\mathbf{a})$ is calculated for each triplet of a topic entity, a question and an answer such that $\phi(\mathbf{h},\mathbf{q},\mathbf{a})>0$ if $a$ is an answer entity and $\phi(\mathbf{h},\mathbf{q},\mathbf{a})<0$ for $a$ is not, where $\mathbf{h}$, $\mathbf{q}$ and $\mathbf{a}$ are the embeddings for the topic entity, question and answer respectively. EmbedKGQA selects the entity with the highest score as the answer. Figure~\ref{fig:EmbedKGQA} illustrates the basic idea of EmbedKGQA. Other works such as \cite{Chen2019BidirectionalAM, Dhingra2020DifferentiableRO,Niu2020JointSA} are similar works for multi-hop KGQA. \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{Figures/EmbedKGQA} \caption{\label{fig:EmbedKGQA} Illustration of the neural reasoning method EmbedKGQA for solving the multi-hop relation questions~\cite{Saxena2020ImprovingMQ}.} \end{figure} \vpara{Complex-logic Question.} KEQA and EmbedKGQA cannot handle complex logical questions, because these queries involve the logical operations that will result in multiple entities at each hop. To address this defect, some researches represent the logic operations as the learned geometric operations. For example, Hamilton et al.~\cite{Hamilton2018EmbeddingLQ} propose a neural reasoning model GQE (i.e., graph query embeddings) to deal with the conjunctive logic queries. On the basis of their work, Q2B (QUERY2BOX) proposed by Ren et al.~\cite{ren2019query2box} fills the gap in disjunctive queries. Both GQE and Q2B assume that a complex logical question can be represented as a DAG. They both start with the embeddings of the topic entities and then iteratively apply their proposed geometric operations to generate the embedding of the query, which are then used to predict the answer entities according to their similarities. The two proposed geometric operators in GQE are the geometric projection operator $P$ and the geometric intersection operator $I$, where $P$ is responsible for projecting a query embedding $\mathbf{q}$ of the last hop according to the relations of the outgoing neighbors to obtain the embedding $\mathbf{q}'$ of the current hop, and $I$ aggregates the embeddings of all the incoming neighbors of a node in the DAG to simulate the logic conjunction operator. Specifically, $P$ and $I$ are implemented as: \beqn{ P(\textbf{q},r) &=& \mathbf{R_rq},\\ \nonumber I(\{\textbf{q}_1,...,\textbf{q}_n\}) &=& \mathbf{W_r}\Psi(NN_k(\textbf{q}_i),\forall i=\{1,...,n\}) \nonumber } \noindent Where $\mathbf{R_r,W_r}$ are trainable parameter matrices for relation $r$, $NN_k$ is a k-layer feedforward neural network and $\Psi$ is a symmetric vector function (e.g., an elementwise mean or min of a set over vectors). However, GQE embeds a question into a single point in the vector space, which is problematic because there are usually multiple immediate entities when traversing the KGs for answering questions. And it is not clear how to effectively model a set with a single point. Also, it is unnatural to define the logical operation of two points in the vector space. Thus, Q2B is proposed to embed a query as a box in which the set of points correspond to the answer entities of the query. A box is represented by the embedding of the center and the offset of the box, which models a set of entities whose vectors are inside the box. Each relation is associated with a box embedding. Based on the definition of the box, given an input box embedding $\mathbf{p}$ and a relation embedding $\mathbf{r}$, the geometric projection operator can be simply represented as $\mathbf{p}+\mathbf{r}$, where the centers and the offsets of them are summed respectively. Then the intersection of a set of box embeddings is calculated by performing attention over the box centers and shrinking the box offset using the sigmoid function. As for the union operation, since boxes can be located anywhere in the vector space, the union of two boxes would no longer be a simple box. To rectify this issue, Q2B transforms the query into Disjunctive Normal Form (DNF), i.e. disjunction of conjunctive queries, such that the union operation only appears in the last step. Then a DNF query can be solved by firstly representing each conjunctive query and then simply aggregating their results, for example, taking the nearest point of the boxes of all the conjunctive queries. However, the negation operation is not involved in the above two models. Both GQE and Q2B learn geometric operators to simulate logic operators, which, however, are not faithful to deductive reasoning and fail to find entities logically entailed as answers, due to the fact that they casually use spatial operations hoping to achieve logic reasoning. Thus, EmQL~\cite{Sun2020FaithfulEF} can obtain faithful embeddings by proposing five operators for reasoning, including set intersection, union, difference, relation following and relational filtering. \vpara{Summary.} Although the neural reasoning methods can deal with the three kinds of questions, the complex questions with different constraints are not totally solved by the neural reasoning methods (Cf. Table~\ref{tb:constraints} for details). And similar to KG completion, the neural reasoning methods also lack the interpretation for KGQA. \subsubsection{Symbolic-driven Neural Reasoning} \label{sec:symbolic_driven_neural_reasoning} \input{symbolic_driven_neural_reasoning.tex} \subsubsection{Symbolic-driven Probabilistic Reasoning} \label{sec:symbolic_driven_probabilistic_reasoning} \input{symbolic_driven_probabilistic_reasoning.tex} \subsubsection{Neural-driven Symbolic Reasoning} \label{sec:neural_driven_symbolic_reasoning} Neural-driven symbolic reasoning aims to derive the logic rules, where the neural networks are incorporated to deal with the uncertainty and the ambiguity of data, and also reduce the search space in symbolic reasoning. The basic idea is to extend the multi-hop neighbors around the head entity and then predict the answers included in these neighbors. We further divide neural-driven symbolic reasoning methods into path-, graph- and matrix-based framework according to the number of the extended neighbors in each step. \vpara{Path-based Reasoning.} \label{sec:path-based-reasoning} \input{path_reasonsing.tex} \vpara{Graph-based Reasoning.} \label{sec:graph_based_reasoning} \input{graph_reasoning.tex} \vpara{Matrix-based Reasoning.} \label{sec:matrix_based_reasoning} \input{matrix_reaonsing.tex} \subsection{Neural-Symbolic Reasoning} \label{sec:neural_symbolic_reasoning_for_QA} Neural-symbolic reasoning combines the advantages of both the neural reasoning and the symbolic reasoning for KGQA. These hybrid methods generally fall into two categories: the neural-enhanced symbolic reasoning which only targets at parsing the questions, or the end-to-end reasoning which parses the questions and retrieves the answers simultaneously. \subsubsection{Neural-enhanced Symbolic Reasoning} Neural-enhanced symbolic reasoning still parses the given question into a query graph. After parsing, a neural network is leveraged to evaluate whether the parsed query graph is relevant to the given question. \vpara{Single-relation Question.} Yih et al.~\cite{Yih2014} solve the single-relation question by completing two tasks: linking the mention in the question to an entity in KGs as the topic entity, and mapping the relation pattern described by the question to a relation in KGs. For example, given a question such as ``\textit{When were DVD players invented?}", the paper first extracts the mention ``\textit{DVD players}" and derives the relation pattern ``when were X invented", and then links ``\textit{DVD players}" to the entity ``\textit{dvd-player}" and also maps ``when were X invented" to the relation ``\textit{be-invent-in}". Once the topic entity and the relation are detected, the answer to the question can be directly queried by the relation-entity triple ``\textit{be-invent-in}(\textit{dvd-player},?)" in the KGs. To extract the mention and derive the relation pattern, the authors simply enumerate all the combinations. The key point is to determine the mapping between the extracted mention and the entity as well as the mapping between the derived pattern and the relation. To achieve the goal, the authors propose a CNN model to take the sequential tokens in a mention or a relation pattern as input and output the corresponding embedding, which is then compared with the embedding of the ground truth entity or relation in KGs. \vpara{Multi-hop Question.} In comparison with the simple questions, the searching space grows exponentially if the given question involved multi-hop relations. To tackle the multi-hop relation questions, instead of generating the whole query graph at once, MULTIQUE~\cite{bhutani2020answering} breaks the original question into simple partial queries and builds sub query graphs for partial queries one by one. The search space is shrinked since each time when extending the whole query graph by a new sub-query graph, the model only needs to consider the immediate answers queried by the previous most matched sub-query graph. In the graph generation process, how to measure the quality of a sub-query graph is a key problem to be solved. The authors apply an LSTM model to encode the token sequence of the given question, where an attention mechanism is incorporated to emphasize a particular part of the question which is expected to be represented by the current sub-query graph. Meanwhile, the relation and the constraint in each sub-graph are also encoded by the identification and the tokens. Once the embeddings of the original question and the sub-query graph are encoded, they are concatenated and fed to an MLP, which outputs a scalar to reflect the similarity between the question and the sub-query graph. \vpara{Complex-logic Question.} Bao et al.~\cite{bao2016constraint} further deal with questions with multiple constraints, which are presented in Table~\ref{tb:constraints}. They first transform a question into a multi-constraint query graph, then propose a Siamese convolutional neural networks to calculate the similarity between the query graph and the input natural language question, and finally execute the top-ranked query graph on KGs by instantiating all variable nodes according to the constraints in order. The multi-constraint query graph contains two types of nodes, where a constant node represents a ground entity in KGs such as ``Barachk Obama" or an attribute value such as ``1961", and a variable node represents an unknown entity or unknown attribute value. The graph also contains two types of edges where a relational edge represents a relation such as ``birthday" in KGs and a functional edge represents a functional predicate of a truth such as $<$ in the truth $\langle 2000,<, 2001\rangle$. To construct the query graph, an entity linking method proposed by~\cite{yang-chang-2015-mart} is leveraged to detect topic entities from the given question. For each topic entity, one-hop relations or two-hop relations are extended from it to form a basic query graph, and then different types of constraints in Table~\ref{tb:constraints} are detected from the question and binded to the basic query graph. Later, instead of adding constraints only after relation paths have been constructed, Lan et al.~\cite{lan-jiang-2020-query} propose a method to incorporate constraints and extend relation paths simultaneously, which can effectively reduce the search space. \subsubsection{End-to-end Reasoning} End-to-end reasoning parses the questions and retrieves the answers in a unified model. According to the form of the connections between the topic entities and the answers, we categorize the end-to-end reasoning into path-based and graph-based methods. \vpara{Path-based Reasoning.} Path-based methods employ a hop-by-hop path search over KGs, which usually contains three stages of dealing with the input question, reasoning over the KGs and predicting the answers. \begin{figure*}[t] \centering \includegraphics[width=0.8\textwidth]{Figures/IRN} \caption{\label{fig:IRN} Illustration of IRN~\cite{zhou2018an}. Notation $\textbf{s}^h$ represents the state vector of the $h$-th hop, which is initialized by the embedding of the topic entity. $\textbf{g}^{h}$ is the vector of the probabilities to select each relation according to the $h$-th state vector, question embedding and each relation embedding. The question embedding is updated after each hop's selection.} \end{figure*} For example, IRN (Interpretable Reasoning Network)~\cite{zhou2018an} proposes three modules corresponding to the above three stages in a unified model. The input module initializes the question by the embeddings of the words in the question and updates the question's embedding hop-by-hop according to inference results of the reasoning module. The reasoning module initializes its state by the topic entity of the question and predicts the embedding of the relation $\hat{\mathbf{r}}^h$ at the $h$-th hop based on the question's embedding $\mathbf{q}^{h-1}$ and the state vector $\mathbf{s}^{h-1}$ at the $(h-1)$-th hop, i.e., \beqn{ \label{eq:IRN_predict_relation} g_j^h \!\!\!\!\!&=&\!\!\!\!\! \text{softmax}((\mathbf{M}_{rq} \mathbf{r}_j)^T \mathbf{q}^{h-1} \!\! + \!\! (\mathbf{M}_{rs} \mathbf{r}_j)^T \mathbf{s}^{h-1}),\\ \nonumber \hat{\mathbf{r}}^h \!\!\!\!\!&=&\!\!\!\!\! \sum_{j} g_j^h * \mathbf{r}_j, } \noindent where $\mathbf{r}_j$ is the embeding of the $j$-th relation in KGs, $g_j^h$ is the probability of selecting the $j$-th relation in KGs, and $\mathbf{M}_{rs},\mathbf{M}_{rq}$ are the project matrices mapping $\mathbf{r}$ from the relation space to the state space and to the question space respectively. Then the predicted relation $\hat{\mathbf{r}}^h$ is utilized to update the state vector and the question embedding by: \beqn{ \label{eq:IRN_update_state} \mathbf{s}^h &=& \mathbf{s}^{h-1} + \mathbf{M}_{rs} \hat{\mathbf{r}}^h,\\\nonumber \label{eq:IRN_update_question} \mathbf{q}^h &=& \mathbf{q}^{h-1} - \mathbf{M}_{rq} \hat{\mathbf{r}}^h. } In the above equation, in order to pay attention to different parts of the question at each hop, the predicted relations from previous hops are removed from the question at each hop. The answer module predicts an entity conditioned on the similarity between its pre-trained embedding and the reasoning state at the last hop. In addition to the answer entity, the entities at the intermediate hops are also predicted and evaluated to improve the answer prediction performance, i.e., \beqn{ \mathbf{e}^h &=& \mathbf{M}_{se} \mathbf{s}^h,\\\nonumber o_j^h &=& P(a^h = e_j | \mathbf{s}^h) = softmax(\mathbf{e}_j^T \mathbf{e}^h), } \noindent where $\mathbf{M}_{se}$ is the projection matrix mapping $\mathbf{s}^h$ from the state space to the entity space and $\mathbf{e}_j$ is the pre-trained embedding of the $j$-th entity in KGs. Figure~\ref{fig:IRN} illustrates the three modules in IRN. IRN assumes that the ground truth paths for answering the questions are also observed, thus the intermediate entities and the answer entities can both supervise the model training process. However, in most cases, we can only obtain the answers to the questions, without knowing the reasoning paths. To deal with the challenge, SRN (Stepwise Reasoning Network)~\cite{qiu2020stepwise} formulates the reasoning process as a Markov decision process where the answer entity can provide the delayed reward to the decision of the relation at each hop. In addition to the delayed reward, SRN also incorporates the intermediate reward to overcome the delayed and sparse rewards. To emphasize different parts of a question, instead of removing the predicted relations from the question by IRN, SRN employs the attention mechanism to decide which part should be focused on at present. ~\cite{Neelakantan2015Compositional} ~\cite{Das2017MINERVA} ~\cite{Das2017chain} are similar path-based works. The path-based reasoning methods can obtain explicit paths, i.e., logic rules for solving multi-hop QA. These methods usually employ deliberate analysis on the input question in order to focus on different parts of the question at each hop. Meanwhile, since there is a need for reasoning over several hops, intermediate reward can be powerful signals to supervise the whole training process. \vpara{Graph-based Reasoning.} Instead of extending a single path from the topic entity to the answer, the graph-based reasoning methods extend a subgraph around the topic entity, which is more expressive than a single path. The general idea of graph-based reasoning is to extend a subgraph and then reason the answer in it by the recent technique of graph representation learning. \begin{figure}[t] \centering \includegraphics[width=0.5\textwidth]{Figures/graphnet} \caption{\label{fig:graphnet} Illustration of Graft-Net ~\cite{sun-etal-2018-open}. Given the topic entity ``Lakers" in a question, Graft-Net first extracts the subgraph around the topic entity and then performs a variant GNN model to represent each node in the subgraph. } \end{figure} Graft-Net~\cite{sun-etal-2018-open} is a representative graph-based reasoning model. It first performs a Personalized PageRank (PPR)~\cite{Haveliwala2002TopicsensitiveP} around the topic entities in the question and then incorporates other entities that might be an answer to the question. In PPR, the relations in KGs which are more relevant to the question are weighted higher. After running PPR, they retain the top entities by PPR score, along with all the relations between them. Graft-Net not only leverages the original KGs, but also incorporates Wikipedia text copus as the additional source to infer the answers. When extracting a subgraph from the text corpus, both the most relevant sentences to the question and any entities linked to these sentences are extracted as the nodes, and then the relations from the KGs among these entities, plus the mention links between the sentences and the entities are extracted as the edges in the subgraph. The subgraphs extracted from the KGs and the text corpus are merged together to construct the final subgraph. Since the final subgraph is a heterogeneous graph that includes both the entities and the sentences as the nodes, Graft-Net performs a variant GNN model to represent different types of nodes by different update rules, i.e., the embedding of an entity $v$ at the $l$-th step is updated as follows: \beq{ h_v^{(l)}=\text{FFN} \begin{pmatrix} \begin{bmatrix} h_v^{(l-1)} \\ h_q^{(l-1)} \\ \sum_{r} \sum_{v' \in N_r(v)} \alpha_r^{v'} \psi_r(h_{v'}^{(l-1)}) \\ \sum_{(d,p) \in M(v)} H_{d,p}^{(l-1)} \\ \end{bmatrix} \end{pmatrix} } \noindent where the first two terms correspond to the entity embedding and the question embedding, respectively, from the previous layer. The third term aggregates the states from the entity neighbors of any relations of the current entity, i.e. $N_r(v)$, after scaling with an attention weight $\alpha_r^{v'}$ and applying relation specific transformation $\psi_r$ proposed in R-GCN~\cite{schlichtkrull2018modeling}. The last term aggregates the states of all tokens that correspond to the mentions of the entity $v$ among the documents in the subgraph. In the above equation, $M(v) = \{(d,p)\}$ is the set of document-position pairs, where each pair $(d,p)$ indicates $d$ mentions entity $v$ at the position $p$. The embedding of a document $d$ in a subgraph at the $l$-th step is updated by: \beqn{ \tilde{H}_{d,p}^{(l)} &=& \text{FFN}(H_{d,p}^{(l-1)},\sum_{v \in L(d,p)} h_v^{(l-1)}) \\\nonumber H_d^{(l)} &=& \text{LSTM}(\tilde{H}_{d,p}^{(l)}) } \noindent where $L(v) = \{(d,p)\}$ is the set of entities linked to entity $v$ at position $p$ at document $d$. The above equations first aggregate over the entity states coming in at each position separately and then aggregate states within the document using an LSTM network. Graft-Net predicts whether one entity in the subgraph is the answer based on the entity's embedding of the last step. Figure~\ref{fig:graphnet} illustrates the basic idea of Graft-Net without the text information. However, the question-specific subgraphs the Graft-Net builds heuristically are far from optimal, i.e., they are often much larger than necessary, and sometimes do not contain the correct answer. Thus, PullNet~\cite{SunACL2019} proposes a policy function to learn how to construct the subgraph, rather than using an ad-hoc subgraph-building strategy. The classification model used to predict the answer in the subgraph is the same as Graft-Net. Since the intermediate entities in the subgraph are latent, PullNet proposes a weak supervision method to train the policy function. The general idea is to find all shortest paths between topic entities and the answer entities and mark the entities in such shortest paths as the ground truth intermediate entities. \hide{ In subgraph construction part, to overcome KB’s incompleteness, Graft-Net ( Graphs of Relations Among Facts and Text Networks ) ~\cite{sun-etal-2018-open} and PullNet ~\cite{SunACL2019} incorporate a large text corpus to answer the questions. Due to their large scale, it’s intractable to take the whole KG and corpus into consideration, so in first step, they construct a question-specific subgraph($\mathcal{G}_q$). To extract the subgraph, Graft-Net applies two parallel pipelines, one over the KB and the other over the corpus. In KB retrieval, Graft-Net performs ad hoc Personalized PageRank(PPR) ~\cite{Haveliwala2002TopicsensitiveP} algorithm starting from seed entities in the question. And in text retrieval, it employs information retrieval techniques to add relevant sentences to the subgraph. Figure~\ref{fig: Question Subgraph of Graft-Net } illustrates the Question Subgraph of “Who voiced Meg in Family Guy?”. However, Graft-Net’s ad hoc subgraph construction method often retrieves a subgraph much larger than necessary. So, PullNet incorporates a policy function to learn how to construct the subgraph. The strategy can be divided into three steps. First, classify the entity nodes in the subgraph(initialized with the question and question entities) and select those with probability larger than a threshold $\epsilon$. Second, incorporate facts and documents relevant to selected entities. Third, extract entities from new documents and extract head and tail of new facts. Fourth, add all the newly retrieved nodes and relevant edges to the subgraph. It’s an iterative construction process, for example, T iterations for T-hop questions. \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{Figures/Graft-Net} \caption{\label{fig: Question Subgraph of Graft-Net } Illustration of Question Subgraph in Graft-Net ~\cite{sun-etal-2018-open}.} \end{figure} In graph representation learning part, PullNet follows the representation and reasoning scheme as Graft-Net. Unlike previous graph representation learning works which follow standard gather-apply-scatter methods, there are three important problems need to be solved. First, how to initialize and update representations with heterogeneous nodes, for example, entity node and text node. Second, how to embody the reasoning process, for example, a multi-hop reasoning path starting from the seed entities. Third, how to exploit the question representation to supervise the reasoning, that is to say, make the graph representation learning conditioned on the question. Graft-Net proposes several modifications to previous works to address these three problems. Graft-Net introduces attention mechanisms to address the third problem. When propagating, the relation type of the edge between two nodes is considered. More specifically, the relation $r$ interacts with the current question vector to obtain an attention weight ($\alpha_r^{v’}$) which ensures the propagation along the edges more relevant to the question. It is calculated as follows: \beq{ \alpha_r^{v} = softmax(\mathbf{x}_r^T h_q^{(l-1)}) } Where $h_q^{l-1}$ is the question vector in layer $l-1$ which is initialized by LSTM and updated by vectors of seed entities, and $\mathbf{x}_r$ is pre-trained embedding for relation $r$. For the second problem, Graft-Net uses PPR to obtain the PageRank score ($pr_v^l$) which is the weight of the node $v$ in layer $l$. It not only performs directed propagation, but also measures the weight of the current entity. It updates as follows: \beq{ pr_v^{(l)} = (1-\lambda)pr_v^{(l-1)} + \lambda \sum_{r} \sum_{v' \in N_r(v)} \alpha_r^{v'} pr_{v'}^{(l-1)} } Where $N_r(v)$ denotes the neighbors of $v$ along incoming edges of relation $r$. Based on above solutions, Graft-Net proposes different update rules for heterogeneous nodes in subgraph. Nodes of entities are initialized as pre-trained embeddings ($h_v^{(0)}$), and nodes of documents as the output of LSTM ($H_d^{(0)}$, $H_{d,p}^{(l)}$ is the embedding of p-th word in $d$ ). They are updated as follows: $$ h_v^{(l)}=FFN \begin{pmatrix} \begin{bmatrix} h_v^{(l-1)} \\ h_q^{(l-1)} \\ \sum_{r} \sum_{v' \in N_r(v)} \alpha_r^{v'} \psi_r(h_{v'}^{(l-1)}) \\ \sum_{(d,p) \in M(v)} H_{d,p}^{(l-1)} \\ \end{bmatrix} \end{pmatrix} $$ \beqn{ \tilde{H}_{d,p}^{(l)} = FFN(H_{d,p}^{(l-1)},\sum_{v \in L(d,p)} h_v^{(l-1)}) \\ H_d^{(l)} = LSTM(\tilde{H}_{d,p}^{(l)}) } Where $M(v) = \{(d,p)\}$ is the set of document $d$ and position $p$ which mentions entity $v$, and $L(v) = \{(d,p)\}$ is the set of entities at $p$ in $d$. $\psi_r$ are transformations which make the interaction of $\mathbf{x}_r$ and entity vectors. In answer selection part, Graft-Net uses the final layer representation to perform binary classification of the entity nodes to identify whether it’s the answer or not. \beq{ Pr(v \in {\{a\}}_q | \mathcal{G}_q,q) = \sigma(w^T h_v^{(L)} + b) } Where $\{a\}_q$ is the answer set of the question and $\sigma$ is a sigmoid function. } Graft-Net and PullNet assume the topic entities are given, however, in many cases, only the questions are provided. Thus, VRN (Variational Reasoning Network)~\cite{zhang2018variational} models the topic entities as hidden variables and proposes two probabilistic modules in a unified architecture, one for topic entity recognition ($P(y | q)$) and the other for logic reasoning ($P(a | y,q)$), where $y$ indicates a hidden topic entity, $q$ refers to the query and $a$ refers to the answer. The two modules are jointly trained such that they can coordinate with and benefit from each other. However, the reasoning-graph is also an ad-hoc subgraph. Instead of performing PPR to build the subgraph as Graft-net does, VRN performs topological sort within $T$ hops starting from a topic entity $y$ to build the scope $\mathcal{G}_y$. For each potential answer $a \in \mathcal{G}_y$, the reasoning graph $\mathcal{G}_{y \rightarrow a}$ is represented as the minimum subgraph that contains all the paths from $y$ to $a$ in $\mathcal{G}_y$. Then VRN proposes a ``forward graph embedding" method to embed the reasoning-graph for each answer $a$ recursively using its parents' embeddings. Finally, the similarity between the reasoning-graph embedding and the question representation is calculated as the score to predict the answer. Other similar graph-based works include~\cite{Bordes2014QuestionAW} ~\cite{Hu2018ASF}. \vpara{Summary.} The first kind of the neural-symbolic reasoning for KGQA, i.e., the neural-enhanced symbolic reasoning, leverages the neural networks to evaluate the similarity between the parsed query graph and the natural language question. These methods usually need the ground truth of the query graphs for the questions, which are not easy to be annotated. The second kind of the neural-symbolic reasoning for KGQA, i.e., the end-to-end reasoning, directly aligns the questions with the answers, where the answers are easily obtained and can be used as the ground truth to supervise the alignment. The objective of these methods is to represent the inferred path or graph into an embedding vector, based on which the answer can be determined. The reasoned paths/graphs can be viewed as the explanation for the reasoning results. However, the operations over the embeddings can only support the single-relation and multi-hop relation questions. It is still unknown how to address the complex logic questions by the end-to-end reasoning methods. \section{Background Knowledge and Problem Definition} \label{sec:preliminaries} In this section, we first introduce the background information about knowledge graph, inductive logic programming, and Markov network, and then give the definition of knowledge graph reasoning. \subsection{Knowledge Graphs (KGs)} \label{sec:kgs} We denote a knowledge graph $G$ as a set of facts, each represented by a triplet $(h,r,t )$, where $h$ is a head entity, $r$ is a relation and $t$ is a tail entity. In Figure~\ref{fig:reasoning_example}, (LeBron, part\_of Lakers) is an example of a triplet, where LeBron is the head entity, part\_of is the relation and Lakers is the tail entity. \subsection{Inductive Logic Programming (ILP)} \label{sec:ILP} Inductive Logic Programming (ILP) aims at seeking underlying patterns formulated by logic programs/rules/formulas shared in the data. It is one of the rule-based learning methods which derive a set of if-then logic rules to describe the positive instances but not the negative instances. Most ILP works constrain the logic rule to be Horn clause/rule. A Horn rule consists of a head and a body, where the head is a single atom and the body is flat conjunction over several atoms. A Horn rule $\gamma$ can be formulated as: \beq{ \label{eq:rule} \gamma:A(\alpha_1,\cdots, \alpha_m) \rightarrow \alpha, } \noindent where $\alpha$ is called head atom and $\alpha_1$, $\cdots$, $\alpha_m$ ($m \geq 0 $) are body atoms. $A$ is the rule body which is usually defined as a conjunction normal form (CNF) that uses logical operations $\{\land, \lor, \neg \}$ to combine the body atoms together. The rule body can also be referred to as a formula. If the rule body $A$ on the left is true, then the head atom on the right is also true. An atom $\alpha$ is defined as a predicate symbol $P_i$ that acts as a function to map the set of variables $\{ x_1, x_2, \cdots, x_n \}$ to true or false: \beq{ \label{eq:atom} \alpha \equiv P_i (x_1, x_2,\cdots, x_n ). } \noindent Although there can be multiple variables in a predicate, we usually only consider the simple unary and binary predicates, i.e., $n=1$ and $n=2$. For example, $\text{Person}$ is a unary predicate only applied to a single variable. The atom $\text{Person}(x)$ is true if $x$ is a person. $\text{Mother}$ is a binary predicate applied to two variables. The atom $\text{Mother}(x, y)$ is true if $x$ is the mother of $y$. When all the variables in an atom $\alpha$ are instantiated by constants, $\alpha$ is called a ground atom. In a knowledge graph, a relation $r$ can be viewed as a binary predicate; that is, $r(x,y)$ is an atom with two arguments $x$ and $y$. A triplet $(h,r,t) \in G$ can be taken as a ground atom $r(h,t)$ which applies a relation $r$ to a pair of entities $h$ and $t$. Given a set of pre-defined predicates $\mathcal{P}$, ground atoms $\mathcal{G}$, positive instances $\mathcal{S}$ and negative instances $\mathcal{N}$, ILP aims at constructing a set of rules to explain the positive instances and reject the negative instances. We take the example of learning which natural numbers are even from \cite{evans2018learning} to explain ILP. The predicate set is defined as: \beq{ \mathcal{P} = \{\text{zero}, \text{succ}\}, \nonumber } \noindent where $\text{zero}(X)$ is an unary predicate which is true if $X$ is 0, $\text{succ}(X, Y)$ is a binary predicate which is true if $X$ is the successor of $Y$. The ground atoms are: \beq{ \mathcal{G} = \{\text{zero}(0),\text{succ}(0,1),\text{succ}(1,2), \cdots\}. \nonumber } The positive and negative instances of the even predicate are: \beqn{\nonumber \mathcal{S} &=& \{\text{even}(0), \text{even}(2), \text{even}(4), \cdots\}, \\ \nonumber \mathcal{N} &=& \{\text{even}(1), \text{even}(3), \text{even}(5), \cdots\}. \nonumber } The solution of rules for the even predicate is: \beqn{\nonumber \text{even}(X) &\leftarrow& \text{zero}(X), \\\nonumber \text{even}(X) &\leftarrow& \text{even}(Y) \land \text{succ2}(Y,X), \\\nonumber \text{succ2}(X,Y) &\leftarrow& \text{succ}(X,Z) \land \text{succ}(Z,Y). \nonumber } \noindent where $\text{succ2}(X,Y)$ is an auxiliary predicate which is true when $X$ is the two-hop successor of $Y$. We can see that when the above rules are applied deductively to the ground atoms $\mathcal{G}$, they can produce $\mathcal{S}$ but not $\mathcal{N}$. Two kinds of approaches are usually used to derive rules, where the top-down approach begins from general rules and adds new atoms to improve the coverage precision of positive instances~\cite{clark1989cn2,michalski1986multi}, while the bottom-up approach begins from the specific rules and deletes atoms to extend the coverage rate of the rules~\cite{plotkin1970note,plotkin1971further}. \subsection{Markov Network} Markov network, also known as Markov random field, tries to model the knowledge graph using the joint distribution of a set of variables $X=(X_1, X_2, ..., X_n)$~\cite{pearl2014probabilistic}. Markov network is an undirected graph where each node represents a variable. For cliques in the graph, a nonnegative real-valued potential function $\phi_c$ is defined and the joint distribution is represented as: \beq{ P( X=x) = \frac{1}{Z} \prod_{c}\phi_c( x_{c}) } \noindent where $x_c$ reflects the state of the variables appearing in the $c$-th clique. $Z = \sum_{x \in \mathcal{X}}\prod_{c}\phi_c(x_c)$ is the partition function for normalization. Markov networks are usually represented as log-linear models, with each clique potential replaced by an exponentiated weighted sum of the state's feature: \beq{ P(X=x) = \frac{1}{Z}\exp(\sum_{c} w_{c}f_{c}(x_c)) } \noindent where $f_c$ is the feature function defined on the clique $c$ and $w_c$ is the corresponding vector of weights. \hide{ \subsection{Knowledge Graph Reasoning} \label{sec:knowledge_graph_reasoning} Knowledge graph reasoning is to deduce certain tail entities over the knowledge graphs as the answers to the given query. According to the types of query, we can categorize the knowledge graph reasoning into knowledge graph completion (KGC) and knowledge graph question answering (KGQA). The query in KGC is a pair of a head entity $h$ and a relation $r$. Given $(h,r)$, KGC aims to find the right tail $t$ in $G$ that satisfies the triplet $(h,r,t)$. For example in Figure~\ref{subfig:KGC-example}, given the queried relation ``belong\_to" and the head entity ``Rudy\_Giulian", we aim to infer the tail entity ``U.S. Government" according to the existing triplets such as (Rudy\_Giulian, collaborate\_with, John\_McCain) and (John\_McCain, belong\_to, U.S. Government). The query in KGQA is a natural language question $q$. Given $q$, KGQA targets at finding the right tail $t$ in $G$ that satisfies the question $q$. For example in Figure~\ref{subfig:KGQA-example}, given the question ``What are the genres of movies written by Louis Mellis?" and the head entity ``Louis Mellis", we aim to infer the answer ``Crime" according to the existing triplets such as (Louis Mellis, written\_by$^{-1}$, Gangster No.1), (Gangster No.1, has\_tags, gangs), (gangs, has\_tags$^{-1}$, The Departed) and (The Departed, has\_genre, Crime). For both KGC and KGQA, we can further divide the reasoning methods into pure neural reasoning, pure symbolic reasoning, and hybrid neural-symbolic reasoning. \begin{figure*} \centering \subfigure[KGC~\cite{Lin2018multi}]{\label{subfig:KGC-example} \includegraphics[width=0.45\textwidth]{Figures/KGC-example} } \subfigure[KGQA~\cite{Saxena2020ImprovingMQ}]{\label{subfig:KGQA-example} \includegraphics[width=0.45\textwidth]{Figures/KGQA-example} } \caption{\label{fig:reasonig-example} Examples of knowledge graph completion and question answering.} \end{figure*} } \subsection{Symbolic Reasoning} \label{sec:symbolic_reasoning_for_QA} Symbolic reasoning methods for KGQA fall into two major categories --- semantic parsing ones and template-based ones. Both aim at generating structured queries for unstructured natural language questions. However, they differ in the way to understand the natural language questions. The semantic parsing methods employ NLP tools to convert the question into the syntactic dependency representation, while the template-based methods use a large number of templates which consist of both the natural language pattern and the corresponding structured query pattern like SPARQL to decompose the complex question. \vpara{Semantic Parsing.} \begin{comment} \cite{berant-etal-2013-semantic} \vpara{Constraints.} We usually consider numerical comparison questions as asking about order, size of something or size relation of the same domain of different objects, etc. For example, we may ask "What is the third longest river in the world", or "How many countries are there in the world.". In recent research, numerical comparisons exist in the form of constraints in questions and QA systems. We only find that ~\cite{bao2016constraint} strengthenes the process of detecting, transformation and dealing about numerical comparasions. In this work, ordinal constraints aim to understand the numerals and superlative forms of adjectives and adverbs, with using manually collected vocabulary lists for detection. When ordinal constraints are detected and ready for binding, a new variable vertex is introduced and linked to current answer with a path whose word embedding similarity with the numerals or superlative words is the best. Aggregation constraints is also detected by particular phrases such as "how many", "the number of", etc and dealed by introducing a brand new function to calculate the size of answer set. The temporal constraints shouldn't be collected as the numerical comparasions strictly because it just involves the comparasion with time, specifically a constant. It's markable that the work we mentioned above can answer simple KGQA questions (one hop). The complex (multi-hop) KGQA system usually pass over the detailed process of dealing with constraints to emphasize their main idea. Moreover, many complex KGQA left out the problems with complex constraints in datasets. So we believe numerical comparison questions' detection and answering are still gaps in KGQA, which may attract more people to their future work. \end{comment} Semantic parsing methods target at parsing the input natural language question into a logic expression, based on which the answer to the question can be easily retrieved from the KGs. Different semantic parsing methods transform the natural language questions into different forms of logic expressions. For example, Kwiatkowksi et al.~\cite{kwiatkowksi2010inducing} follow combinatory categorial grammar (CCG)~\cite{bos-etal-2004-wide}, a linguistic formalism that couples syntax and semantics, to transform the questions. For example, for a sentence $x$ ``New York borders Vermont", following the CCG grammar, its corresponding logic expression is Next\_to(ny, vt). The target is to learn a function that maps a sentence $x$ to the logic expression $z$, where the function is learned by inducing CCG from the training data of $\{(x,z)\}$. The whole algorithm consists of two components, where the first one learns the CCG lexicon that is used to define the space of the predicates in the logic expressions, and the second one learns the parameters of the features reflecting the probability of the logic expressions. Berant et al.~\cite{berant2013semantic} follow Lambda Dependency-based Compositional Semantics ($\lambda$-DCS)~\cite{Liang2013} to transform the questions, in order to make existential quantification implicit, thus reducing the number of variables. For example, $\lambda x.\exists a.p_1(x,a) \land \exists b.p_2(a,b) \land p_3(b,e) $ is expressed compactly as $p_1.p_2.p_3.e$ by hiding the existential quantifications $\lambda$, $a$ and $b$. We give a real example of transforming the question ``Where does LeBron live" into the logic expression following $\lambda$-DCS in Figure~\ref{fig:SP}, where the blue labels indicate the composition rules and the red nodes denote the transformed logic expressions. The whole algorithm also consists of two components, where the first one maps the natural language phrases to the predicates in KGs based on some pre-defined lexicon mappings and a set of composition rules, and the second one is a log-linear model to learn the parameters of the features which reflect the probability of the transformed logic expressions. This method differs from the method presented in~\cite{kwiatkowksi2010inducing} in two ways. First, they propose a bridging function to deal with the ambiguity of the predicates in natural language questions through generating predicates compatible with the neighboring predicates. Second, the logic expressions $D(x)=\{d\}$ are assumed to be unobserved, and only the question-answer pairs $\{(x_i,y_i)\}$ can be obtained to supervise the logic transformation. Thus, the log-likelihood of the correct answer ($d.z = y_i$), summing over the latent logic expression $d$, is optimized: \beq{ \mathcal{O}(\theta)=\sum_{i=1}^n\log\sum_{d\in D(x): d.z=y_i} p_\theta(d|x_i), } \noindent where $p_\theta(d|x_i)$ is the probability of generating the logic expression $d$ from the sentence $x_i$ given the parameters $\theta$. Dubey et al.~\cite{dubey2016asknow} follow natural language query formalization (NLQF) to transform the questions. They introduce a chunker-styled pseudo-grammar, named Normalized Query Structure (NQS), to parse each token in the natural language questions. Instead of using static templates, its syntax definition is dynamically fitted to the natural language sentence. For example, the question ``Desserts from which country contain fish." is finally parsed as "[wh = which][R1 = null][D = country][R2 = from][I1 = dessert][R3 = contain][I2 = fish]". Once the NQS instance is obtained, it is fed into the NQS2SPARQL module to generate the SPARQL query, where the SPQRAL is a semantic query language for databases. This module analyzes the NQS instances and then maps the entities in the NQS instances to the entities in KGs. Other similar semantic parsing methods can be referred to~\cite{kate2005learning,riedel2010modeling, schmitz2012open,wong2007learning,xu2014answering,yahya2012natural,zettlemoyer2009learning,zou2014natural}. \hide{ \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{Figures/PA} \caption{\label{fig:PA} Pipeline of NLQF AskNow.} \end{figure} } \vpara{Template-based Parsing.} Template-based parsing usually contains an offline stage and an online stage, where the offline stage targets at generating a collection of templates and the online stage aligns the new arriving question to an existing template, and then aims to retrieve the answer from the KGs based on the matched template. The templates can be mainly summarized into two forms: one in natural language pattern and the other in the structured graph pattern. Both of them correspond to the structured queries such as SPARQL, which can be directly executed on KGs to retrieve the answers. Thus there are two main problems in template-based parsing methods: the first one is how to generate the templates and the second one is how to match questions with templates. \hide{ \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{Figures/UncertainTQA} \caption{\label{fig:UncertainTQA}Template generation in UncertainTQA~\cite{Zheng2015HowTB}.} \end{figure} } As one of the pioneering work, Bast and Haussmann~\cite{Bast2015MoreAQ} manually construct three simple question templates without QA corpora. Since it is expensive to manually define these templates, especially for open-domain QA systems over large KGs, later work studies how to generate templates automatically. For example, Zheng et al. propose UncertainTQA~\cite{Zheng2015HowTB} to generate templates from the collected natural language questions and SPARQL queries on KGs. It first employs the existing method such as~\cite{Zou2014NaturalLQ} to translate each natural language question into a semantic query graph $g$. Meanwhile, a SPARQL query graph $q$ can be also constructed for each SPARQL query. Then graph edit distance (GED) is used to calculate the graph similarity between the query graph $g$ and the SPARQL query graph $q$. A template is defined as a pair of a semantic query graph $g$ and its most similar SPARQL query graph $q$. Based on the derived templates, given a new question, its most similar SPARQL query graph will be found and issued to the KGs to retrieve the answers. In the above process, the semantic query graph is uncertain, i.e., each node/edge has multiple possible labels with different probabilities, because of the semantic ambiguity. For example, the question ``which actress from the USA is married to Michael Jordan born in a city of NY" may be mapped to three different ``Michael Jordan" and two different ``NY". Thus unlike the traditional GED algorithm, Uncertain TQA proposes a common structural subgraph(CSS)-based lower bound to avoid exhaustively enumerating every possible match of $g$, which is a uniform bound for GED. \hide{ \beqn{ Pr\{pw(g)\} = \prod_{\forall v \in pw(g)} l(v).p \\ SimP_\tau (q,g) = \sum_{pw(g) \in PW(g)} Pr\{pw(g)|ged(q,g) \leq \tau\} } Where $pw(g)$ is a possible world of uncertain graph $g$ and $Pr\{pw(g)\}$ the appearance probability of $pw(g)$. The CSS lower bound for GED is as follows: \beqn{ ged(q,g) \geq lb\_ged_{CSS}(q,g) \\\nonumber = |V| + |E| - \lambda_E(q,g) + \frac{dif(q,g)}{2} - \lambda_V(q,g),\\ dif(q,g) = \sum_{i=1}^m (d(u_i,q)\ominus d(v_i,g)) } Where $|V|$ denotes the larger number of the vertices of $q$ and $g$, $|E|$ denotes the number of edges of the larger one. $\lambda_E$ and $\lambda_V$ denote the common vertex and edge labels between q and g. And $a \ominus b = a-b(a>b)$, $a \ominus b = 0(a\leq b)$. $d(u_i,q)$ denotes i-th largest degree of $q$. Once the similar pair are found, the mappings between the two graphs will lead to templates. The process is illustrated in Figure ~\ref{fig:UncertainTQA}. } Similarly, QUINT proposed by Abujabal et al.~\cite{Abujabal2017AutomatedTG} translates the question into a dependency parse tree~\cite{Klein2003AccurateUP}. Instead of matching each question with a SPARQL query graph by UncertainTQA, QUINT retrieves the smallest subgraph connecting the entities in the question and the answers from the KGs, and then maps the graph with the dependency parse tree of the question. The alignment between the two graphs forms a template. QUINT formulates the alignment problem as constrained optimization and finds the best alignment using integer linear programming (ILP). \hide{ \begin{figure}[t] \centering \includegraphics[width=0.4\textwidth]{Figures/Aqqu} \caption{\label{fig:Aqqu}The manually constructed auestion templates in Aqqu~\cite{ Bast2015MoreAQ }.} \end{figure} } Both the above two methods generate templates in form of structured graphs. However, unlike a structured graph, a natural language template includes a natural language pattern and a corresponding SPARQL pattern. To generate the natural language template, one should first replace the entities in the question with their types, and then determine the relation type of the template. For example, for the question ``When was Barack Obama born?", a natural language pattern ``When was \$PERSON born?" is derived, which is also mapped to the predicate ``BirthPlace" and then is corresponded to the SPARQL pattern ``$<$Person$>$, birthPlace, ?place". TemplateQA~\cite{Zheng2018QuestionAO} and KBQA~\cite{Cui2017KBQALQ} are both this kinds of natural language templates. TemplateQA assumes that a natural language pattern is likely to be matched to a predicate if they are simultaneously shared by many entity pairs in KGs. KBQA proposes a probabilistic method to capture the matching likelihood between a natural language pattern and a predicate, where each natural language pattern $s$ is modeled as a hidden variable, and the maximum likelihood is adopted to estimate the matching probability $P(r|s)$. Given a set of derived templates, TemplateQA computes the Jaccard similarity coefficient between the question $q$ and the natural language template $t$. For complex questions, TemplateQA builds a semantic dependency graph (SDG) through matching each subsequence of $q$ with templates one by one. When one template is identified, the subsequence is removed and replaced with the answer type of the template. Thus during the decomposition, the type constraint between the two adjacent templates (i.e., the neighboring nodes in SDG) is naturally guaranteed. To reduce the search space, TemplateQA employs both type-based and order-based optimizations. The whole process of TemplateQA is illustrated in Figure~\ref{fig:TemplateQA}, which includes the offline templates generation based on the text corpus and the KGs, and the online SDG parsing for the input question based on the generated templates. Once the SDG is parsed, it is mapped to a SPARQL query, which is issued to the KGs. \begin{figure*}[t] \centering \includegraphics[width=\textwidth]{Figures/TemplateQA} \caption{\label{fig:TemplateQA}The framework of TemplateQA~\cite{Zheng2018QuestionAO}.} \end{figure*} The above methods deal with KGQA with complex questions in quite different approaches. For example, QUINT defines some dependency parse rewriting rules to get two separate propositions when facing relative clauses and coordinating conjunctions and then connect the two propositions with for example $conj$ or $pobj$ edges in the dependency parse tree, which enables it to answer conjunctive questions. KBQA decomposes the question into a chain of binary sub-questions where the answer of the last sub-question fills in the value of the variable in the next sub-question, which enables it to answer multi-hop questions. However, QUINT depends on the pre-defined rewriting rules and KBQA only supports multi-hop questions. Thus, compared with them, in TemplateQA, the sub-questions form a dependency graph, which is more expressive. In addition, ~\cite{Mazzeo2016AnsweringCN,TunstallPedoe2010TrueKO,Yahya2012NaturalLQ} are similar works which generate natural language templates while ~\cite{Unger2011PythiaCM,Unger2012TemplatebasedQA} generate structured graph templates. \hide{ \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{Figures/QUINT} \caption{\label{fig:QUINT}Rewriting rules of QUINT ~\cite{ Abujabal2017AutomatedTG }.} \end{figure} } \vpara{Summary.} Semantic parsing and template-based parsing are both symbolic ways to represent a question as a structured query. Semantic parsing directly learns a function to map the question to a structured query, while template-based parsing first generates a collection of templates and then maps the question to an existing template to obtain the structured query. These symbolic reasoning methods are good at dealing with complex logic questions, as the structured query can be trees or graphs, which are expressive enough to represent complex logic questions. However, similar to KGC, the symbolic reasoning methods cannot deal with the ambiguity of natural languages and the uncertainty of entities and relations.
{'timestamp': '2021-04-01T02:12:37', 'yymm': '2010', 'arxiv_id': '2010.05446', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05446'}
arxiv
\section{Introduction} \vspace{-1mm} \label{sec:introduction} In recent years, research on processing 3D point clouds has gained momentum due to an increasing number of relevant applications. From robot navigation \cite{biswas2012depth, luo20163d} to autonomous vehicles \cite{pfrunder2017real, whitty2010autonomous,zhu20123d}, augmented reality \cite{wang2018point, pfrunder2017real} to health care \cite{liu20183d,bostelman2006applications, pohlmann2016evaluation}, the challenges of working with 3D datasets are being realized. Among miscellaneous data modalities, raw point clouds are becoming popular as a compact homogeneous representation that has the ability to capture intricate details of the environment. Intuitively, a 3D point cloud can be thought of as an unordered set of irregular points collected from the surface of an object. Each point consists of a Cartesian coordinate, along with other additional information such as a surface normal estimate and RGB color value. Although 3D point clouds are the product of range sensing devices (e.g., structured light, time-of-flight, light detection and ranging, etc.), the application of conventional machine learning techniques on the direct sensor output is nontrivial. In particular, deep learning methods fall short in the processing of 3D point clouds due to the irregular and permutation invariant nature of the data. \begin{figure}[t] \begin{center} \includegraphics[width=0.8\linewidth]{pcgan_results_1.png} \end{center} \caption{Examples of 3D point clouds synthesized by our progressive conditional generative adversarial network (PCGAN) for an assortment of classes. PCGAN generates both geometry and color for point clouds, without supervision, through a coarse to fine training process. Best viewed in color.} \label{fig:pcgan_results_1} \vspace{-2mm} \end{figure} Generating synthetic 3D point cloud data is an open area of research with the intention of facilitating the learning of non-Euclidean point representations. In three dimensions, synthetic data may take the form of meshes, voxels, or raw point clouds in order to learn a representation that aids the solution of computer vision tasks such as classification \cite{qi2017pointnet, wang2019dynamic,maturana2015voxnet,zhou2018voxelnet,cao20173d}, segmentation \cite{qi2017pointnet,wang2019dynamic,qi2017pointnet++,yi2017syncspeccnn, hou20193d,yi2019gspn,sharma2019learning,wu2019pointconv}, and reconstruction \cite{wu2018learning,wang2019forknet,wen2020point,sarmad2019rl,yuan2018pcn, tchapmi2019topnet}. Currently, researchers make use of point clouds sampled from the mesh of manually designed objects as synthetic data for training deep learning models \cite{qi2017pointnet,wang2019dynamic,shu20193d,cao2019point}. However, the geometry and texture of these point clouds is bounded by the resolution of the modeled objects. Moreover, due to the complexity of the design process, the number of composed objects can fail to satisfy the enormous data needs of deep learning research. Automatically synthesizing 3D point clouds can solve this problem by providing a source of potentially infinite amounts of diverse data. Although color and geometry are among the defining features of 3D objects in the physical world, current point cloud generation methods either create the geometry \cite{shu20193d,yang2019pointflow,valsesia2018learning, achlioptas2018learning,hertz2020pointgmm,ramasinghe2019spectral} or the color \cite{cao2019point} of the point cloud, but not both. We believe that 3D point cloud generators should have the ability to synthesize dense point clouds with complex details that mimic real-world objects in both {\em geometry} and {\em color}. To this end, we propose a progressive conditional generative adversarial network (PCGAN) that faithfully generates dense point clouds with color using tree structured graph convolutions. To the best of our knowledge, our work is the first attempt to generate both geometry and color for point clouds in an unsupervised fashion with progressive, i.e., coarse to fine training. Figure \ref{fig:pcgan_results_1} shows examples of 3D point clouds generated by our network. Generating high-resolution data is a difficult and computationally expensive task as the number of features and the level of details increases with resolution. In traditional generative methods \cite{goodfellow2014generative, arjovsky2017wasserstein,gulrajani2017improved}, the generator tries to optimize both global structure and local features simultaneously which can overwhelm an unsupervised network. To reduce the learning complexity, a progressively growing generative adversarial network \cite{karras2017progressive} may be used to learn features in a coarse to fine manner. Progressive growing has also been shown to improve training time \cite{karras2017progressive} since the generator first optimizes low-resolution global structures which helps the optimization of local details at higher resolutions. In terms of 3D point clouds, boosting the resolution makes the dataset denser by the expansion of the number of points. Consequently, this adds more complexity to the generation procedure and amplifies the computational cost. This directly proportional relationship between point cloud resolution and complexity/computational cost has inspired us to use progressive growing in PCGAN for dense point cloud generation. Our network is end-to-end trainable and it learns the distribution of the data as well as the mapping from label to data to generate samples of numerous classes with a single network. \subsection{Contributions} \label{subsec:contributions} The key contributions of our work are threefold. \begin{itemize} \setlength{\itemsep}{-\parsep}\setlength{\topsep}{-\parsep} \item We introduce a progressive generative network that creates both geometry and color for 3D point clouds in the absence of supervision. \item We include both a qualitative and quantitative analysis of the objects synthesized by our network. \item We present the Fr\`echet dynamic distance metric to evaluate colored dense point clouds. \end{itemize} To allow other researchers to use our software, reproduce the results, and improve on them, we have released PCGAN under an open-source license. The source code and detailed installation instructions are available online \cite{pcgan2020}. The remainder of this paper is organized as follows. We give a summary of related research in Section \ref{sec:related_work}. In Section \ref{sec:problem_statement}, we define the problem mathematically and provide the essential background information in Section \ref{sec:background}. The details of our model are provided in Section \ref{sec:model}, and we present the experimental setup and results in Section \ref{sec:experiments}. A conclusion of this work is given in Section \ref{sec:conclusion}. \vspace{-1mm} \section{Related Work} \vspace{-1mm} \label{sec:related_work} In this section, we summarize pertinent work on the generation of 3D point clouds. Interested readers are encouraged to read \cite{chaudhuri2019learning, ahmed2018survey,ioannidou2017deep} for a comprehensive survey of deep learning research on 3D point cloud datasets. \textbf{3D Point Cloud Generation.} The first generative model capable of producing raw point clouds comes from the work of Achlioptas \etal \cite{achlioptas2018learning}. Using PointNet \cite{qi2017pointnet} as the backbone, Achlioptas \etal introduced an autoencoder and two variants of a generative adversarial network to generate point clouds. Prior to \cite{achlioptas2018learning}, Qi \etal introduced PointNet \cite{qi2017pointnet}, the first neural network to operate directly on point cloud data. Eckart \etal \cite{eckart2016accelerated} used hierarchical Gaussian mixture models (hGMMs) to process point clouds, Zaheer \etal \cite{zaheer2017deep} utilized deep networks to analyze point clouds as sets, and Li \etal \cite{li2018so} made use of self-organizing maps and hierarchical feature extraction to discriminate point clouds. Following \cite{achlioptas2018learning}, Li \etal \cite{li2018point} used two generative networks to learn a latent distribution and generated points based on learned features. Yang \etal \cite{yang2018foldingnet} improved upon \cite{achlioptas2018learning} by incorporating graph-based enhancement on top of PointNet and 2D grid deformation. Valsesia \etal \cite{valsesia2018learning} used graph convolutions and exploited pairwise distances between features to construct a generator. Similar to \cite{li2018point}, Yang \etal \cite{yang2019pointflow} generated point clouds by learning two hierarchical distributions and through the use of continuous normalizing flow. Mo \etal \cite{mo2019structurenet} mapped part hierarchies of an object shape as a tree and implemented an encoder-decoder network to generate new shapes via interpolation. Gadelha \etal \cite{gadelha2018multiresolution} presented a tree network for 3D shape understanding and generation tasks by operating on 1D-ordered point lists obtained from a k-d tree space partitioning. Ramasinghe \etal \cite{ramasinghe2019spectral} generated high-resolution point clouds by operating on the spatial domain, and Hertz \etal \cite{hertz2020pointgmm} used hGMMs to generate shapes in different resolutions. However, both \cite{ramasinghe2019spectral} and \cite{hertz2020pointgmm} fail to generate fine shape details. Xie \etal \cite{xie2020generative} proposed an energy-based generative PointNet \cite{qi2017pointnet}, and Sun \etal \cite{sun2020pointgrow} implemented auto-regressive learning with self-attention and context awareness for the generation and completion of point clouds. Cao \etal used adversarial training to generate color for point cloud geometry in \cite{cao2019point}. In follow up work, they used a style transfer approach to transform the geometry and color of a candidate point cloud according to a target point cloud or image \cite{cao2020psnet}. Compared to the focus of the aforementioned works on solely generating the geometry or color of point clouds, our model can produce both color and geometry in an unsupervised manner while maintaining exceptional details at high resolutions. The generator of our model is inspired by the tree structured graph convolution generator of Shu \etal \cite{shu20193d}. However, the generator proposed by Shu \etal does not generate point clouds in color nor does it incorporate the advantages of progressive training. The multiclass generation model of Shu \etal is class agnostic thus making the generation process of a specific class of objects uncontrollable. Conversely, we incorporate conditional generation to control the creation process and use progressive training to build high-resolution point clouds with color. Although, Tchapmi \etal \cite{tchapmi2019topnet} also introduced a tree graph-based decoder, the focal point of their work was the completion of point cloud geometry with supervision. \textbf{Graph Convolutions.} Point clouds can be portrayed as graphs where points represent nodes and the co-relation among neighboring points represent edges. Applying the notion of graph convolution operations to process point clouds is a relatively new area of research. In \cite{qi2017pointnet++}, Qi \etal proposed the hierarchical application of PointNet to learn point cloud features as a graph embedding. However, their work did not incorporate the co-relation of neighboring points and consequently disregards local features. To account for local features, Atzmon \etal \cite{atzmon2018point} used a Gaussian kernel applied to the pairwise distances between points. Wang \etal \cite{wang2019dynamic} introduced DGCNN which uses aggregated point features and pairwise distances among $k$ points to dynamically construct a graph. The discriminator of our model was motivated by DGCNN. Nevertheless, DGCNN was designed for the classification of point cloud geometry while our discriminator aims to act as a critic of point cloud geometry and color to distinguish between real and synthetic data given a class label. \textbf{Progressive Training.} Progressive training has been shown to improve the quality of 2D image generation \cite{karras2017progressive,karras2019style, karras2020analyzing}. Our work is the first attempt to use progressive training in an unsupervised 3D generative network. In previous research, Valsesia \etal \cite{valsesia2018learning} used upsampling layers based on $k$ neighbors of the adjacency graph to increase the feature size between each graph convolution. However, their proposed architecture learns without progressive growing and suffers the same computational complexity of regular generative adversarial networks. The work of Yifan \etal \cite{yuan2018pcn} is the only example of coarse-to-fine generation in 3D. Yet, Yifan \etal used a supervised patch-based approach to upsample point clouds where the overall structure of the data is provided as a prior. In contrast, our network progressively learns the global shape of the data through the underlying distribution of the point cloud geometry and color of a class with no supervision or priors given. \vspace{-1mm} \section{Problem Statement} \vspace{-1mm} \label{sec:problem_statement} Consider a set of classes, $C = \{c_1,\ldots,c_n\}$, each representing mixed objects as 3D colored point clouds, $x \in \mathbb{R}^{N \times 6}$, where $N$ is the number of points. Given a class $c \in C$, we seek to learn the underlying features that constitute $c$ and generate a realistic point cloud $\hat{x} \in \mathbb{R}^{N \times 6}$. \vspace{-1mm} \section{Background} \vspace{-1mm} \label{sec:background} In the following subsections we lay out the necessary background knowledge upon which our work is grounded. \subsection{Wasserstein or Kantorovich-Rubinstein Distance} \label{subsec:wasserstein_distance} Given two distributions $P_r$ and $P_g$ in a metric space $\mathcal{M}$, the Wasserstein or Kantorovich-Rubinstein distance calculates the minimal cost to transform $P_r$ into $P_g$ or vice-versa \cite{villani2008optimal}. A distance of order $p$ can be expressed as \begin{equation*} W_p(P_r,P_g) = \underset{\gamma \in \Pi(P_r,P_g)}{\inf}\mathbb{E}_{(x,y)\sim\gamma}\big[\|x-y\|\big], \end{equation*} where $\Pi(P_r,P_g)$ is the set of all joint distributions $\gamma(x,y)$ with marginals $P_r$ and $P_g$. \subsection{Generative Adversarial Networks} \label{subsec:generative_adversarial_network} Introduced by Goodfellow \etal \cite{goodfellow2014generative}, a generative adversarial network (GAN) is a special type of neural network that focuses on learning the underlying distribution, $P_r$, of a dataset to generate new samples. A GAN consists of a generator $G$ and a discriminator $D$ that compete against each other in a minimax game. The generator tries to manipulate a random vector $z$, drawn from a fixed distribution $P_g$, into synthetic samples $\hat{x}$ that are indistinguishable from the real data $x$. The discriminator seeks to differentiate between $\hat{x}$ and $x$. More formally, the objective of a GAN can be written as \begin{align*} \underset{G}\min\,\underset{D}\max(G, D) &= \mathbb{E}_{x \sim P_r}[\log D(x)]\\ &+ \mathbb{E}_{z \sim P_{g}}[\log(1-D(G(z)))]. \end{align*} \subsection{Wasserstein GAN with Gradient Penalty} \label{subsec:wasserstein_gan-gp} To optimize the convergence of a GAN, Arjovsky \etal \cite{arjovsky2017wasserstein} introduced the Wasserstein GAN (WGAN) whose goal is to minimize the distance between the real data distribution $P_r$ and the generated data distribution $P_g$ using the Wasserstein metric. To make the goal of inter-distribution distance minimization tractable, Arjovsky \etal used the dual form of the Wasserstein distance, i.e., the Wasserstein-1 \cite{villani2008optimal} with the GAN objective \begin{equation*} \underset{G}\min\,\underset{D\in\mathcal{D}}\max(G, D) = \mathbb{E}_{x \sim P_r}[D(x)] - \mathbb{E}_{z \sim P_{g}}[D(G(z))], \end{equation*} where $\mathcal{D}$ is the set of 1-Lipschitz functions. To ensure continuity in space, the discriminator of the WGAN must be 1-Lipschitz which is achieved through weight clipping. However, since weight clipping penalizes the norm of the gradient the stability of network can be compromised. Gulrajani \etal \cite{gulrajani2017improved} improved the WGAN by using a gradient penalty (WGAN-GP) instead of weight clipping. To enforce the 1-Lipschitz condition, the WGAN-GP constrains the norm of the gradient to be at most 1. This is achieved by a penalty term applied to the gradient of the discriminator, \begin{align*} \underset{G}\min\,\underset{D\in\mathcal{D}}\max(G, D) &= \mathbb{E}_{x \sim P_r}[D(x)] - \mathbb{E}_{z \sim P_{g}}[D(G(z))]\\ &+ \lambda\,\mathbb{E}_{\tilde{x}\sim P_{\tilde{x}}}\big[(\|\nabla_{\tilde{x}}D(\tilde{x})\|_2 - 1)^2\big], \end{align*} where $\tilde{x}\sim P_{\tilde{x}}$ are the points uniformly sampled along the straight line between pairs of points from the real data distribution $P_r$ and generated data distribution $P_g$. \vspace{-1mm} \section{Model Architecture} \vspace{-1mm} \label{sec:model} Our model has the following two main components: a generator $G$ and a discriminator $D$. Unless stated otherwise, we refer to a point cloud $x$ as a 6-dimensional matrix with $N$ points, i.e., $x \in \mathbb{R}^{N\times 6}$ where each point represents a Cartesian coordinate and RGB color. For multiclass generation, both the generator and the discriminator are conditioned on a class label, $c \in C$, which is randomly chosen from a set of $n$ classes $C = \{c_1,\ldots,c_n\}$. To optimize the generator and the discriminator we make use of the WGAN-GP techniques discussed in Section \ref{subsec:wasserstein_gan-gp}. Figure \ref{fig:pcgan_model} shows the overall architecture of PCGAN. \begin{figure*} \begin{center} \includegraphics[width=0.8\linewidth]{pcgan_model.png} \end{center} \caption{Given a random vector $z_{in}$ and class label $c$, the generator produces a colored point cloud $\hat{x}$. The real point cloud $x$, class label $c$, and the generated point cloud $\hat{x}$ are given to the discriminator which then tries to predict the probability of the data being real or synthetic. Best viewed in color.} \label{fig:pcgan_model} \end{figure*} \subsection{Generator} \label{subsec:generator} The generator $G$ takes as input a random vector, $z_{in} \in \mathcal{N}(0,1)$, along with a class label $c \in C$ represented as one hot vector. The class label controls the generation of colored point clouds of a desired class. The generator is comprised of two sub-networks: a label transformer $G_{LT}$ and a point transformer $G_{PT}$. The class label goes through $G_{LT}$, a shallow two-layer perceptron, and a class vector $g_c \in \mathbb{R}^{64}$ is constructed. The input vector $z_{in}$ is then concatenated with $g_c$ to produce a point vector $z$ which is given to $G_{PT}$ as input, i.e., \begin{equation*} z = (z_{in}, g_c). \end{equation*} Following \cite{shu20193d}, the point transformer incorporates tree structured graph convolutions (TreeGCN). As the name suggests, information in TreeGCN is passed from the root node to a leaf node instead of all neighbors, i.e., the $i$-th node at layer $l$ is generated by aggregating information from its ancestors $A = \{a_i^{l-1},a_i^{l-2},\ldots,a_i^{1},a_i^{0}\}$. However, we have empirically found that the information from up to three immediate ancestors $A = \{a_i^{l-1},a_i^{l-2},a_i^{l-3}\}$ is sufficient for realistic point cloud generation. This observation improves the overall computational cost of our network as $G_{PT}$ is not bounded by the entire depth of the tree as in \cite{shu20193d} (additional details and an analysis are included in Section \ref{sec:experiments}). Therefore, the output of $(l+1)$-layer of $G_{PT}$ is a first order approximation of the Chebyshev expansion \begin{equation*} p_i^{l+1} = \sigma\Bigg(\textbf{F}_m^l(p_i^l) + \sum_{q_j \in A(p_i^l)} W_j^lq_j^l + b^l\Bigg), \end{equation*} where \begin{equation*} \textbf{F}_m^l(p_i^l) = \sum_{j=1}^{m}S_j p_i^l + r_j, \end{equation*} $\sigma(\cdot)$ is an activation function, $p_i^l$ is the $i$-th node of the graph at the $l$-layer, and $q_j^l$ is the $j$-th ancestor of $p_i^l$ from the set of three immediate ancestors of $p_i^l$. $W, b, S, r$ are learnable parameters and $\textbf{F}_m$ is a sub-network with $m$ support. \begin{figure}[t] \begin{center} \includegraphics[width=0.9\linewidth]{pcgan_progressive_growing.png} \end{center} \caption{The progressive growing of the point transformer $G_{PT}$. The network starts with a leaf output layer and branches $(B_1\ldots,B_T)$, each incorporating a tree graph, and converts a point vector $z$ into a low-resolution point cloud. After a predefined number of iterations, the number of branches is increased through the replication $R$ of the last branch $B_T$. In this figure, $T$ was kept small for visualization purposes. The process is continued until the generation of a point cloud at the desired resolution is achieved. Best viewed in color.} \label{fig:pcgan_progressive_growing} \end{figure} Figure \ref{fig:pcgan_progressive_growing} presents an overview of the progressive growing of PCGAN. We have sub-divided the point transformer $G_{PT}$ into two parts, a branch $B$ and a leaf $L$, where a leaf acts as the output layer of $G_{PT}$ for increasing replications $R$. Each branch incorporates a tree graph of expanding depth, $H = (h_1,\ldots,h_T)$, where $T$ is the total number of branches. The leaf also incorporates a tree graph of depth $h_L$. First, we optimize the generator to produce a point cloud $\hat{x}$ at a predefined base resolution $(N_{R_1} \times 6)$ where $R_1 = h_L \Pi_{i=1}^T h_i$. After a fixed number of iterations, we introduce a new branch $B_{T+1}$ through the replication of the branch $B_{T}$ and we increase the depth $H = (h_1,\ldots,h_{T+1})$ of the incorporated tree graph. The replication of an already optimized branch facilitates the generation of higher resolution point clouds without starting the learning process from scratch. We continue this procedure until the desired resolution of the point cloud is realized, i.e., $R_{d} = h_L \Pi_{i=1}^{T+d} h_i$. \subsection{Discriminator} Given a point cloud $x$, the discriminator $D$ tries to predict the probability of $x$ being real or synthesized. The discriminator is comprised of the following three sub-networks: a feature transformer $D_{FT}$, a label transformer $D_{LT}$, and a critic $D_{CR}$. The feature transformer network was inspired by \cite{wang2019dynamic} to collect local and global features through a dynamic graph construction. Nonetheless, we expand the feature size in every layer to account for the color of the point clouds. Given an input point vector, each layer of the point transformer network constructs a dynamic $k$-NN graph, $\mathcal{G}^l = (\mathcal{V}^l,\mathcal{E}^l)$, with self loops. Each point of the point cloud represents a vertex in the graph and the vertex of each subsequent layer depends on the output of the preceding layers. For a graph $\mathcal{G}^l$ at layer $l$, the edges $e_i^l$ between a vertex $v_i^l$ and its $k$ nearest neighbors are defined as a nonlinear function $\Theta = [\theta_1,\ldots,\theta_m]$ with learnable parameter $\theta$, \begin{equation*} e_{i,(1,\ldots,k)}^l = \Theta_{j \in (1,\ldots,k)}(v_i^l,v_j^l). \end{equation*} Although there are three choices available for $\Theta$, we use the function defined in \cite{wang2019dynamic} to capture both local and global features. Concretely, for two vertices $v_i$ and $v_j$ we have \begin{equation*} \Theta(v_i,v_j) = \theta(v_i,v_i-v_j). \end{equation*} Lastly, the output of the feature transform network is a feature vector $f_c$ collected from the channel-wise maximum operation on the edge features from all the edges of each vertex, \begin{equation*} f_c = \max_{(i,j)\in\mathcal{E}}\Theta(v_i,v_j). \end{equation*} The label transformer of the discriminator functions in an analogous way to the label transformer of the generator and it provides a label vector $d_c$. Note that even though $D_{LT}$ and $G_{LT}$ are similar in architecture, their objectives are distinct. Hence, we use two different networks for this reason. The feature vector $f_c$ together with the label vector $d_c$ are fed to the critic, a fully-connected three layer sub-network that aspires to predict the probability of its input vector being real or synthetic given that it was collected from object class $c$, i.e., \begin{equation*} D_{CR}(f_c,d_c) = [P(\text{real}\,|\,c), P(\text{generated}\,|\,c)]. \end{equation*} \vspace{-1mm} \section{Experiments} \vspace{-1mm} \label{sec:experiments} In this section, we describe our experimental setup and provide an analysis of the results. \textbf{Dataset.} We used the synthetic dataset ShapeNetCore \cite{chang2015shapenet} to conduct our experiments. ShapeNetCore is a collection of CAD models of various object classes among which we chose Chair, Table, Sofa, Airplane, and Motorcycle for our experiments. We have selected these classes for the diversity of their shapes and we keep the number of classes to five to reduce the training time. In addition, we have eliminated any CAD model that does not have material/color information. The training data was prepared by collecting point clouds of desired resolution from the surface of the CAD models. We normalized each point cloud such that the object is centralized in a unit cube and the RGB colors are in the range $[-0.5, +0.5]$. Table \ref{tab:training_data} shows the number of sample objects in each class. \begin{table} \begin{tabularx}{\columnwidth}{| X | X |} \hline Class Label & Number of Samples\\ \hline Airplane & 4029\\ Chair & 4064\\ Table & 8474\\ Sofa & 3149\\ Motorcycle & 333\\ \hline \end{tabularx} \caption{The class labels and the number of samples in the training data.} \label{tab:training_data} \end{table} \textbf{Implementation Details.} The generator of PCGAN learns to produce colored point clouds from low to high resolutions. We start the generation process with $N_{R_1} = 1024$ points and double the number of points progressively. To save memory and reduce computation time, we fix $N_{R_d} = 8192$ points as the highest resolution for the point clouds. The input to the generator is a vector, $z_{in} \in \mathbb{R}^{64}$, sampled from a normal distribution $z_{in} \in \mathcal{N}(0,1)$, and the labels of the chosen classes $c \in C$. For the point transformer, the number of branches was set to $T = 5$ with depth increments $H = [1,2,2,2,2]$. The leaf increments were set to $h_L = 64$. The depth increment hyperparameter for the branches and the leaves is similar to the branching of \cite{shu20193d}. The feature dimension for the layers of $G_{PT}$ was set to $[128,128,256,256,128,128,6]$. We used the Xavier initialization \cite{glorot2010understanding} for $G_{PT}$ and the support $q$ for each branch was set to $10$ as in \cite{shu20193d}. The feature dimension for the layers of the feature transform sub-network were set to $[6,64,128,256,512,1024]$. To comply with the constraints of WGAN-GP, we did not use any batch normalization or dropout in $D_{FT}$. For $D_{FT}$, $k=20$ was used to construct the $k$-NN graph and $k$ was increased by $10$ with each increment in resolution. For both the generator and the discriminator, LeakyReLU nonlinearity with a negative slope of 0.2 was employed. The learning rate $\alpha$ was set to $10^{-4}$ and the Adam optimizer \cite{kingma2014adam} with coefficients $\beta_1 = 0.0$ and $\beta_2 = 0.95$ were used. The gradient penalty coefficient $\lambda$ for WGAN-GP was set to 10. \textbf{Metrics.} To quantitatively evaluate generated samples in 2D, the Fr\`echet inception distance \cite{heusel2017gans} is the most commonly used metric. We propose a similar metric called the Fr\`echet dynamic distance (FDD) to evaluate the generated point clouds where DGCNN \cite{wang2019dynamic} is used as a feature extractor. Although similar metrics exist \cite{shu20193d, sun2020pointgrow} where PointNet is used to extract features, the color of the point clouds is not considered and they suffer from the limitations of PointNet. We use DGCNN because it collects both local and global information over the feature space and it also performs better than PointNet in point cloud classification \cite{wang2019dynamic}. To implement FDD, we trained DGCNN until a 98\% test accuracy per class was achieved on the task of classification. Then, we extracted a $512$-dimensional feature vector from the average pooling layer of DGCNN to calculate the mean vector and covariance matrix. For real point clouds $x$ and synthetic point clouds $\hat{x}$, the FDD calculates the 2-Wasserstein distance, \begin{equation*} \text{FDD}(x,\hat{x}) = \|\mu_x - \mu_{\hat{x}} \| + \tr(\Sigma_x+\Sigma_{\hat{x}} - 2(\Sigma_x \Sigma_{\hat{x}})^{1/2}), \end{equation*} where $\mu$ and $\Sigma$ represent the mean vector and the covariance matrix, respectively. The matrix trace is denoted by $\tr()$. Additionally, we have used the matrices from Achlioptas \etal \cite{achlioptas2018learning} for point cloud evaluation and we have compared the results with \cite{achlioptas2018learning, shu20193d,valsesia2018learning}. \begin{table*} \begin{tabularx}{\textwidth}{| X | X | c c c c c|} \hline Class & Model & JSD $\downarrow$ & MMD-CD $\downarrow$ & MMD-EMD $\downarrow$ & COV-CD $\uparrow$ & COV-EMD $\uparrow$\\ \hline & r-GAN (dense) & 0.182 & 0.0009 & 0.094 & 31 & 9\\ & r-GAN (conv) & 0.350 & \color{cyan}0.0008 & 0.101 & 26 & 7\\ Airplane & Valsesia \etal (no up.) & 0.164 & 0.0010 & 0.102 & 24 & 13\\ & Valsesia \etal (up.) & \color{magenta}{0.083} & \color{cyan}0.0008 & 0.071 & 31 & 14\\ & tree-GAN & 0.097 & \color{magenta}{0.0004} & \color{magenta}0.068 & \color{magenta}61 & 20\\ & {\bf PCGAN} (ours) & \color{cyan}0.085 & 0.0010 & \color{cyan} 0.070 & \color{cyan}37 & \color{magenta}29\\ \hline & r-GAN (dense) & 0.238 & 0.0029 &0.136 & \color{cyan}33 & 13\\ & r-GAN (conv) & 0.517 & 0.0030 & 0.223 & 23 & 4\\ Chair & Valsesia \etal(no up.) & 0.119 & 0.0033 & 0.104 & 26 & 20\\ & Valsesia \etal (up.) & \color{cyan}0.100 & 0.0029 & \color{cyan}0.097 & 30 & 26\\ & tree-GAN & 0.119 & \color{magenta}0.0016 & 0.101 & \color{magenta}58 & \color{cyan}30\\ & {\bf PCGAN} (ours) & \color{magenta}0.089 & \color{cyan}0.0027 & \color{magenta}0.093 & 30 & \color{magenta}33\\ \hline & r-GAN (dense) & 0.221 & \color{magenta}0.0020 & 0.146 & \color{cyan}32 & 12\\ & r-GAN(conv) & 0.293 & 0.0025 & 0.110 & 21 & 12 \\ Sofa & Valsesia \etal (no up.) & \color{cyan}0.095 & \color{cyan}0.0024 & 0.094 & 25 & 19\\ & Valsesia \etal (up.) & \color{magenta}0.063 & \color{magenta}0.0020 & \color{magenta}0.083 & \color{magenta}39 & \color{cyan}24\\ & {\bf PCGAN} (ours) & 0.16 & 0.0027 & \color{cyan}0.093 & 24 & \color{magenta}27\\ \hline Motorcycle & {\bf PCGAN} (ours) & 0.25 & 0.0016 & 0.097 & 10 & 9\\ \hline Table & {\bf PCGAN} (ours) & 0.093 & 0.0035 & 0.089 & 45 & 43\\ \hline \end{tabularx} \caption{A qualitative evaluation of the Jensen-Shannon divergence (JSD), the minimum matching distance (MMD), coverage (COV) with the Earth mover's distance (EMD), and the pseudo-chamfer distance (CD). Please refer to \cite{achlioptas2018learning} for details regarding the metrics. The results of previous studies are from \cite{shu20193d,valsesia2018learning}. The magenta and cyan values denote the best and the second best results, respectively. The resolution of the evaluated point clouds was $2048 \times 3$.} \label{tab:metrics_results} \end{table*} \begin{table} \begin{tabularx}{\columnwidth}{|X|c|c|} \hline Class & Real Data & Generated Samples\\ \hline Airplane & $1.12 \times 10^{-5}$ & 4.58\\ Chair & $2.07 \times 10^{-9}$ & 3.07\\ Motorcycle & $1.04 \times 10^{-4}$ & 13.25\\ Sofa & $5.88 \times 10^{-6}$ & 3.14\\ Table & $4.37 \times 10^{-7}$ & 2.02\\ \hline \end{tabularx} \caption{The FDD score for point cloud samples generated by PCGAN. Notice that the scores for real point clouds are almost zero. The point clouds were evaluated at a resolution of $8192 \times 6$.} \label{tab:fdd_results} \end{table} \subsection{Results} A set of synthesized objects along with their real counterparts is shown in Figure \ref{fig:pcgan_results_2}. As is evident from the samples, our model first learns the basic structure of an object in low resolutions and gradually builds up to higher resolutions. PCGAN also learns the relationship between object parts and color. For example, the legs of the chair have equal colors while the seat/arms are a different color, the legs of the table have matching colors while the top is a contrasting color, and the airplane wings/engine have the same color while the body/tail has a dissimilar color. \textbf{Quantitative Analysis.} We generated $5000$ random samples for each class and performed an evaluation using the matrices from \cite{achlioptas2018learning}. Table \ref{tab:metrics_results} presents our findings along with comparisons to previous studies \cite{achlioptas2018learning,shu20193d,valsesia2018learning}. Note that although our model is capable of generating higher resolutions and colors, we only used point clouds with $N = 2048$ points in order to be comparable with other methods. Also, separate models were trained in \cite{achlioptas2018learning, shu20193d, valsesia2018learning} to generate point clouds of different classes while we have used the {\em same} model to generate point clouds for all five classes. Even though we have achieved comparable results in Table \ref{tab:metrics_results}, the main focus of our work is dense colored point cloud generation and point clouds with a resolution of $N = 2048$ is an intermediate result of our network. We have also evaluated colored dense point clouds ($N = 8192$) using the proposed FDD metric with the results presented in Table \ref{tab:fdd_results}. \textbf{Computational Complexity.} Tree structured graph convolutions are used in each layer of the point transformer sub-network. Since every subsequent node in the tree is originally dependent upon all of its ancestors, the time complexity of the graph convolutions is $\sum_{l=1}^{L} B \times n_i^l \times A^l_i \times V^l_i$, where $B$ is the batch size of the training data, $L$ is the total number of layers, $n_i^l$ is the height of the tree graph at the $i$-th node, $A_i$ is the induced number of ancestors preceding $i$-th node, and $V_i^l$ is the induced vertex number of the $i$-th node \cite{shu20193d}. However, we restrict $G_{PT}$ to aggregate information from at most three levels of ancestors in each layer. Thus, $n_i^l \le 3$ and the effective time complexity is $\sum_{l=1}^{L} B \times 3 \times A^l_i \times V^l_i$. \textbf{Progressive Experiments.} We have experimented with different strategies of progressive growing such as branching $H = [2,4,4,4], [1,2,4,8], [1,2,4,2]$ and leaf $h_L = [4,16,64]$ increments. Although branching and leaf combinations may generate more discernible point cloud geometries and colors for individual classes, we have found that $H = [1,2,2,2]$ and $h_L =64$ work best in our experiments. Additionally, instead of creating new branches we have experimented with introducing new leaves for progressive growing. However, this seems to destabilize the network and results in the generation of inferior samples. \textbf{Limitations and Future Work.} The main drawback of our model is the computational complexity. With $\approx 20000$ point clouds from five classes, our model takes roughly $15$ minutes per iteration (MPI) on four Nvidia GTX 1080 GPUs to generate point clouds $\hat{x} \in \mathbb{R}^{1024 \times 6}$. The MPI rises with every increase in resolution. For future work, we will attempt to reduce the computational complexity of our network. Our model also struggles with generating objects that have fewer examples in the training data. The generated point clouds of the Motorcycle class in Figure \ref{fig:pcgan_results_2} is an example of this (ShapeNetCore has only $333$ CAD models of the Motorcycle). In the future, we will try to improve the generalization ability of our model and we will work on the addition of surface normal estimates. \vspace{-1mm} \section{Conclusion} \vspace{-1mm} \label{sec:conclusion} This paper introduces PCGAN, the first conditional generative adversarial network to generate dense colored point clouds in an unsupervised mode. To reduce the complexity of the generation process, we train our network in a coarse to fine way with progressive growing and we condition our network on class labels for multiclass point cloud creation. We evaluate both point cloud geometry and color using our new FDD metric. In addition, we provide comparisons on point cloud geometry with recent generation techniques using available metrics. The evaluation results show that our model is capable of synthesizing high-quality point clouds for a disparate array of object classes. \begin{figure*}[p] \begin{center} \includegraphics[width=0.90\linewidth]{pcgan_results_2.png} \end{center} \caption{The results of generated samples produced by PCGAN. Our model first learns the basic structure of an object at low resolutions and gradually builds up towards high-level details. The relationship between the object parts and their colors (e.g., the legs of the chair/table are the same color while seat/top are contrasting) is also learned by the network. Mitsuba 2 \cite{mitsuba2020} was used to render the point clouds. Best viewed in color.} \label{fig:pcgan_results_2} \end{figure*} \ifthreedvfinal \section*{Acknowledgments} \vspace{-1mm} The authors acknowledge the Texas Advanced Computing Center (TACC) at the University of Texas at Austin for providing software, computational, and storage resources that have contributed to the research results reported within this paper. \fi {\small \bibliographystyle{ieee}
{'timestamp': '2020-10-13T02:26:55', 'yymm': '2010', 'arxiv_id': '2010.05391', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05391'}
arxiv
\section{Introduction}\label{Sec_1} The long-standing Golomb--Welch conjecture \cite{GW} states that there are no perfect Lee codes for spheres of radius greater than 1 and dimension greater than 2. Resolving this conjecture has been one of the main motivations for studying perfect and quasi-perfect Lee codes. Very recently, Camarero and Mart\'{i}nez \cite{CM}, showed that for every prime number $p>5$ such that $p\equiv \pm 5 \pmod{12}$, the Cayley graph $\mathcal{G}_p=\textnormal{Cay}(\mathbb{Z}_p[i], S_2)$, where $S_2$ is the set of units of $\mathbb{Z}_p[i]$, induces a 2-quasi-perfect Lee code over $\mathbb{Z}_p^m$, where $m=2\lfloor \frac{p}{4}\rfloor$. They also conjectured \cite[Conj. 31]{CM} that the Cayley graph $\mathcal{G}_p=\textnormal{Cay}(\mathbb{Z}_p[i], S_2)$ is a Ramanujan graph for every prime $p$ such that $p\equiv 3 \pmod{4}$. In this paper, we solve this conjecture. Our main tools, which are reviewed in the next section, are Deligne's bound \cite{DEL} from 1977 for estimating a particular kind of trigonometric sum and a result of Lov\'{a}sz \cite{LO} from 1975 (or of Babai \cite{BA} from 1979) which gives the eigenvalues of Cayley graphs of finite Abelian groups. Our proof techniques may motivate more work in the interactions between spectral graph theory, character theory, and coding theory, and may provide new ideas towards the Golomb--Welch conjecture. Let us first recall here briefly some terminologies and concepts that we will need in this paper. The ring of \textit{Gaussian integers} is defined as $$ \mathbb{Z}[i]=\lbrace x+yi : x, y \in \mathbb{Z}, i=\sqrt{-1} \rbrace. $$ In other words, Gaussian integers are the lattice points in the Euclidean plane. The \textit{norm} of a Gaussian integer $w=x+yi$ is N$(w)=|w|^2=x^2+y^2$. The elements of $\mathbb{Z}[i]$ with norm 1 are called the \textit{units} of $\mathbb{Z}[i]$; so, the units of $\mathbb{Z}[i]$ are just $\pm 1$ and $\pm i$. Similarly, the ring of Gaussian integers modulo a positive integer $n$ is defined as $$ \mathbb{Z}[i]/n\mathbb{Z}[i]\cong\mathbb{Z}_n[i]=\lbrace a+bi : a, b \in \mathbb{Z}_n, i=\sqrt{-1} \rbrace. $$ Note that the definition of norm (and so unit) in the ring $\mathbb{Z}_n[i]$ is the same as that of $\mathbb{Z}[i]$ except that we need to evaluate the norm modulo $n$. That is, the \textit{norm} of $z=a+bi \in \mathbb{Z}_n[i]$ is N$(z)=a^2+b^2 \pmod{n}$, and $z=a+bi \in \mathbb{Z}_n[i]$ is a \textit{unit} of $\mathbb{Z}_n[i]$ if and only if $$ a^2+b^2 \equiv 1 \pmod{n}. $$ The following classical result gives necessary and sufficient conditions under which the ring $\mathbb{Z}_n[i]$ is a field; see, e.g., \cite[Fact 3]{DRD}. \begin{proposition}\label{field} Let $n>1$ be an integer. The ring $\mathbb{Z}_n[i]$ is a field if and only if $n$ is a prime and $n\equiv 3 \pmod{4}$. \end{proposition} Let $\Gamma$ be a group written in additive notation. A non-empty subset $S \subseteq \Gamma$ is said to be \textit{symmetric} if $S=-S$, where $-S=\lbrace -x : x\in S \rbrace$. In other words, $S$ is symmetric if $-x \in S$ whenever $x \in S$. Now, we define Cayley graphs: \begin{definition} Let $\Gamma$ be a group, written additively, and $S$ be a finite symmetric subset of $\Gamma$ which does not contain the identity element of $\Gamma$. The \textit{Cayley graph} of $\Gamma$ with respect to $S$, denoted by $G=\text{Cay}(\Gamma, S)$, is the graph whose vertex set is $\Gamma$, and such that $u \sim v$ if and only if $v-u \in S$. Note that the Cayley graph $G=\text{Cay}(\Gamma, S)$ is undirected, simple, $|S|$-regular, and vertex-transitive. Also, $G$ is connected if and only if $S$ generates $\Gamma$. \end{definition} Roughly speaking, an expander is a highly connected sparse graph, that is, every subset of its vertices has a large set of neighbours. An important special case, namely, Ramanujan graphs are also of great interest. These graphs are actually `optimal' expanders, from the spectral point of view. Roughly speaking, a Ramanujan graph is a connected regular graph whose second largest eigenvalue in absolute value is `asymptotically' the smallest possible (or, equivalently, whose spectral gap is `asymptotically' the largest possible). Formally, a finite, connected, $k$-regular graph $G$ is called a \textit{Ramanujan graph} if every eigenvalue $\lambda\not=\pm k$ of $G$ satisfies the bound $$ |\lambda|\leq 2\sqrt{k-1}. $$ To this date, there are only a few explicit constructions (which are useful for applications) of expanders and Ramanujan graphs, all given using several strong (and seemingly unrelated!) mathematical tools; mainly from number theory. These graphs have a great deal of seminal applications in many disciplines such as computer science, cryptography, coding theory, and even in pure mathematics! See \cite{DSV, HLW, LUBO} for detailed discussions and surveys on expanders and Ramanujan graphs, their interactions with other areas like number theory and group theory, and their many wide-ranging applications. Now, we review some basic facts about group characters; see, e.g., \cite{ISA, SE} for more details. A \textit{character} of a group $\Gamma$ is a group homomorphism from $\Gamma$ to the unit circle $S^1=\lbrace z \in \mathbb{C} : |z|=1 \rbrace$. So, if $\Gamma$ is a finite group then a character of $\Gamma$ can be defined as a group homomorphism from $\Gamma$ to $\mathbb{C}^{*}$, the multiplicative group of non-zero complex numbers. For a group $\Gamma$, the \textit{trivial} character $\chi_0$ is the function on $\Gamma$ where $\chi_0(g)=1$, for all $g\in \Gamma$. The characters of a finite group are linearly independent. A finite group $\Gamma$ has \textit{at most} $|\Gamma|$ characters and a finite Abelian group $\Gamma$ has \textit{exactly} $|\Gamma|$ distinct characters. For a finite Abelian group $\Gamma$ with the trivial character $\chi_0$, \begin{equation*} \sum_{g \in \Gamma}\chi(g) = \begin{cases} |\Gamma|, & \text{ if \ $\chi=\chi_0$}; \\ 0, & \text{ if \ $\chi\not=\chi_0$}. \end{cases} \end{equation*} \section{Proof ingredients and techniques}\label{Sec_2} In this section, we prove the conjecture proposed in \cite{CM}, by showing that the Cayley graph $\mathcal{G}_p=\textnormal{Cay}(\mathbb{Z}_p[i], S_2)$ is a $(p+1)$-regular Ramanujan graph. First, we mention the proof ingredients. The following proposition lists some classical facts from spectral graph theory; see, e.g., \cite{doob}. As it is common, by an eigenvalue (resp., eigenvector) of a graph we mean an eigenvalue (resp., eigenvector) of the adjacency matrix of that graph. \begin{proposition}\label{facts} Let $G$ be a simple graph (i.e., without loops or multiple edges) of order $n$, with the adjacency matrix $A(G)$, and with the maximum degree $\Delta(G)$. Also, let $\lambda_{\min}(G)$ and $\lambda_{\max}(G)$ denote, respectively, the smallest and the largest eigenvalues of $G$. The following facts hold: \begin{itemize \item The graph $G$ has $n$ eigenvalues (including multiplicities), and since $A(G)$ is real and symmetric, all these eigenvalues are real. \item We have $\lambda_{\max}(G)\leq \Delta(G)$. Furthermore, if $G$ is $k$-regular then $\lambda_{\max}(G)=k$, and for every eigenvalue $\lambda$ of $G$, $|\lambda|\leq k$. \item If $G$ is $k$-regular then the multiplicity of the eigenvalue $k$ equals the number of connected components of $G$. So, if $G$ is $k$-regular then $G$ is connected if and only if the eigenvalue $k$ has multiplicity one. \item The graph $G$ is bipartite if and only if its spectrum is symmetric about \textnormal{0}. Also, if $G$ is connected then $G$ is bipartite if and only if $\lambda_{\min}(G)=-\lambda_{\max}(G)$. \end{itemize} \end{proposition} It is well-known that the spectra of Cayley graphs of finite groups can be expressed in terms of characters of the underlying group (\cite{BA, LO}). The following result determines the eigenvalues and eigenvectors of Cayley graphs of finite Abelian groups. The theorem follows from a more general result of Lov\'{a}sz \cite{LO} from 1975 (or of Babai \cite{BA} from 1979). \begin{theorem}\label{eigenvalue} Let $\Gamma$ be a finite Abelian group, $\chi : \Gamma \rightarrow \mathbb{C}^{*}$ be a character of $\Gamma$, and $S$ be a symmetric subset of $\Gamma$ which does not contain the identity element of $\Gamma$. Then the vector $v_{\chi}=(\chi(g))_{g \in \Gamma}$ is an eigenvector of the Cayley graph $G=\textnormal{Cay}(\Gamma, S)$, with the corresponding eigenvalue being $$ \lambda_{\chi}=\sum_{s \in S}\chi(s). $$ \end{theorem} In order to find the degree of the Cayley graph $\mathcal{G}_p=\textnormal{Cay}(\mathbb{Z}_p[i], S_2)$, we need to evaluate the number of solutions of certain quadratic congruences. The problem of counting the number of solutions of quadratic congruences in several variables has been investigated, in a general form, in \cite{TOTH}, where a general formula is proved. Specifically, T\'oth \cite{TOTH} considered the quadratic congruence \begin{equation} \label{quadratic cong} a_1x_1^2+ \cdots +a_kx_k^2 \equiv b \pmod{n}, \end{equation} where $b\in \mathbb{Z}$, $\mathbf{a}=(a_1,\ldots,a_k)\in \mathbb{Z}^k$, and proved an explicit formula (see Theorem~\ref{main quadratic} below) for the number $N_k(b,n,\mathbf{a})$ of solutions $\langle x_1,\ldots,x_k\rangle\in \mathbb{Z}_n^k$ of \eqref{quadratic cong}, when $n$ is odd. The formula involves a special kind of trigonometric sums, namely, quadratic Gauss sums that we now define. Let $e(x)=\exp(2\pi ix)$ be the complex exponential with period 1. For positive integers $m$ and $n$ with $\gcd (m,n)=1$, the quantity \begin{align}\label{Gauss Sum} S(m,n)= \mathlarger{\sum}_{j=1}^n e\left(\frac{m j^2}{n}\right) \end{align} is called a {\it quadratic Gauss sum}. \begin{theorem} \label{main quadratic} Let $k$, $b$, $n$ be integers \textnormal{(}$k,n \geq 1$\textnormal{)}, and $\mathbf{a}=(a_1,\ldots,a_k)\in \mathbb{Z}^k$. We have \begin{align*} \ & N_k(b,n,\mathbf{a})\\ =\ & n^{k-1} \mathlarger{\sum}_{d\;\mid\;n} \frac1{d^k} \mathlarger{\sum}_{\substack{m=1\\ (m,d)=1}}^d e\left(\frac{-bm}{d}\right) S(m a_1,d) \cdots S(m a_k,d). \end{align*} \end{theorem} Putting $k=2$, $a_1=a_2=1$, $b=1$, and $n=p^r$ (a power of a prime) in Theorem~\ref{main quadratic}, the following special case is obtained (see \cite{TOTH}): \begin{lemma}\label{quadratic} Let $p$ be a prime and $r$ be a positive integer. The number $N_2(1,p^r)$ of solutions of the quadratic congruence $x^2+y^2\equiv 1 \pmod{p^r}$ is \begin{equation*} N_2(1,p^r) = \begin{cases} p^r (1-\frac{1}{p}), & \text{if \ $p \equiv 1$ {\rm (mod $4$)}, $r \ge 1$}; \\ p^r (1+\frac{1}{p}), & \text{if \ $p \equiv 3$ {\rm (mod $4$)}, $r \ge 1$}; \\ 2, & \text{if \ $p=2$, $r=1$}; \\ 2^{r+1}, & \text{if \ $p=2$, $r \ge 2$}. \end{cases} \end{equation*} \end{lemma} If $\mathbb{F}$ and $\mathbb{E}$ are fields and $\mathbb{F} \subseteq \mathbb{E}$, then $\mathbb{E}$ is said to be an {\it extension} of $\mathbb{F}$, denoted by $\mathbb{E}\;/\;\mathbb{F}$. The {\it degree} of a field extension $\mathbb{E}\;/\;\mathbb{F}$, denoted by $[\mathbb{E} \;:\; \mathbb{F}]$, is the dimension of $\mathbb{E}$ as a vector space over $\mathbb{F}$. A field extension $\mathbb{E}\;/\;\mathbb{F}$ is called a \textit{finite extension} if $[\mathbb{E} \;:\; \mathbb{F}]<\infty$. Let $\mathbb{F}_{q^n}$ be a finite extension field of the finite field $\mathbb{F}_q$. For $\alpha \in \mathbb{F}_{q^n}$, the \textit{field norm} of $\alpha$ is defined by (see, e.g., \cite[Def. 2.27]{LIN}) $$ \text{N}_{\mathbb{F}_{q^n}/\mathbb{F}_q}(\alpha)=\alpha^{(q^n-1)/(q-1)}. $$ The elements of $\mathbb{F}_{q^n}$ with field norm 1 are called the \textit{units} of $\mathbb{F}_{q^n}$. \begin{lemma}\label{norm} Let $p$ be a prime such that $p\equiv 3 \pmod{4}$. Then for every $z\in \mathbb{Z}_p[i]$ the field norm of $z$ coincides with the norm of $z$ in the usual sense, that is, as the norm of a Gaussian integer modulo $p$. \end{lemma} \begin{proof} Let $z=a+bi \in \mathbb{Z}_p[i]$, where $p$ is a prime and $p\equiv 3 \pmod{4}$. Then, by the above definition, the field norm of $z$ equals \begin{eqnarray*} \text{N}_{\mathbb{Z}_p[i]/\mathbb{Z}_p}(a+bi)&=&(a+bi)^{p+1}\\ &=&(a+bi)(a+bi)^{p}\\ &=&(a+bi)(a^p+b^pi^p)\\ &=&a^{p+1}+ab^pi^p+ba^pi+b^{p+1}i^{p+1}\\ &\equiv &a^2+b^2 \pmod{p}, \end{eqnarray*} where we have used Fermat's little theorem and also the binomial theorem for commutative rings of characteristic $p$ (see, e.g., \cite[Th. 1.46]{LIN}) which says that in a commutative ring $R$ of prime characteristic $p$, we have $$ (x+y)^{p^n}=x^{p^n}+y^{p^n}, $$ for every $x,y\in R$ and every positive integer $n$. Note that the value $a^2+b^2 \pmod{p}$ is just the norm of $z$ as a Gaussian integer modulo $p$. \end{proof} Deligne \cite{DEL} using tools from algebraic geometry and cohomology proved the following crucial bound. \begin{theorem}\label{Deligne's bound} Suppose that $\mathbb{F}_{q^n}/\mathbb{F}_q$ is the field extension of degree $n$ of the finite field $\mathbb{F}_q$, $S_n$ is the set of units of $\mathbb{F}_{q^n}$, and $\chi$ is a nontrivial character of the additive group of $\mathbb{F}_{q^n}$. Then $$ \Big|\sum_{s \in S_n}\chi(s)\Big|\leq nq^{\frac{n-1}{2}}. $$ \end{theorem} Now, we are ready to prove our main result. This problem has been mentioned as Conjecture 31 in \cite{CM}. \begin{theorem}\label{main} Let $p$ be a prime, $p\equiv 3 \pmod{4}$, and $S_2$ be the set of units of $\mathbb{Z}_p[i]$. Then the Cayley graph $\mathcal{G}_p=\textnormal{Cay}(\mathbb{Z}_p[i], S_2)$ is a $(p+1)$-regular Ramanujan graph. \end{theorem} \begin{proof} By Proposition~\ref{field}, the ring $\mathbb{Z}_n[i]$ is a field if and only if $n$ is a prime and $n\equiv 3 \pmod{4}$. Thus, for a prime $p$ with $p\equiv 3 \pmod{4}$ we have $\mathbb{Z}_p[i]\cong \mathbb{F}_{p^2}$. Also, we know that for a prime $p$ with $p\equiv 3 \pmod{4}$, $\mathbb{Z}_p[i]$ as an extension field of the finite field $\mathbb{F}_p$ has degree 2 (because $\lbrace 1, i\rbrace$ can serve as a basis), that is, $[\mathbb{Z}_p[i]:\mathbb{F}_p]=2$. Note that $S_2$ is a symmetric subset of $\mathbb{Z}_p[i]$ and does not contain the identity element of $\mathbb{Z}_p[i]$. Since the Cayley graph $\mathcal{G}_p=\text{Cay}(\mathbb{Z}_p[i], S_2)$ is of order $p^2$, it has $p^2$ real eigenvalues. Also, by Lemma~\ref{quadratic}, the number of solutions of the quadratic congruence $x^2+y^2\equiv 1 \pmod{p}$ is $p+1$, so, $|S_2|=p+1$ which means that $\mathcal{G}_p$ is $(p+1)$-regular. By Theorem~\ref{eigenvalue}, the eigenvalues of $\mathcal{G}_p$ are determined by $$ \lambda_{\chi}=\sum_{s \in S_2}\chi(s), $$ where $\chi$ runs over all characters of $\mathbb{Z}_p[i]$; note that since $\mathbb{Z}_p[i]$, as an additive group, is a finite Abelian group, it has $p^2$ distinct characters. The eigenvalue corresponding to the trivial character $\chi_0$ of $\mathbb{Z}_p[i]$ equals $$ \lambda_{\chi_0}=\sum_{s \in S_2}\chi_0(s)=\sum_{s \in S_2}1=|S_2|=p+1. $$ Of course, as $\mathcal{G}_p$ is $(p+1)$-regular, we already knew, by Proposition~\ref{facts}, that $p+1$ is an eigenvalue of $\mathcal{G}_p$ (in fact, the largest one). Note that since $p$ is a prime and $p\equiv 3 \pmod{4}$, by Lemma~\ref{norm}, for every $z\in \mathbb{Z}_p[i]$ the field norm of $z$ coincides with the norm of $z$ as a Gaussian integer modulo $p$, thus, the `field norm' (and so unit) in Theorem~\ref{Deligne's bound} is in fact the `norm' (and so unit) we already have. Now, by Theorem~\ref{Deligne's bound}, the absolute values of the eigenvalues corresponding to the nontrivial characters $\chi\not=\chi_0$ of $\mathbb{Z}_p[i]$ satisfy the bound $$ |\lambda_{\chi}|=\Big|\sum_{s \in S_2}\chi(s)\Big|\leq 2\sqrt{p}. $$ Therefore, $\mathcal{G}_p$ is a $(p+1)$-regular Ramanujan graph. We remark that since $\mathcal{G}_p$ is $(p+1)$-regular and the eigenvalue $p+1$ has multiplicity one, by Proposition~\ref{facts}, $\mathcal{G}_p$ is connected. This in turn implies that $S_2$ generates $\mathbb{Z}_p[i]$. \end{proof} Since by the above argument, $-(p+1)$ is not an eigenvalue of $\mathcal{G}_p$, by Proposition~\ref{facts}, we get: \begin{corollary} The Cayley graph $\mathcal{G}_p=\textnormal{Cay}(\mathbb{Z}_p[i], S_2)$ is not bipartite. This implies that $\mathcal{G}_p$ has at least one odd cycle. \end{corollary} \section*{Acknowledgements} During the preparation of this work the first author was supported by a Fellowship from the University of Victoria (UVic Fellowship).
{'timestamp': '2020-10-13T02:27:15', 'yymm': '2010', 'arxiv_id': '2010.05407', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05407'}
arxiv
\section{Introduction}\label{sec:introduction}} \IEEEPARstart{O}{ne} of the key technologies transforming our living experiences into much smarter ones is the Internet of Things (IoT). However, since IoT devices are usually resource-constrained, it is pressing to design lightweight block ciphers as building blocks to secure IoT protocols, \emph{i.e.}, providing basic security requirements including confidentiality, data integrity, and source authentication for IoT devices. By now, there have been numerous lightweight block ciphers introduced. A statistic performed by researchers of the University of Luxembourg~\footnote{https://www.cryptolux.org/index.php/Lightweight_Block_Ciphers} lists 36 lightweight block ciphers proposed by 2016. In order to evaluate and standardize lightweight cryptographic algorithms, NIST is supporting a Lightweight Cryptography project. By now, 32 candidates have been selected and are evaluating in Round 2. Readers can find more information about the project in this link \url{https://csrc.nist.gov/projects/lightweight-cryptography}. In CHES 2015, Yang {\it et al.}~\cite{simeck} introduced SIMECK, which is a family of lightweight block ciphers based upon Feistel structure and combines the good design principles of the SIMON and SPECK block ciphers~\cite{BSS+13}. Precisely, SIMECK consists of three members with block sizes of $32, 48$, and $64$, and the corresponding key sizes are $64, 96$, and $128$, respectively. As demonstrated in~\cite{simeck}, SIMECK allows a smaller and more efficient hardware implementation in comparison to SIMON. Due to its nice property in efficiency, SIMECK has been significantly analyzed since its publication. As is known to all, fault analysis is a very efficient implementation attack against cryptographic protocols, which essentially tries to influence the behavior of a cryptographic device and determine sensitive information by examining the effects. Today, there have been several mechanisms to inject faults into microprocessors. Examples include changes in the power supply, the clock frequency~\cite{KK99}, or intensive lighting of the circuit~\cite{SA02}. In most cases, injecting faults will force a change in the data located in one of the registers. The first fault attack against RSA-CRT implementation was reported in {a Bellcore press in 1996} and subsequently analyzed by Boneh, DeMillo and Lipton in~\cite{BDL97}. Concretely, Boneh \emph{et al.}~\cite{BDL97} showed that many implementations of RSA signatures and other public-key algorithms are vulnerable to a certain transient fault occurring during the processing phase, and the RSA-CRT implementation is at extreme risk to be compromised by using one erroneous result. After that, Biham and Shamir ~\cite{BS97} introduced the Differential Fault Analysis (DFA) against symmetric cryptosystems such as the DES~\cite{BS97}. They assume that an attacker can disturb DES computations by using the same - but {\it unknown} - plaintext at the last (three) DES round(s). The wrong ciphers provide a system of equations for the unknown last round key bits that finally reveals the correct key value. Since then, there have been many DFA attacks carried out on other block ciphers, including attacks against AES~\cite{Gir04,kim2011improved}, Triple DES~\cite{HJQ04}, IDEA~\cite{CGV08}, SIMON and SPECK~\cite{tupsamudre2014differential, LYK19} or KLEIN lightweight block ciphers~\cite{GruberS19}. These attacks are performed on the key schedule~\cite{kim2011improved}, S-box~\cite{GruberS19}, or intermediate inputs~\cite{tupsamudre2014differential}. They are also carried out under various fault models (see more details in Section~2.3.2). In 2016, Nalla \emph{et al.} ~\cite{NSS16} presented two fault analysis attacks against SIMECK ciphers. While the former is under the one bit-flip fault model, the latter is under the random byte fault model. Both of the two attacks aim at recovering the last round key by injecting faults into the second last round. In this paper, we would like to present an improved fault analysis attack against SIMECK block ciphers under the one bit-flip model, which is more practical than Nalla \emph{et al.}'s attacks. Specifically, the main contribution of this paper is three-fold. \begin{itemize} \item First, we show that the whole master key of SIMECK block ciphers could be recovered by injecting faults into a single round of the ciphers, which makes our attack more {\em practical} than Nalla \emph{et al.}'s attacks~\cite{NSS16}, as their attacks require faults from $4$ different rounds. \item Second, by deducing more key bits with one fault, our attack also requires fewer faults than those previously reported attacks. \item Third, we conduct extensive simulation evaluations, and the results demonstrate the effectiveness and correctness of our attack. \end{itemize} The remainder of this paper is organized as follows. Section~\ref{background} briefly recalls SIMECK ciphers, security analyses, and differential fault analysis on this family of ciphers. Section~\ref{sec:observations} discusses some facts and observations that will be used in our attack. Section~\ref{sec:bitflip} describes our differential fault analysis under the one bit-flip model. Then, we present our simulation evaluations in Section~\ref{sec:simulation}. Finally, we draw our conclusions in Section~\ref{sec:conclusion}. \section{Preliminaries}\label{background} In this section, we briefly recall the specification of the SIMECK family of lightweight block ciphers and differential fault analysis on this family of ciphers. For the sake of consistency, we make use of the following notations listed in Table~\ref{tab:notations} in the rest of the paper. In principles, we use capital letters for vectors or strings while small letters are used to represent individual bits. \begin{table}[ht] \centering \caption{Definition of Notations} \label{tab:notations} \footnotesize \begin{tabular}{p{0.07\textwidth}p{ 0.36\textwidth}} \toprule ~Notation& ~Definition\\ \midrule \midrule \rowcolor[gray]{.9} $T$ & the total number of rounds of the cipher.\\ $(X^i, Y^i)$ & input of round $i$, $i=0,1,\ldots,T-1$. \\ \rowcolor[gray]{.9} $(X^T, Y^T)$ & ciphertext. \\ $(\hat{X}^{ i}, \hat{Y}^{ i})$ & faulty input of round $i$, $i=0,1,\ldots,T-1$. \\ \rowcolor[gray]{.9} $(\hat{X}^{ T}, \hat{Y}^{ T})$ & faulty ciphertext. \\ $X^i + Y^i$ & `XOR' operation of $X^i$ and $Y^i$.\\ \rowcolor[gray]{.9} $X^i Y^i$ & `AND' operation of $X^i$ and $Y^i$.\\ $(x^i_j, y^i_j)$ & variables denoting bit $j$ of the input of the round $i$, $i=0,1,\ldots,T$, $ \quad j=0,1,\ldots,n-1$.\\ \rowcolor[gray]{.9} $(\hat{x}^{i}_j, \hat{y}^{i}_j)$ & variables denoting bit $j$ of the faulty input of the round $i$, $i=0,1,\ldots,T$, $ \quad j=0,1,\ldots,n-1$.\\ $x^i_{j} + y^i_{j}$ & bitwise 'XOR' operation of $x^i_j$ and $y^i_j$. \\ \rowcolor[gray]{.9} $x^i_{j} y^i_{j}$ & bitwise 'AND' operation of $x^i_j$ and $y^i_j$. \\ $K^i$ & the round key in round $i$, $i=0,1,\ldots,T-1$. \\ \rowcolor[gray]{.9} $k^i_{j}$ & $j^{th}, 0 \le j \le n-1$ bit round key of round $i$.\\ $\Delta^i$ & the difference between correct and faulty left inputs of round $i$, where $ 0 \le i < T$. \\ \rowcolor[gray]{.9} $\delta^i_{j}$ & the difference at bit $j$ of $\Delta^i$, where $ 0 \le i < T$, and $0 \le j < n$.\\ $S^a(X)$ & Circular left rotation of a $n$ bit word $X$ by $a$ bits.\\ \bottomrule \end{tabular} \end{table} \subsection{SIMECK Specification} The SIMECK family of lightweight block ciphers was introduced in CHES 2015~\cite{simeck} and was optimized for hardware implementations. Similar to SIMON, SIMECK is based on a typical Feistel design and comprises three simple operations, namely, the bit-wise `AND', `rotation' and `XOR' operations. Let $n$ denote the word size. Then, SIMECK$2n/4n$ refers to perform encryptions or decryptions on $2n$-bit message blocks using a $4n$-bit key, where $n = 16, 24$ or $32$ is called the word size of SIMECK$2n/4n$. \begin{figure}[ht] \centering \caption{One round of SIMECK block cipher} \label{fig:Simeck} \includegraphics[width=0.35\textwidth]{Simeck} \end{figure} Fig.~\ref{fig:Simeck} shows a round function of SIMECK. Basically, the design of this family is based on the balanced Feistel network. There are in total $32, 36$ and $44$ encryption rounds for SIMECK32/64, SIMECK48/96, an SIMECK64/128, respectively. In the following, let us consider encrypting a plaintext $P$. At each round $i$, the input message is divided into two words $X^i$ and $Y^i$, where $P = X^0 || Y^0$ is the $2n$-bit plaintext. The round function of SIMECK is defined as follows: \begin{equation}\label{eq:roundfunction} (X^{i + 1}, Y^{i + 1}) = (Y^i + F(X^i) + K^i, X^i) \end{equation} \noindent where $F(X) = X \cdot S^5(X) + S^1(X)$, $K^i$ is the round key at the round $i$, and $S^a$ denotes a circular left rotation by $a$ bits. Let $(x^i_{n - 1}, \ldots, x^i_{0})$, and $(y^i_{n - 1}, \ldots, y^i_{0})$ denote the input of round $i$ for $0 \le i \le T-1$. The following relations hold for any $j = 0,\ldots, n - 1$: \begin{align} \label{eq:simeck} &x^{i+1}_{j} = f(x^i_j) + y^i_{j} + k^{i}_{j}, \nonumber \\ &y^{i + 1}_{j} = x^i_{j}, \end{align} where $f(x^i_j) = (x^i_{j} \; \& \; x^i_{(j - 5) \bmod n}) + x^i_{(j - 1) \bmod n}$. As all indices are computed modulo $n$, in what follows, $x^i_{j}$ will denote $x^i_{j \bmod n}$, $x^i_{j} x^i_{j'}$ will denote $x^i_{j \bmod n} \; \& \; x^i_{j' \bmod n}$, and $x^i_{j} + x^i_{j'}$ will denote $x^i_{j \bmod n} \; + \; x^i_{j' \bmod n}$. \\ \noindent {\bf Key Schedule:} In SIMECK ciphers, the round key is generated from the master $K$ as follows. Firstly, the master is segmented into four words $K = (K^3, K^2, K^1, K^0)$, then for $i \ge 0$: $$K^{i + 4} = K^i + F(K^{i + 1}) + C + (z_j)_i,$$ where $C$ is a constant value defined by $C = 2^n - 4$, $(z_j)_i$ denotes the $i$-th bit of the sequence $z_j$. SIMECK32/64 and SIMECK48/96 use the same sequence $z_0$, which can be generated by the primitive polynomial $X^5 + X^2 + 1$ with the initial state $(1, 1, 1, 1, 1)$, whereas SIMECK64/128 uses the sequence $z_1$, which can be generated by the primitive polynomial $X^6 + X + 1$ with the initial state $(1, 1, 1, 1, 1, 1)$. Compared to SIMON ciphers, SIMECK ciphers are more efficient and compact hardware implementation due to its reuse of the round function with the round constant $C + (z_j)_i$ in the key scheduling algorithm. \subsection{Security Analysis on SIMECK Ciphers} Since SIMECK is based on SIMON and SPECK ciphers~\cite{BSS+13}, the security level of SIMECK ciphers is expected to be {\em comparable} to the those of SIMON ciphers. Since their publication, there have been a number of academic works analyzing the security of SIMECK ciphers~\cite{bagheri2015linear, kolbl2016brief, qiao2016differential, qin2016linear, zhang2016integral, zhang2017security, sadeghi2018improved}. We briefly recall a few attacks in this section. Kolbl and Roy~\cite{kolbl2016brief} performed differential and linear cryptanalysis~\footnote{Differential cryptanalysis is a chosen-plaintext attack that studies how differences in input can affect the resultant difference at the output. Linear cryptanalysis is a known-plaintext attack in which the attacker studies probabilistic linear relations (called linear approximations) between parity bits of the plaintext, the ciphertext, and the secret key.}~\cite{biham1991differential, matsui1993linear}, the two most widely used attacks on block ciphers. They managed to break up to 19/32, 26/36, and 33/44 rounds of SIMECK32/64, SIMECK48/96, and SIMECK64/128 ciphers, respectively, with higher probability. These results cover more rounds compared to those against SIMON ciphers~(see \cite[Table 6]{kolbl2016brief}). Then, an improved differential attack using the dynamic key-guessing technique~\cite{qiao2016differential} was able to break up to 22, 28, and 35 rounds of SIMECK32/64, SIMECK48/96, and SIMECK64/128 ciphers. Even better, using the same technique with linear hull cryptanalysis, Qin et al.~\cite{qin2016linear} were able to break 1 or 2 more rounds compared to results in~\cite{qiao2016differential}. \subsection{Differential Fault Analysis (DFA) on SIMECK Ciphers} \subsubsection{Differential Fault Analysis} The {\it Differential Fault Analysis} or {\it DFA} was first proposed by Biham and Shamir in~\cite{BS97}. Unlike the statistical attacks mentioned above such as differential and linear attacks, which requires a large amount of data to perform an attack, a DFA attack is able to recover the full master key by using just a few pair of plaintexts/ciphertexts. In the Biham-Shamir's DFA attack against DES block cipher~\cite{DES}, an attacker will inject a fault in some rounds when executing a cryptographic implementation to obtain a faulty ciphertext. By analyzing the difference between the correct and faulty ciphertexts, the last round key could be revealed. Then, with the knowledge of the last round key, the attacker decrypts the correct ciphertext to obtain the input of the last round, which is the output of the second last round. After that, the attacker repeats this procedure to obtain more round keys until the master key can be deduced by the key schedule. Subsequently, various DFA attacks on block ciphers have also been carried out, including attacks against AES~\cite{Gir04}, Triple DES~\cite{HJQ04}, IDEA~\cite{CGV08}, SIMON and SPECK~\cite{tupsamudre2014differential, LYK19}, and SIMECK~\cite{NSS16}. \subsubsection{Fault Models} There exist various techniques to inject a fault into a computing device during its execution. Low-cost techniques include power glitch, clock tempering, or temperature variation~\cite{BDL97,KK99}. Kommerling and Kuhn reported that glitch attacks at the external power and clock supply lines are the most useful in practice~\cite{KK99}. High-cost techniques include light/laser injections or electromagnetic (EM) disturbances~\cite{SA02,SAS+02}. These techniques allow specific control of a single register, a bus, or memory. The fault characteristics resulting from a fault injection are commonly captured in a {\it fault model}. A fault model will indicate the following characteristics: the location of the fault, the number of bits affected by the fault, and the fault types. In~\cite{riviere2015novel}, Riviere {\it et al.} classified fault models as follows: \begin{itemize} \item {\em Bit-wise models}: in which faults will manipulate a single bit. There are five types of bit-wise fault models: bit-set, bit-flip, bit-reset, stuck-at, and random-value. \item {\em Byte-wise models}: in which faults will modify a byte at once. There are three types of byte-wise fault models: byte-set, byte-reset, or random-byte. \item {\em Wider models}: in which faults will manipulate an entire word that can be from 8 to 64 bits depending on the given architecture. \end{itemize} Theoretical works often assume that the attacker has a precise control on both timing and location, {\em i.e.}, he knows the attacked bit as well as the attacked operation. In practice, it would be more challenging to inject a fault into a precise bit. In this paper, we consider the bit-flip model in which a single bit will be flipped to its complementary value, either from 0 to 1 or from 1 to 0. We also assume that the location of the flipped bit is {\em unknown} to the attacker. \subsubsection{DFA attacks on SIMECK block cipher} In the following, we briefly review differential fault analysis against SIMECK cipher in the {\it bit-flip} and {\em random byte} fault models. \\\\ In~\cite{NSS16}, Nalla \emph{et al.} presented the first differential fault analysis against SIMECK ciphers. Specifically, they demonstrated two DFA attacks. The former makes use of the {\it bit-flip fault model} and could recover the $n$-bit {\em last round key} using $n/2$ bit faults. The latter makes use of the {\it random byte fault model} that is more practical and could retrieve the last round key using $n/8$ faults. The process could be repeated four times to recover 4 round keys that are enough to recover the full master key. Basically, their attacks mainly exploit the information leaked by the `AND' operation, which is the only non-linear function of SIMECK. Specifically, the attacker injects a fault in the intermediate left half ciphertext $X^{T-2}$, where $T$ is the number of rounds of SIMECK. If one of the two input bits of the `AND' operation is $0$, then flipping the other input bit does not affect the output bit of $X^{T-1} = Y^T$. From the following equation, we can observe that one can deduce the last round key $K^{T-1}$ if the value $X^{T - 2}$ is known. \begin{equation}\label{eq:lastroundkey} K^{T-1} = X^{T-2} + F(Y^T) + X^T \end{equation} Suppose that the $j^{th}$ bit of $X^{T - 2}$ was flipped, one is able to deduce the value of $(j - 5)^{th}$ and $(j + 5)^{th}$ bits of $X^{T - 2}$, and thus recover the corresponding bits of $K^{T - 1}$ using Eq.~(\ref{eq:lastroundkey}). In other words, $2$ bits of $K^{T - 1}$ will be disclosed with every bit flipped in $X^{T-2}$. Therefore, by assuming that one could control the injected fault location, it requires $n/2$ faulty ciphertexts to retrieve the $n$-bit key. However, if the attacker has no control over the location of the flipped bit, the average number of faults required is approximately double, namely, around $n$ faults.\\\\ \section{Preliminary Observations and Facts}\label{sec:observations} In this section, some facts and observations that can be used to analyze faults on SIMECK block ciphers will be discussed. First, we consider the following lemma. \begin{lemma}\label{lem:difference} Let $X^t = \{x^t_0, x^t_1 \ldots, x^t_{n - 1}\}$ and $\hat{X}^t = \{\hat{x}^{t}_{0}, \hat{x}^{t}_{1}, \ldots, \hat{x}^{t}_{n - 1}\}$ be the correct and faulty left inputs respectively of the intermediate $t$-th round, $0 \le t < T$. Let $\delta^t_j = x^t_j + \hat{x}^{t}_{j}$, for $0 \le j < n $, be the differential representation of two correct and faulty bits $x^t_j$ and $\hat{x}^{t}_{j}$. We have: \begin{dmath}\label{eq:difference} \delta^{t + 1}_j = \delta^t_{j} x^t_{j - 5} + \delta^t_{j - 5} x^t_{j} + \delta^t_{j} \delta^t_{j - 5} + \delta^t_{j - 1} + \delta^{t - 1}_j \end{dmath} \end{lemma} \begin{proof} From Eq.~(\ref{eq:simeck}), we have: \begin{align*} x^{t+1}_j &= x^t_{j} x^t_{j - 5} + x^t_{j - 1} + y^t_{j} + k^t_j, \quad \mbox{ and }\\ \hat{x}^{t+1}_j &= \hat{x}^{t}_{j} \hat{x}^{t}_{j - 5} + \hat{x}^{t}_{j - 1} + \hat{y}^{t}_{j} + k^t_{j} \end{align*} Note that $y^t_j = x^{t - 1}_j$. Then, summing up the two above equations gives: $$\delta^{t + 1}_j = x^t_{j} x^t_{j - 5} + \hat{x}^{t}_{j} \hat{x}^{t}_{j - 5} + \delta^t_{j - 1} + \delta^{t - 1}_j$$ We have: \begin{small} \begin{align*} &x^t_{j} x^t_{j - 5} + \hat{x}^{t}_j \hat{x}^{t}_{j - 5} \\&= (x^t_j + \hat{x}^{t}_j) (x^t_{j - 5} + \hat{x}^{t}_{j - 5}) + \hat{x}^{t}_j x^t_{j - 5} + x^{t}_j \hat{x}^{t}_{j - 5}\\& = \delta^t_j \delta^t_{j - 5} + (\hat{x}^{t}_j x^t_{j - 5} + x^t_j x^t_{j -8}) + (x^{t}_j \hat{x}^{t}_{j - 5} + x^t_j x^t_{j -8}) \\& = \delta^t_j \delta^t_{j - 5} + \delta^t_j x^t_{j - 5} + \delta^t_{j - 5} x^t_j \end{align*} \end{small} \noindent As a result, $\delta^{t + 1}_j = \delta^t_j x^t_{j - 5} + \delta^t_{j - 5} x^t_j + \delta^t_j \delta^t_{j - 5} + \delta^t_{j - 1} + \delta^{t - 1}_j$. \qed \end{proof} Lemma \ref{lem:difference} tells us that each bit $\delta^{t + 1}_j$ can be represented in terms of intermediate plaintext bits and input differences in the previous rounds. More particular, the value of $\delta^{t + 1}_j$ depends on 2 bits of the intermediate input $X^t$, $3$ bits of the input difference $\Delta^t$, and one bit of $\Delta^{t - 1}$. This allows us to construct a differential trail table to record and trace the $\delta^i_j$ values. Table~\ref{tab:trail_6rounds} shows the differential trail of SIMECK32/64 when we inject faults into the round $27$. The other trail tables are listed in Fig.~\ref{sec:appendix}. \begin{figure}[h] \centering\footnotesize \caption{Differential Trails of SIMECK Ciphers. Without loss of generality, we suppose that a fault will be injected into the bit $0$. The notation $*$ denotes for a complex non-linear expression of variables that is non-trivial to deduce their values.}\label{sec:appendix} \vspace{0.2cm} \begin{tabular}{|cp{7.5cm}|} \hline \multicolumn{2}{|c|}{SIMECK48/96}\\ &\\ $\Delta^{31}$ : & ($1$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$)\\ $\Delta^{32}$ : & ($x^{31}_{19}$, $1$, $0$, $0$, $0$, $x^{31}_{5}$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$)\\ $\Delta^{33}$ : & ($*$, $x^{32}_{20} + x^{31}_{19}$, $1$, $0$, $0$, $*$, $x^{32}_{6} + x^{31}_{5}$, $0$, $0$, $0$, $*$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$)\\ $\Delta^{34}$ : & ($*$, $*$, $x^{33}_{21} + x^{32}_{20} + x^{31}_{19}$, $1$, $0$, $*$, $*$, $x^{33}_{7} + x^{32}_{6} + x^{31}_{5}$, $0$, $0$, $*$, $*$, $0$, $0$, $0$, $*$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$)\\ $\Delta^{35}$ : & ($*$, $*$, $*$, $x^{34}_{22} + x^{33}_{21} + x^{32}_{20} + x^{31}_{19}$, $1$, $*$, $*$, $*$, $x^{34}_{8} + x^{33}_{7} + x^{32}_{6} + x^{31}_{5}$, $0$, $*$, $*$, $*$, $0$, $0$, $*$, $*$, $0$, $0$, $0$, $*$, $0$, $0$, $0$)\\ $\Delta^{36}$ : & ($*$, $*$, $*$, $*$, $x^{35}_{23} + x^{34}_{22} + x^{33}_{21} + x^{32}_{20} + x^{31}_{19}$, $*$, $*$, $*$, $*$, $x^{35}_{9} + x^{34}_{8} + x^{33}_{7} + x^{32}_{6} + x^{31}_{5}$, $*$, $*$, $*$, $*$, $0$, $*$, $*$, $*$, $0$, $0$, $*$, $*$, $0$, $0$) \\ &\\ \end{tabular} \begin{tabular}{|cp{7.5cm}|} \multicolumn{2}{|c|}{SIMECK64/128}\\ &\\ $\Delta^{39}$ : & ($1$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$)\\ $\Delta^{40}$ : & ($x^{39}_{27}$, $1$, $0$, $0$, $0$, $x^{39}_{5}$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$)\\ $\Delta^{41}$ : & ($*$, $x^{40}_{28} + x^{39}_{27}$, $1$, $0$, $0$, $*$, $x^{40}_{6} + x^{39}_{5}$, $0$, $0$, $0$, $*$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$)\\ $\Delta^{42}$ : & ($*$, $*$, $x^{41}_{29} + x^{40}_{28} + x^{39}_{27}$, $1$, $0$, $*$, $*$, $x^{41}_{7} + x^{40}_{6} + x^{39}_{5}$, $0$, $0$, $*$, $*$, $0$, $0$, $0$, $*$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$)\\ $\Delta^{43}$ : & ($*$, $*$, $*$, $x^{42}_{30} + x^{41}_{29} + x^{40}_{28} + x^{39}_{27}$, $1$, $*$, $*$, $*$, $x^{42}_{8} + x^{41}_{7} + x^{40}_{6} + x^{39}_{5}$, $0$, $*$, $*$, $*$, $0$, $0$, $*$, $*$, $0$, $0$, $0$, $*$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$, $0$)\\ $\Delta^{44}$ : & ($*$, $*$, $*$, $*$, $x^{43}_{31} + x^{42}_{30} + x^{41}_{29} + x^{40}_{28} + x^{39}_{27}$, $*$, $*$, $*$, $*$, $x^{43}_{9} + x^{42}_{8} + x^{41}_{7} + x^{40}_{6} + x^{39}_{5}$, $*$, $*$, $*$, $*$, $0$, $*$, $*$, $*$, $0$, $0$, $*$, $*$, $0$, $0$, $0$, $*$, $0$, $0$, $0$, $0$, $0$, $0$) \\ \hline \end{tabular} \end{figure} \begin{small} \begin{table*}[ht] \centering \caption{Differential trail for the left half of the last 7 rounds of SIMECK32/64 when flipping the least significant bit $0$ at the round $27$. The notation $*$ denotes a non-linear expression that would not be used in our attack.} \label{tab:trail_6rounds} \begin{tabular}{p{0.10\textwidth}p{0.10\textwidth}p{0.10\textwidth}p{0.10\textwidth}p{0.13\textwidth}p{0.10\textwidth}p{0.10\textwidth}p{0.07\textwidth}} \toprule \textbf{Bit} & ${\bf 0}$&${\bf 1}$&${\bf 2}$&${\bf 3}$&${\bf 4}$&${\bf 5}$&${\bf 6}$\\ \midrule \midrule \rowcolor[gray]{.9} $\Delta^{26}$ &$0$&$0$&$0$&$0$&$0$&$0$&$0$\\ $\Delta^{27}$ &$1$&$0$&$0$&$0$&$0$&$0$&$0$\\ \rowcolor[gray]{.9} $\Delta^{28}$ &$x^{27}_{11}$ & $1$ &$0$ & $0$ & $0$ & $x^{27}_5$ &$0$ \\ $\Delta^{29}$ & $*$ & $x^{28}_{12} + x^{27}_{11}$ & $1$ & $0$ & $0$ & $*$ & $x^{28}_{6} + x^{27}_{5}$ \\ \rowcolor[gray]{.9} $\Delta^{30}$ & $*$ & $*$ & $x^{29}_{13} + x^{28}_{12} + x^{27}_{11}$ & $1$ & $0$ & $*$ & $*$ \\ $\Delta^{31}$ & $*$ & $*$ & $*$ & $x^{30}_{14} + x^{29}_{13} + x^{28}_{12} + x^{27}_{11}$ & $*$ & $*$ & $*$ \\ \rowcolor[gray]{.9} $\Delta^{32}$ & ~ Known values &&&&&&\\ \bottomrule \end{tabular} \vspace{.3cm} \begin{tabular}{p{0.10\textwidth}p{0.10\textwidth}p{0.12\textwidth}p{0.06\textwidth}p{0.06\textwidth}p{0.06\textwidth}p{0.06\textwidth}p{0.06\textwidth}p{0.06\textwidth}p{0.07\textwidth}} \toprule {\bf Bit} & ${\bf 7}$ &${\bf 8}$ & ${\bf 9}$&${\bf 10}$&${\bf 11}$&${\bf 12}$&${\bf 13}$&${\bf 14}$&${\bf 15}$\\ \midrule \midrule \rowcolor[gray]{.9}$\Delta^{26}$ & $0$ & $0$ & $0$ & $0$ & $0$ & $0$ & $0$ & $0$ & $0$\\ $\Delta^{27}$ & $0$ & $0$ & $0$ & $0$ & $0$ & $0$ & $0$ & $0$ & $0$\\ \rowcolor[gray]{.9}$\Delta^{28}$ & $0$ & $0$ & $0$& $0$& $0$& $0$& $0$& $0$& $0$ \\ $\Delta^{29}$ & $0$ & $0$ & $0$& $*$ & $0$ & $0$ & $0$ & $0$& $0$ \\ \rowcolor[gray]{.9}$\Delta^{30}$ & $x^{29}_{7} + x^{28}_{6} + x^{27}_{5}$ & $0$ & $0$ & $*$& $*$ & $0$ & $0$ & $0$ & $*$ \\ $\Delta^{31}$ & $*$ & $x^{30}_{8} + x^{29}_{7} + x^{28}_{6} + x^{27}_{5}$ & $0$ & $*$ & $*$ & $*$ & $0$ & $0$ & $*$ \\ \rowcolor[gray]{.9}$\Delta^{32}$ & ~ Known values &&&&&&&&\\ \bottomrule \end{tabular} \end{table*} \end{small} \begin{small} \begin{table*}[htbp] \footnotesize \centering \caption{Differential trail for the left half of the last 6 rounds of SIMECK48/96 and SIMECK64/128 when a fault injected at the round $T - 5$ causing one bit flipped. The notation $*$ denotes an algebraic expression of immediate input bit variables.} \label{tab:zeros} \begin{tabular}{p{0.09\textwidth}p{0.08\textwidth}p{0.08\textwidth}p{0.08\textwidth}} \toprule {SIMECK48/96} & \multicolumn{3}{c}{Left Input Differences (Bit position) } \\ \rowcolor[gray]{.9}\textbf{Round} & 0--7 & 8--15 & 16--23\\ \midrule \midrule $\Delta^{31}$ & 10000000 & 00000000 & 00000000 \\ \rowcolor[gray]{.9}$\Delta^{32}$ & *1000*00 & 00000000 & 00000000 \\ $\Delta^{33}$ & **100**0 & 00*00000 & 00000000 \\ \rowcolor[gray]{.9} $\Delta^{34}$ & ***10*** & 00**000* & 00000000 \\ $\Delta^{35}$ & ****1*** & *0***00* & *000*000 \\ \rowcolor[gray]{.9}$\Delta^{36}$ & ******** & ******0* & **00**00 \\ \bottomrule \end{tabular} ~~~~~~ \begin{tabular}{p{0.09\textwidth}p{0.08\textwidth}p{0.08\textwidth}p{0.08\textwidth}p{0.08\textwidth}} \toprule SIMECK64/128 & \multicolumn{4}{c}{Left Input Differences (Bit position) } \\ \rowcolor[gray]{.9}\textbf{Round} & 0--7 & 8--15 & 16--23 & 24--31 \\ \midrule \midrule $\Delta^{39}$ & 10000000 & 00000000 & 00000000 & 00000000 \\ \rowcolor[gray]{.9}$\Delta^{40}$ & *1000*00 & 00000000 & 00000000 & 00000000 \\ $\Delta^{41}$ & **100**0 & 00*00000 & 00000000 & 00000000 \\ \rowcolor[gray]{.9}$\Delta^{42}$ & ***10*** & 00**000* & 00000000 & 00000000 \\ $\Delta^{43}$ & ****1*** & *0***00* & *000*000 & 00000000 \\ \rowcolor[gray]{.9} $\Delta^{44}$ & ******** & ******0* & **00**00 & 0*000000 \\ \bottomrule \end{tabular} \end{table*} \end{small} \begin{remark}[Input differences at the round $T - 2$.]\label{rem:deducedeltat2} Let $T$ be the number of round of a SIMECK cipher, given the left input differences at the rounds $T - 1$ and $T$ ({\em i.e.}, $\Delta^{T - 1}$ and $\Delta^T$, resp.), and the left input of the round $T - 1$, {\em i.e.}, $X^{T - 1}$, then the left input differences of the round $T - 2$ could be computed as follows: \begin{align}\label{eq:deduceDeltat2} \Delta^{T - 2} &= \Delta^{T - 1} S^5(X^{T - 1}) + S^5(\Delta^{T - 1}) X^{T - 1} \\ \nonumber & + \Delta^{T - 1} S^5(\Delta^{T - 1}) + S^1(\Delta^{T - 1}) + \Delta^{T} \end{align} \end{remark} Eq.~(\ref{eq:deduceDeltat2}) can be easily obtained because from Eq.~(\ref{eq:difference}) we have: \begin{equation*}\label{eq:deducedeltat2} \delta^{T - 2}_j = \delta^{T - 1}_j x^{T - 1}_{j - 5} + \delta^{T - 1}_{j - 5} x^{T - 1}_j + \delta^{T - 1}_j \delta^{T - 1}_{j - 5} + \delta^{T - 1}_{j - 1} + \delta^{T}_j \end{equation*} Once an attacker obtains the correct ciphertext $C = (X^T, Y^T)$ and the faulty ciphertext $\hat{C} = (\hat{X}^{ T}, \hat{Y}^{ T})$, s/he first computes values: $X^{T - 1} = Y^T$, $\hat{X}^{T - 1} = \hat{Y}^T$, $\Delta^{T} = X^T + \hat{X}^T$, and $\Delta^{T - 1} = X^{T - 1} + \hat{X}^{T - 1}$. Then, s/he is able to deduce the value of $\Delta^{T - 2}$ via Eq.~(\ref{eq:deduceDeltat2}). \begin{observation}[Fault Propagation] For each presence of fault in the round $t$ at the bit position $j$, {\em i.e.}, $\delta^t_j = 1$, it will affect into $3$ left input differences in the next round $t + 1$, they are values of $\delta^{t + 1}_{j}$, $\delta^{t + 1}_{j + 1}$, and $\delta^{t + 1}_{j + 5}$. \end{observation} From Lemma~\ref{lem:difference}, we have: \begin{align*} \delta^{t + 1}_j & = \delta^t_j x^t_{j - 5} + \delta^t_{j - 5} x^t_j + \delta^t_j \delta^t_{j - 5} + \delta^t_{j - 1} + \delta^{t - 1}_j \\ \delta^{t + 1}_{j + 1} & = \delta^t_{j + 1} x^t_{j - 4} + \delta^t_{j - 4} x^t_{j + 1} + \delta^t_{j + 1} \delta^t_{j - 4} + \delta^t_{j} + \delta^{t - 1}_{j + 1} \\ \delta^{t + 1}_{j + 5} & = \delta^t_{j + 5} x^t_{j} + \delta^t_{j} x^t_{j + 5} + \delta^t_{j + 5} \delta^t_{j} + \delta^t_{j + 4} + \delta^{t - 1}_{j + 5}. \end{align*} The values are dependent on the value of $\delta_{j}^{t}$. From Table~\ref{tab:trail_6rounds}, it can be seen that if one injects a fault at the bit position $0$ of the round $27$, that is, $\delta_0^{27} = 1$, then three bit positions $0, 1$ and $5$ at the round $28$ will be affected, they are $\delta^{28}_0$, $\delta^{28}_1$, and $\delta^{28}_5$. These faults continue propagating into the next round in the same way. \begin{lemma}\label{lem:numberzero} Suppose that a fault is injected into the left input of the round $t$ and one-bit flipped at the position $\ell$ is made, {\em i.e.}, $\delta^t_{\ell} = 1$ and $\delta^t_{j} = 0$ for $j \ne \ell$. Then, for $i \ge 1$, \begin{enumerate} \item $\delta^{t + i}_{\ell + i} = 1$ for $i \le \min\{4, \frac{n}{5}\}$ \item $\delta^{t + i}_{\ell + j} = 0$ for $1 \le i \le 3$, and $i < j \le 4$ \item $\delta^{t + i}_{\ell + j} = 0$ for $2 \le i \le 4$, and $i + 5 \le j \le i + 8$ \item $\delta^{t + i}_{j} = 0$ for $\ell + 5i < j < n + \ell$. \end{enumerate} \end{lemma} \begin{proof} This lemma can be easily proved due to Eq.~(\ref{eq:difference}). It can be seen that that the bit-flipped fault $\delta^{t}_{\ell}$ will affect to three input differences in the next round, that is, $\delta^{t + 1}_{\ell}$, $\delta^{t + 1}_{\ell + 1}$ and $\delta^{t + 1}_{\ell + 5}$. Bits at the position $j$, where $j \in [0, \ell)$ and $j \in (\ell + 5, n)$ will not be affected, {\em i.e.}, $\delta^{t + 1}_{j} = 0$. Furthermore, $\delta^{t + 1}_{\ell + 1} = \delta^t_{\ell} = 1$ and $\delta^{t + 1}_{\ell + j} = 0$, for $2 \le j \le 4$ due to Lemma~\ref{lem:difference}. Likewise, the rightmost bit position $\ell + 5$ at the round $t + 1$ will propagate faults into three bits in the next round $t + 2$ ({\em i.e.}, $\delta^{t + 2}_{\ell + 5}$, $\delta^{t + 2}_{\ell + 6}$ and $\delta^{t + 2}_{\ell + 10}$) and $\delta^{t + 2}_{\ell + 2} = \delta^{t + 1}_{\ell + 1} = 1$. The process will continue in the next round and so on. \qed \end{proof} \begin{observation}\label{obs:deducefromzeros} From Lemma~\ref{lem:difference}, we have: \begin{align*} \mbox{If } &\delta^t_j = 1 \,\, \& \,\, \delta^t_{j - 5} = 0, \,\, \mbox{then }\, x^t_{j - 5} = \delta^{t + 1}_j + \delta^t_{j - 1} + \delta^{t - 1}_j\\ \mbox{If } &\delta^t_j = 0 \,\,\& \,\, \delta^t_{j - 5} = 1, \,\, \mbox{then } x^t_{j} = \delta^{t + 1}_j + \delta^t_{j - 1} + \delta^{t - 1}_j\\ \end{align*} \end{observation} \begin{table}[htbp] \centering \caption{Recover $x^t_{j - 5}$ and $x^t_{j}$ from Observation~\ref{obs:deducefromzeros}}\label{tab:recover_twobits} \begin{tabular}{p{0.03\textwidth}p{0.03\textwidth}p{0.1\textwidth}p{0.1\textwidth}p{0.1\textwidth}} \toprule $\delta^t_j$ & $\delta^t_{j - 5}$ & $\delta^{t - 1}_j$ & $x^t_{j - 5}$ & $x^t_{j}$ \\ \midrule \midrule \rowcolor[gray]{.9}0 & 0 & known/unknown & unknown & unknown\\ 0 & 1 & known & unknown & $\delta^{t + 1}_j + \delta^t_{j - 1} + \delta^{t - 1}_j$\\ \rowcolor[gray]{.9}0 & 1 & unknown & unknown & unknown\\ 1 & 0 & known & $\delta^{t + 1}_j + \delta^t_{j - 1} + \delta^{t - 1}_j$ & unknown \\ \rowcolor[gray]{.9}1 & 0 & unknown & unknown & unknown\\ 1 & 1 & known/unknown & unknown & unknown\\ \bottomrule \end{tabular} \end{table} \noindent Table~\ref{tab:recover_twobits} shows the possibility to recover two bits $x^t_{j - 5}$ and $x^t_{j}$ based on the relation of $\delta^t_j$ and $\delta^t_{j - 5}$. \section{Differential Fault Analysis on SIMECK ciphers}\label{sec:bitflip} This section will describe our DFA attack against SIMECK lightweight block ciphers in the bit-flip model. Specifically, there will be one bit flipped when a fault is injected. Given a plaintext $P$, the SIMECK encryption function outputs the corresponding ciphertext $C$. Assume that a fault is injected into the input $X^t$ of an intermediate round $t$ and causes a bit-flip at the position $\ell$. Let $\hat{X}^{t}$ be the fault value, so $X^t$ and $\hat{X}^{t}$ will be different at the $\ell^{th}$ bit and identical everywhere else. In other words, if $(x^t_{0}, \ldots, x^t_{n - 1})$ and $(\hat{x}^t_{0}, \ldots, \hat{x}^t_{n - 1})$ are $n$-bits of $X^t$ and $\hat{X}^t$, respectively, then $x^t_j = \hat{x}^{t}_j + 1$ for $j = \ell$ and $x^t_j = \hat{x}^{t}_j$ for $j \ne \ell$. \subsection{Attack Description}\label{sec:attackdescription} We aim at recovering the full master key $K$ (equivalent to $4$ round keys) by injecting faults into a single round only. Faults will be injected at the round $T - 5$ and we try to obtain 4 round keys $K^{T - 1}, K^{T - 2}, K^{T - 3}$ and $K^{T - 4}$. For instance, in order to retrieve $4$ round keys of SIMECK32/64 ($K^{28}$, $K^{29}$, $K^{30}$, and $K^{31}$), we will inject faults into the round $27$. Our analytic attack based on the differential trail works as follows ({\sc Algorithm 1}):\\ \par\noindent\rule{0.49\textwidth}{1.6pt} \textbf{\sc Algorithm 1:} DFA attack on SIMECK ciphers \par\noindent\rule{0.49\textwidth}{0.6pt} \underline{\sc Step 1:} Choose a random plaintext $P$ to feed into the SIMECK encryption function, and get a ciphertext $C$ as return. \underline{\sc Step 2:} Re-run encryption with the above input $P$, and then inject a fault into the left input at the round $T - 5$. Without loss of generality, we suppose that this fault flips the least significant bit $x^{T - 5}_{0}$. \underline{\sc Step 3:} Find input differences of the subsequent rounds $T - 5 < t < T$, {\em i.e.}, $\Delta^t = X^t + \hat{X}^{ t}$. These input differences can be determined due to Lemma~\ref{lem:difference} and could be represented by $0, 1$ or algebraic expressions of other input variables. (as shown in Table~\ref{tab:trail_6rounds}). The differences for SIMECK32/64 when the bit $x^{27}_0$ flipped are listed in Table~\ref{tab:trail_6rounds}. Such differences for SIMECK48/96 and SIMECK64/128 are listed in Fig~\ref{sec:appendix}. It can be seen that each round contains $2$ linear expressions to express the differences between correct and faulty intermediate ciphertexts. \underline{\sc Step 4:} Deduce bits of $X^{T - 2}$, \begin{itemize} \item \underline{From linear expressions}: As $\Delta^{T}, \Delta^{T - 1}$, and $\Delta^{T - 2}$ are known, the attacker can deduce two bits of $X^{T - 2}$ by summing up linear equations in two round $T - 2$ and $T - 1$. For example, if a fault was injected into the position $0$ at the round $27$ of SIMECK32/64, as shown in Table~\ref{tab:trail_6rounds}, the attacker can obtain the values of $x^{30}_{8}$ and $x^{30}_{14}$ by summing up $\delta^{31}_{8} + \delta^{30}_{7}$, and $\delta^{31}_{3} + \delta^{30}_{2}$, respectively. Let $\ell$ be the fault position at the round $T - 5$. As the fault will propagate to the position $\ell + 3$ at the round $T - 2$, the attacker will be able to deduce two bits $x^{T - 2}_{\ell - 2}$ and $x^{T - 2}_{\ell + 8}$. \item \underline{From Observation~\ref{obs:deducefromzeros}}: The attacker knows $\Delta^{T - 1}$, $\Delta^{T - 2}$ and some bits of $\Delta^{T - 3}$ according to Lemma~\ref{lem:numberzero}. Thus, if $\delta^{T - 2}_j = 1$ and $\delta^{T - 3}_j = 0$ (resp., $\delta^{T - 3}_{j + 5} = 0$), then thanks to Observation~\ref{obs:deducefromzeros} the attacker can deduce two bits $x^{T - 2}_{j - 5}$ (and $x^{T - 2}_{j + 5}$, resp.). \end{itemize} \underline{\sc Step 5:} After obtaining bits of $X^{T - 2}$, the attacker can retrieve the corresponding bits of the last round key $K^{T - 1}$ due to Eq.~(\ref{eq:lastroundkey}). He/she repeats steps 2--4 with different flipped bit position to recover the full round key $K^{T - 1}$. \underline{\sc Step 6:} Decrypt the last round using $K^{T - 1}$ to get $(X^{T - 1}, Y^{T - 1}) (=(X^{T - 1}, X^{T - 2})) $ and $(\hat{X}^{ T - 1}, \hat{Y}^{ T - 1}) = ((\hat{X}^{ T - 1}, \hat{X}^{ T - 2}))$. Again, as the values $\Delta^{T - 1}$, $\Delta^{T - 2}$, and $X^{T - 2}$ are known, the attacker could compute $\Delta^{T - 3}$ due to Eq.~(\ref{eq:difference}). He/she then repeats steps 4 and 5 to obtain the round key $K^{T - 2}$. The attacker continues this process to retrieve two more round keys $K^{T - 3}$ and $K^{T - 4}$. \underline{\sc Step 7:} With $4$ round keys, the attacker could deduce the master key $K$ of a SIMECK block cipher by the key schedule. \par\noindent\rule{0.49\textwidth}{1.6pt} From {\sc Step 4}, it can be seen that for each bit $1$ of $\Delta^{T - 2}$, the attacker may recover $2$ bits of $X^{T - 2}$ (corresponding to two bits of $K^{T - 1}$). Likewise, once $K^{T - 1}$ is recovered, that attacker knows $\Delta^{T - 2}$, $\Delta^{T - 3}$ and some bits of $\Delta^{T - 4}$, he then may be able to recover two bits of $X^{T - 3}$ (corresponding to two bits of $K^{T - 2}$) with each bit $1$ of $\Delta^{T - 3}$ and so on. \begin{table*}[t] \small \centering \caption{Comparisons of the Fault analysis attacks on SIMECK ciphers \label{tab:comparison} \begin{tabular}{l|cc|ccc} \toprule \multirow{3}{*}{SIMECK$2n/4n$} & \multicolumn{2}{c|}{Nalla \emph{et al.}~\cite{NSS16}} & \multicolumn{3}{c}{Our work} \\\cline{2-6} & Locations of faults to & No of faults * & Locations of faults to & No of faults & No of faults \\%\cline{2-6} & recover master key & (Last round key) & recover master key & (Last round key) & (Master key) \\ \midrule \midrule \rowcolor[gray]{0.9} SIMECK32/64 & $30, 29, 28, 27$ & $28.32$ & $27$ & $12.12$ & $25.78$ \\ SIMECK48/96 & $34, 33, 32, 31$ & $41.44$ & $31$ & $22.88$ & $43.56$ \\ \rowcolor[gray]{.9} SIMECK64/128 & $42, 41, 40, 39$ & $57.06$ & $39$ & $30.14$ & $89.51$ \\ \bottomrule \end{tabular} \end{table*} \subsection{Fault Position}\label{sec:faultposition} In this section, we will discuss how the attacker determines the position of a fault. \subsubsection{Determining fault position in SIMECK64/128.} A fault will be injected into the round $39$ at the position $\ell$, that is, $\delta^{39}_{\ell} = 1$. An attacker will use on the following facts to deduce the value of $\ell$: \begin{itemize} \item From Lemma~\ref{lem:numberzero}, the input differences at the round $42$ will have $16$ consecutive zeros (see Table~\ref{tab:zeros}). \item The fault position $\ell$ will be propagated and shifted right three positions at the round $42$, that is $\delta^{42}_{\ell + 3} = 1$. \item There is a pattern $10***00**000* \underbrace{00\ldots0}_{16 \, digits}$, where the value of $*$ could be 1 or 0. The position of the first $1$ in this pattern will be $\ell + 3$. This pattern consists of $29$ digits out of $32$ digits of $\Delta^{42}$. \end{itemize} \subsubsection{Determining fault position in SIMECK48/96.} A fault will be injected into the round $31$ at the position $\ell$, that is, $\delta^{31}_{\ell} = 1$. Likewise, an attacker will use on the following facts to deduce the value of $\ell$: \begin{itemize} \item From Lemma~\ref{lem:numberzero}, the input differences at the round $34$ will have $8$ consecutive zeros (see Appendix~\ref{sec:appendix}). \item The fault position $\ell$ will be propagated and shifted right three positions at the round $34$, that is $\delta^{34}_{\ell + 3} = 1$. \item There is a pattern $10***00**000* \underbrace{00\ldots0}_{8 \, digits}$, where the value of $*$ could be 1 or 0. The position of the first $1$ in this pattern will be $\ell + 3$. This pattern consists of $21$ digits out of $24$ digits of $\Delta^{34}$. \end{itemize} \subsubsection{Determining fault position in SIMECK32/64.} As there is no consecutive bit zero determined by Lemma~\ref{lem:numberzero}, determining the fault position for SIMEC 32/64 is challenging. However, we still have this pattern $10***00**000$ in $16$ bits of $\Delta^{30}$, where the value of $*$ could be 1 or 0. The first $1$ in this pattern will be $\ell + 3$, where $j$ is the fault position injected at the round $27$. Based on the above facts and given that $\Delta^{T - 2}$ is known, the attacker also can deduce the fault position $\ell$ at the round $T - 5$ with high confidence. \section{Experiments}\label{sec:simulation} \subsection{Setup} To verify our proposed attack, we implemented a software simulation against all three SIMECK family members in C programming language\footnote{The source code could be found in the link \url{https://github.com/dple/DFA_Simeck}}. In this simulation, we suppose that the attacker cannot control the position of the faults. He thus may inject faults into the same position many times until fully recovering one round key or the master key. Once a {\em random} fault is injected into the left input of the round $i$ at the bit $j$, only the differential input $\delta_j^i$ will be equal to one, differential inputs at other positions will be zero. The positions of the faults were generated {\em randomly} and {\em independently}. For each cipher member, we repeat the experiment 10,000 times and report the average number of faulty ciphers required to recover the last round key $K^{T - 1}$ and the whole master key (corresponding to the last 4 round keys $K^{T - 1}$, $K^{T - 2}$, $K^{T - 3}$, and $K^{T - 4}$). The only purpose of recovering the last key is to compare our attacks to the ones in~\cite{NSS16}. \subsection{Simulation Results} \begin{figure*} \centering \caption{Histogram of the number of faults required to recover keys. The number of samples is 10,000. Frequency density is represented on the vertical axis and the number of fault injections is represented on the horizontal axis.}\label{fig:histogram} \includegraphics[width=0.75\textwidth]{histogram.png} \end{figure*} Fig.~\ref{fig:histogram} shows a histogram of the number of fault injections to obtain the last round key and the full master key of all three variants of SIMECK block cipher. The horizontal axis represents the number of faults, and the vertical axis represents the frequency experiments requiring that number of faults. The total number of experiments is 10,000, as mentioned in the previous section. As seen in Fig.~\ref{fig:histogram}, all histograms are right-skewed. In order to recover the last round key in SIMECK32/64, it requires from a few fault injections to about 70 fault injections. However, most of the experiments only required around 9-13 fault injections. Likewise, the maximum number of fault injections required to recover the full master key is about 90; however, most of the experiments only required around 19-25 fault injections. Table~\ref{tab:comparison} compares the round locations, in which faults are induced, the number of faults required between our attacks, and Nalla \emph{et al.}'s attack under the one bit-flip model. From Table~\ref{tab:comparison}, it can be seen that our fault analysis attack requires much fewer faults than Nalla \emph{et al.}'s attack to recover the last round key for all three members of SIMECK. Even more, our attack to recover the whole master key of SIMECK32/64 also requires fewer faults than theirs for only the last round key. Last but not least, in order to recover the whole master key, while our attack injects the faults into a single round only, Nalla \emph{et al.}'s attack has to inject faults into $4$ different rounds of a SIMECK cipher. As a result, our attack is more {\em practical}. \subsection{Discussions} The proposed attack is based on an analytic method, which analyzes the differential trail between the correct and faulty ciphertexts to deduce the intermediate inputs, and then round keys. The key point in this method is to find the differential trail that is not too complicated to analyze. Compared to theoretical attacks~\cite{bagheri2015linear, qiao2016differential, zhang2016integral, zhang2017security}, this method is more straightforward, but we demonstrated that the attack is {\em effective}. In this paper, we use only linear expressions to analyze, however, non-linear expressions (e.g., quadratic expressions denoted as $*$ in Table~2 and Fig.~2) may be useful for more-in-depth analyses. Block ciphers with more complicated round functions would be resistant to the proposed attack, e.g., using a non-linear S-box. However, this will trade-off with the performance of the implementation. \section{Conclusion}\label{sec:conclusion} In this paper, we have proposed an improved fault attack on the SIMECK lightweight block ciphers under the one bit-flip model. In this model, we assume that a single bit will be flipped to its complementary value once a fault was successfully injected. We also assume that the attacker has no control over the location of the flipped bit. The advantage of our attack is that not only it requires less number of faults, but also faults need to be injected into only a {\em single round} of the ciphers in order to recover the whole master key. As a result, it makes our attack more {\em practical}. We demonstrated the effectiveness of our attack by simulating in C for all three members of SIMECK ciphers. Our experimental results over $10,000$ times showed that the attack requires $25.78$, $43.56$, and $89.51$ faults on average to recover the full master key of the SIMECK32/64, SIMECK48/96, and SIMECK64/128, respectively. \bibliographystyle{IEEEtran}
{'timestamp': '2020-10-13T02:24:07', 'yymm': '2010', 'arxiv_id': '2010.05296', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05296'}
arxiv
\section{Introduction} \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{Fig1.pdf} \caption{Example of an ambiguous experiment (without inoculation). A model is trained on ambiguous data whose labels are consistent with either a linguistic or a surface generalization, and tested on disambiguating data whose labels support only the linguistic generalization. Light green and dark red shading represents data or features associated with the positive and negative labels/predictions, respectively.} \label{fig:POS_example} \end{figure} Self-supervised pretraining through language modeling on massive datasets has revolutionized NLP. One reason this method works is that pretraining shapes a model's hypothesis space, giving it inductive biases that help it learn linguistic tasks \cite{howard2018universal}. Numerous probing studies have provided support for this idea by showing that language models learn representations that encode linguistic features \cite{gulordava2019colorless,tenney2019you,hewitt2019structural}. However, feature learning is just the first step to acquiring helpful inductive biases. Models must also be able to learn which features matter. The NLU datasets these models are often fine-tuned on are ambiguous and contain artifacts, and often support multiple possible generalizations. Neural networks are not mind readers: Models that have been shown to represent linguistic features sometimes fail to use them during fine-tuning on NLU tasks, instead adopting shallow surface generalizations \cite{jia2017adversarial,mccoy2019right}. To this end, recent work in probing pretrained models advocates for shifting the focus of study away from whether they represent linguistic features and in favor of whether they learn \emph{useful} representations of those features \cite{voita2020information,pimentel2020information,elazar2020amnesic}. \begin{table*}[ht!] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{lllll} \toprule & \bf Feature type & \bf Feature description & \bf Positive example & \bf Negative example\\\midrule \multirow{5}{*}{\rotatebox[origin=c]{90}{\bf Surface}} & Absolute position & Is the first token of S ``the''? & The cat chased a mouse. & A cat chased a mouse. \\ & Length & Is S longer than $n$ (e.g.,~3) words? & The cat chased a mouse. & The cat meowed. \\ & Lexical content & Does S contain ``the''? & That cat chased the mouse. & That cat chased a mouse. \\ & Relative position & Does ``the'' precede ``a''? & The cat chased a mouse. & A cat chased the mouse. \\ & Orthography & Does S appear in title case? & The Cat Chased a Mouse. & The cat chased a mouse. \\\midrule \multirow{4}{*}{\rotatebox[origin=c]{90}{\bf Linguistic}} & Morphology & Does S have an irregular past verb? & The cats slept. & The cats meow. \\ & Syn. category & Does S have an adjective? & Lincoln was tall. & Lincoln was president. \\ & Syn. construction & Is S the control construction? & Sue is eager to sleep. & Sue is likely to sleep. \\ & Syn. position & Is the main verb in ``ing" form? & Cats who eat mice are purring. & Cats who are eating mice purr. \\\bottomrule \end{tabular}% } \caption{Schematic examples of the linguistic and surface features in our experiments.} \label{tab:features} \end{table*} We investigate how RoBERTa \cite{liu2019roberta} acquires language-specific inductive biases during self-supervised pretraining. We track separately how RoBERTa's representation of linguistic features and its preferences for linguistic generalizations over surface generalizations change as the amount of pretraining data increases. We pretrain RoBERTa from scratch on datasets ranging from 1M to 1B words and evaluate these models alongside RoBERTa$\subtxt{BASE}$ in a series of experiments to probe the inductive biases of a pretrained model at the time of fine-tuning on a downstream task. We probe these models in three kinds of experiments: First, we conduct \emph{control} experiments where we fine-tune models on unambiguous binary classification tasks to test whether they learn to represent simple linguistic and surface features. Second, we conduct \emph{ambiguous} experiments following the \emph{poverty of the stimulus} design \cite{wilson2006learning}, as illustrated in Figure \ref{fig:POS_example}. In these experiments, we fine-tune a pretrained model on an ambiguous binary classification task in which the training set is consistent with both a linguistic generalization and a surface one. We then test the classifier on disambiguating data to reveal which generalization the model adopted, and by extension its preference among the two features. Third, we conduct \emph{inoculation} experiments \citep[following][]{liu2019inoculation} to test how hard it is to sway a model with a surface bias to adopt a linguistic generalization. We do this by introducing small amounts of disambiguating data into an otherwise ambiguous training set. We automatically generate data for all these tasks, and call the resulting dataset MSGS\ (Mixed Signals Generalization Set), pronounced ``messages''. The results show that RoBERTa acquires a stronger linguistic bias as pretraining increases. RoBERTa$\subtxt{BASE}$ has the strongest linguistic bias, and requires little to no inoculating data to reliably make the linguistic generalization. In general, models with more pretraining data can generally be induced to adopt linguistic generalizations with less inoculating data. We also find a large gap between the amount of pretraining data that RoBERTa needs to learn the linguistic features necessary to generalize out-of-domain and the amount it needs to learns that it should \textit{prefer} those features when generalizing. The control experiments on unambiguous data reveal that models with little pretraining do actually represent the linguistic features, but nonetheless show a strong surface bias. In other words, the main contribution of pretraining to linguistic bias learning is devoted not to extracting features, but to learning which features matter. We conclude that helpful inductive biases can be learned through pretraining, but current models require abundant data to do so. The implications of this conclusion point in two directions: First, we can probably continue to pretrain on increasingly massive training sets to improve on the generalization and few-shot learning abilities of models like T5 \cite{raffel2019t5} and GPT-3 \cite{brown2020gpt3}. Second, since models learn useful features early, there is hope that future advances could accelerate by reducing the amount of data needed to learn which features matter. To aid in this effort, we release the MSGS dataset, our pretrained RoBERTas, and all our code: \href{https://github.com/nyu-mll/msgs}{\url{https://github.com/nyu-mll/msgs}}. \section{Inductive Bias} \paragraph{Background: Learning Inductive Bias} Any finite set of training examples shown to a learning algorithm like a neural network is consistent with infinitely many generalizable decision functions. Inductive biases are a learner's preferences among these functions. An inductive bias can eliminate certain possible functions altogether, or result in a preference for some over others \citep{haussler1988quantifying}. For instance, an RNN classifier is capable of representing \textit{any} function, but prefers ones that focus mostly on local relationships within the input sequence \citep{dhingra2018neural,ravfogel2019studying}. Some recent work seeks to design neural architectures that build in desirable inductive biases \cite{dyer2016recurrent,battaglia2018relational}, or compares the immutable biases of different architectures \cite{mccoy2020does,hu2020systematic}. However, inductive biases can also be \emph{learned} by biological \cite{harlow1949formation} and artificial systems alike \cite{lake2017building}. In the language model fine-tuning paradigm proposed by \citet{howard2018universal} and popularized by models such as BERT \citep{devlin2019bert}, a pretrained neural network plays the role of the learner. Pretraining adjusts a model's weights so that it will navigate the hypothesis space during training on a downstream task more effectively than a randomly initialized model. There is a difference between learning to extract a linguistic feature and acquiring a bias towards using it when generalizing. There is ample evidence that BERT encodes features such as syntactic category and constituency \citep{tenney2019you,clark2019does,hewitt2019structural}. The acquisition of linguistic features is a \emph{prerequisite} for a linguistic bias. However, these findings do not tell us if the model will make use of these features to form generalizations during target task training, or if it will fall back on surface features that account for most of the data. \begin{table*}[t] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{llrrl} \toprule \bf Dom. & \bf Split & $\textbf{L}_{\textbf{L}}$ & $\textbf{L}_{\textbf{S}}$ & \bf Sentence \\\midrule \multirow{4}{*}{In} & \multirow{2}{*}{Train (Ambiguous)} & 1 & 1 & These men weren't hating that this person who sang tunes destroyed the vase.\\ & & 0 & 0 & These men hated that this person who sang tunes was destroying some vase.\\ & \multirow{2}{*}{Inoc. (Disamb.)} & 1 & 0 & These men weren't hating that this person who sang tunes destroyed some vase.\\ & & 0 & 1 & These men hated that this person who sang tunes was destroying the vase.\\\midrule \multirow{4}{*}{Out} & \multirow{2}{*}{Test (Disamb.)} & 1 & 0 & These reports that all students built that school were impressing some children.\\ & & 0 & 1 & These reports that all students were building the school had impressed some children.\\ & \multirow{2}{*}{Aux. (Ambiguous)} & 1 & 1 & These reports that all students built the school were impressing some children.\\ & & 0 & 0 & These reports that all students were building that school had impressed some children.\\\bottomrule & \end{tabular}% } \caption{A full paradigm from the \paradigm{syntactic position $\times$ lexical content} task. $\textbf{L}_{\textbf{L}}$ and $\textbf{L}_{\textbf{S}}$ mark the presence of the linguistic feature (\emph{Is the main verb in the ``ing'' form?}) and surface feature (\emph{Does S contain ``the''?}), respectively. \emph{Dom.} is short for \emph{domain}.} \label{tab:paradigm} \end{table*} \paragraph{Methods: Measuring Inductive Bias}\label{sec:measuring} We conduct three kinds of experiments to probe a model's preference for linguistic or surface generalizations: unambiguous control experiments, fully ambiguous experiments, and partially ambiguous inoculation experiments. Figure \ref{fig:POS_example} gives an overview of the ambiguous experiment design. First, it only makes sense to compare a model's preference between two features if it actually represents both features. This is the goal behind \emph{control experiments}, in which we fine-tune RoBERTa to classify sentences based on a single linguistic or surface feature in a totally unambiguous setting. Second, we conduct \emph{ambiguous experiments} on models that pass the controls. We fine-tune a pretrained model on a binary sentence classification task using \emph{ambiguous} data, which equally supports both a simple linguistic generalization and a simple surface one. For example, Figure \ref{fig:POS_example} shows a linguistic task where sentences in the positive class are defined by having a main verb in the ``ing'' form. We make the training data ambiguous by introducing a surface feature that distinguishes the two classes: In all (and only) training examples with label 1, the word ``the'' precedes the word ``a''. Based on this training data, a model could reasonably adopt either a linguistic generalization or a surface one. We then test the classifier on disambiguating data to observe which generalization it made. In this kind of data, the labels align with the linguistic generalization, and contradict the surface one: For example, in Figure \ref{fig:POS_example}, ``a'' now always precedes ``the'' in the positive test examples with label 1. We quantify a model's inductive bias using a metric we call the \newterm{linguistic bias score} (LBS). We define LBS as the Matthews correlation between the model predictions and the labels on the disambiguating test set \cite{matthews1975correlation}. If LBS is 1, the learner shows a systematic linguistic bias. If LBS is -1, it shows a systematic surface bias. If LBS is 0, it shows neither bias. Finally, while the fully ambiguous experiments probe models' biases in an idealized setting, training data in more naturalistic contexts often does contain some evidence supporting a linguistic generalization over a simple surface one. To simulate this, we also conduct a series of \emph{inoculation experiments} \citep[following][]{liu2019inoculation}, in which we introduce small amounts of disambiguating data into an otherwise ambiguous training set. For each experiment, we replace 0.1\%, 0.3\%, or 1\% of the training data with examples that support the linguistic generalization and contradict the surface one. These experiments allow us to compare the strength of linguistic bias in models that show an overall surface bias: If two models adopt the surface generalization in the fully ambiguous case, we can still say that one has a stronger linguistic bias than the other if it requires less inoculation data to be swayed towards the linguistic generalization. \section{Evaluation Data} We introduce MSGS~(Mixed Signals Generalization Set), pronounced ``messages'', a dataset we design to be used in poverty of the stimulus and inoculation experiments. With the goal of contrasting inductive biases that are helpful and harmful in most NLP applications, the tasks in MSGS\ test a model's preferences for generalizations based on linguistic or surface features. \paragraph{Features under Study} Table \ref{tab:features} illustrates the 4 linguistic features and 5 surface features we consider.\footnote{We explored a slightly larger set of linguistic features and excluded several based on initial experiments showing our models did not encode them. For example, we constructed a task with the objective of identifying sentences that contain antonyms (e.g. \emph{The little girl likes the big dog.}), but found that only RoBERTa$\subtxt{BASE}$ could solve the unambiguous control task.} Each feature is meant to be representative of a broad category of features (e.g. morphological features), though the precise implementation of each feature is necessarily much narrower (e.g. \emph{Does the sentence have an irregular past verb?}). Forming generalizations based on surface features entails knowledge of the identity of certain words (in our case, only ``the'' and ``a''), the positional indices of words in the string, the total number of words in a string, or whether certain characters are lowercase or uppercase.\footnote{Although these are surface properties of the string, they are not all trivial for RoBERTa due to its subword tokenization.} Forming generalizations based on linguistic features requires more abstract knowledge of tense and inflectional morphemes, parts of speech, the control construction,\footnote{The \emph{control construction} is a syntactic construction in which a semantic argument of a predicate fills or \emph{controls} an argument slot of an embedded verb. The \emph{raising construction} is superficially similar, but the filler of the embedded argument slot is not a \emph{semantic} argument of the main predicate \cite{sag2003syntactic}. For instance, \emph{Sue is eager to sleep} is an example of control because the NP \emph{Sue} is the semantic subject of both \emph{eager} and \emph{sleep}. By contrast, \emph{Sue is likely to sleep} is an example of raising because \emph{Sue} is the semantic subject of \emph{sleep}, but not of \emph{likely}. These two phenomena have different syntactic derivations in some theories \cite{chomsky1981lectures}.} and hierarchical syntactic structures, none of which are encoded in the surface string. \paragraph{Dataset Structure}\label{sec:dataset} MSGS\ contains 20 ambiguous binary classification tasks each gotten by pairing one of 4 linguistic features with one of 5 surface features. We write $\textsc{feat}_1\times\textsc{feat}_2$ to denote a task that combines features $\textsc{feat}_1$ and $\textsc{feat}_2$. Each ambiguous dataset contains 50k sentences split into training, evaluation, and inoculation sets. MSGS\ also includes 9 unambiguous \newterm{control tasks}---one for each feature. Each control dataset contains 30k sentences split into training and evaluation sets. For ambiguous tasks, we generate data in paradigms of 8 sentences following a $2\times 2\times 2$ design, as shown in Table \ref{tab:paradigm}. We vary the following three features: a binary linguistic feature, a binary surface feature, and the domain from which the sentence is sampled. We generate in-domain and out-of-domain sentences from different templates (see \S\ref{sec:data_generation}:\nameref{sec:data_generation} for more detail). As shown in Table \ref{tab:paradigm}, we split the data into four contrasting pairs with different purposes: (1) \emph{Training data} is ambiguous in-domain data makes up 99\% to 100\% of the training set. (2) \emph{Inoculating data} is disambiguating in-domain data which makes up 0.1\% to 1\% of the training set in experiments with inoculation. We show the classifier only the linguistic label ($\textbf{L}_{\textbf{L}}$) to nudge it towards adopting a linguistic generalization. (3) \emph{Test data} is disambiguating out-of-domain data used to test whether the model adopted the linguistic or surface generalization. (4) \emph{Auxiliary data} is ambiguous out-of-domain data used to test how well the model adapts to the out-of-domain templates, regardless of which generalization it makes. For control tasks, we generate data in paradigms of 4 sentences following a $2\times 2$ design by varying the feature and domain. We use control tasks to test whether each pretrained model represents each feature well enough to fine-tune an effective classifier in an unambiguous setting. \begin{figure*}[t] \centering \includegraphics[width=\textwidth]{control_results.pdf} \caption{Results on the main experiments measured in Matthews correlation for the surface control tasks (top) and linguistic control tasks (bottom). Note: For surface tasks a positive score represents a surface generalization.} \label{fig:control_results} \end{figure*} \paragraph{Data Generation}\label{sec:data_generation} The data is generated from templates using a generation toolkit from \citet{warstadt2020blimp}. This toolkit includes a vocabulary of over 3000 entries labeled with grammatical features that allow for lexical variation in the data while maintaining grammatical well-formedness. Although generated sentences often describe unlikely or implausible scenarios (e.g., \emph{The lawyer was sinking all canoes}), semantic plausibility is independent of all the features we examine, so this should not affect a model that genuinely encodes these features. To prevent out-of-vocabulary tokens affecting our results, we ensure that every word stem in the vocabulary appears in the pretraining datasets for our RoBERTa models (see \S \ref{sec:pretraining_data}). Our experimental logic only makes sense if we are reasonably confident that models can only achieve high test performance by genuinely adopting a linguistic generalization. However, training models on generated data can easily lead to overfitting, and classifiers trained and tested on data from the same domain can achieve perfect performance even on arbitrary tasks with random labels \cite{hewitt2019control}. For this reason, our primary evaluations test models' ability to \emph{generalize} out-of-domain. We manipulate domain in two ways: First, we generate training data and test data for each dataset from separate in-domain and out-of-domain templates. Thus a model cannot succeed at test time simply by recognizing a template or a key part of a template. For example, in the \paradigm{syntactic position $\times$ lexical content} paradigm shown in Table \ref{tab:paradigm}, the in-domain data contrasts the main verb with a verb in a relative clause embedded in the complement clause of a verb; while the out-of-domain data contrasts the main verb with a verb in the complement clause of a noun. In most tasks, each domain itself is generated from multiple templates as well to widen the domain and encourage better generalization during training. Second, on tasks that test lexical knowledge (for instance, the knowledge that \emph{slept} is an irregular past verb and \emph{meow} is not), we divide the crucial lexical items into in-domain and out-of-domain sets. Thus, a model cannot succeed by memorizing the keywords associated with each class. See the Appendix for a more detailed description of the implementation details for each feature. \begin{figure*}[t] \centering \includegraphics[width=\textwidth]{violin.pdf} \caption{Results measured in LBS for each pretraining and inoculating data amount, aggregated over the 20 tasks in MSGS. We exclude models that fail the corresponding controls, as described in Section \ref{sec:results}. High density near LBS of 1 means many models in that group have a linguistic bias; high density near -1 means many models have a surface bias. Models with stronger linguistic bias achieve higher LBS with less inoculation data.} \label{fig:violin_plot} \end{figure*} \section{Models, Pretraining, \& Fine-Tuning} We test 13 RoBERTa models in our main experiments: We pretrain 12 from scratch, and also test RoBERTa$\subtxt{BASE}$ pretrained by \citet{liu2019roberta}. \subsection{Pretraining}\label{sec:pretraining_data} \paragraph{Pretraining Data} We pretrain RoBERTa using scaled-down recreations of the dataset used by \citet{devlin2019bert} to train BERT, i.e English Wikipedia (2.5 billion tokens) and BookCorpus (800 million tokens). Both are included in the RoBERTa pretraining data.\footnote{RoBERTa uses English Wikipedia, BookCorpus, CC-News, OpenWebText, and STORIES in pretraining.} We download the latest Wikipedia dump as of Feb 1, 2020. The original BookCorpus \citep{zhu2015aligning} is no longer available, so we collect similar data from Smashwords, the original source of BookCorpus.\footnote{We collect our data using the Wikipedia XML dump \href{https://dumps.wikimedia.org/mirrors.html}{https://dumps.wikimedia.org/mirrors.html} and data-processing code \href{https://github.com/attardi/wikiextractor}{https://github.com/attardi/wikiextractor}, and a Smashwords crawler \href{https://github.com/soskek/bookcorpus}{https://github.com/soskek/bookcorpus}.} We pretrain RoBERTa on four training sets containing different numbers of words: 1M, 10M, 100M, and 1B.\footnote{The publicly available RoBERTa$\subtxt{BASE}$ is trained on 160GB of data, which we estimate to be about 30B words.} To make these datasets, we sample entire Wikipedia articles and Smashwords books independently, keeping the proportions of Wikipedia and Smashwords text approximately constant. \paragraph{Model Sizes} Model size is the only hyperparameter we systematically search over during pretraining. We consider smaller model sizes to prevent overfitting on small training sets. The detailed configurations of the model sizes are summarized in the Appendix. We use RoBERTa$\subtxt{BASE}$ from \citet{liu2019roberta} as our largest model size. The other configurations represent a scale roughly based on settings used in \citet{sanh2019distilbert}, \citet{vaswani2017attention}, \citet{jiao2019tinybert}, and \citet{tsai2019small}. \paragraph{Search Range} For dropout, attention dropout, learning rate decay, weight decay and the Adam parameters, we adopt the same parameter values used in \citet{liu2019roberta}. We fix warm up steps to be 6\% of max steps, peak learning rate to be 5e-4, early stopping patience to be 100M tokens, and heuristically define the search range of model size, max steps and batch size for each training set. \paragraph{Search Results} We randomly sample hyperparameters from the search range and train 25 models for each of the 1M, 10M, 100M datasets. We train 10 models on the largest (1B) dataset due to resource limitations. For each training set size, we choose three of the resulting models to evaluate. In order to avoid confounds caused by different model sizes, for each training set we choose three models of the same size that have the lowest perplexity. The hyperparameters and validation perplexities of the selected models are listed in the Appendix. \subsection{Fine-Tuning} We loosely follow the hyperparameter settings that \citet{liu2019roberta} used for fine-tuning on GLUE tasks \cite{wang2018glue}, and use the following learning rates: \{1E-5, 2E-5, 3E-5\}. We depart from \citeauthor{liu2019roberta}\ in using a batch size of 16 and training for 5 epochs without early-stopping in all runs. These changes are based on pilots that showed that larger batch sizes and longer fine-tuning were no more effective for our tasks. We conduct 3,471 fine-tuning runs: We fine-tune 13 RoBERTa models: (3 random initializations) $\times$ (4 pretraining data amounts) $+$ (1 RoBERTa$\subtxt{base}$). We fine-tune each model 267 times: (3 learning rates) $\times$ ((9 control tasks) $+$ (20 ambiguous tasks) $\times$ (4 inoculation amounts)). We evaluate model performance using LBS (see \S \ref{sec:measuring}:\nameref{sec:measuring}). \begin{figure*}[t] \centering \includegraphics[width=\textwidth]{main_figure.pdf} \caption{Results of the ambiguous binary classification tasks measured in LBS for every (linguistic feature, surface feature) pair. Each plot in the matrix shows the results on the disambiguating test items after training on an ambiguous task. All experiments on the same row investigate the same linguistic feature; all experiments on the same column investigate the same surface feature. Each data point represents one run. The x-axis of the point is the pretraining size of the model, and the y-axis is its LBS. Models with stronger linguistic bias achieve higher LBS with less inoculation data. Gray points show runs where the corresponding controls did not pass. A black-and-white version of this figure separating color channels into separate plots, can be found in the Appendix.} \label{fig:main_results} \end{figure*} \section{Results \& Discussion}\label{sec:results} We have several main findings: (1) models learn to \emph{represent} both surface features and linguistic features with relatively little data; (2) RoBERTa begins to acquire a linguistic bias with over 1B words of pretraining data; (3) increasing pretraining data strengthens linguistic bias; (4) there is considerable variation in models' preferences between specific pairs of linguistic and surface features. \paragraph{Control results} Figure \ref{fig:control_results} shows the results for the controls. Performance is near ceiling for most models and features. Because we evaluate all the models out-of-domain, this result cannot be explained by the models simply memorizing the features from the task training data. Thus, we conclude that most pretrained models we test encode both linguistic and surface features. The only exceptions are the syntactic category and syntactic construction features, for which models with less than 100M perform poorly. In subsequent plots, we filter out results where the controls are not passed. Specifically, if a particular combination of model checkpoint and learning rate achieves a Matthews correlation of less than 0.7 on the control task for feature $F$, we eliminate all results with this combination for any task involving $F$ in Figure \ref{fig:violin_plot}, or represent them as gray points in Figure \ref{fig:main_results}. \paragraph{Main Experiment Results} Figure \ref{fig:violin_plot} summarizes the main experiment results. For a given amount of pretraining and inoculation data, we consider all classifiers trained on all 20 tasks in MSGS and plot the density of their linguistic bias scores (LBSs). The results in the leftmost box (with 0\% inoculation) show that only RoBERTa$\subtxt{BASE}$ demonstrates a consistent linguistic bias in the fully unambiguous setting. That said, it still adopts the surface bias much of the time. The other models show a clear surface bias overall. The results of experiments with inoculation data show that models with more pretraining data require less inoculation data to be swayed towards the linguistic generalization. We consistently observe, for each pretraining quantity, a phase transition where the linguistic generalization begins to overtake the surface generalization upon exposure to a certain amount of inoculating data. For example, the 1B model goes through this transition between 0.1\% and 0.3\% inoculating data. The 100M and 10M models go through this transition between 0.3\% and 1\% inoculating data. The phase transition comes earlier for models with more pretraining, indicating they have a stronger linguistic bias. We also notice distinctive behavior for the models at the extreme ends of pretraining data quantity: The 1M model never completes the transition, suggesting it has a strong surface bias, and RoBERTa$\subtxt{BASE}$ appears to be in the middle of this transition with 0\% inoculating data, suggesting that even more pretraining data could produce a model with a more consistent linguistic bias. These findings are echoed in individual task results in Figure \ref{fig:main_results}.\footnote{Analogous results for the held out training-condition data, inoculation data, and auxiliary data are in the Appendix.} In each plot, models with the same amount of inoculation data (i.e. points with a given color) have higher LBS as the amount of pretraining data increases. Notably, on ambiguous tasks involving \paradigm{lexical content}, RoBERTa$\subtxt{BASE}$ usually favors generalizations based on linguistic features without any inoculating data, which no other pretrained model does. We find this result quite striking: Even if the labels are perfectly correlated with the presence or absence of the word ``the'', RoBERTa$\subtxt{BASE}$ overlooks that fact in favor of a deeper generalization based on an abstract feature like the inflectional form of a verb in a particular syntactic position. Furthermore, this preference is clearly \emph{acquired} through additional pretraining. The results for \paradigm{morphology $\times$ orthography} is a typical illustration of the differences between models. The 1M model never adopts the linguistic generalization based on the morphological feature, though it eventually rejects the surface generalization. The 100M and 1B models make robust linguistic generalizations only with 1.0\% inoculating data. By contrast, RoBERTa$\subtxt{BASE}$ requires only 0.1\% inoculating data (i.e.~10 out of 10k examples) to adopt the linguistic generalization. \paragraph{Surface Biases of RoBERTa} Our results also suggest some specific conclusions about which kinds of surface features RoBERTa pays attention to.\footnote{MSGS\ does not come close to representing the full range of possible relevant lexical or syntactic features, preventing us from making strong conclusions about which specific linguistic features RoBERTa has biases in favor of.} For instance, these models have little preference for sentence length. As shown in the second column of Figure \ref{fig:main_results}, most of the models form linguistic generalizations rather than generalizations based on sentence length, even with no inoculating data. By contrast, the models strongly prefer generalizations based on orthography---and to a lesser extent lexical content and word order---over linguistic generalizations. \paragraph{The Success of Pretrained Models} Our findings provide insight into why pretraining on massive datasets is so successful. While linguistic feature learning is a major effect of pretraining, it is far from the end of the story: Pretraining also helps models learn which features are central to language. However, this second kind of learning seems to require far more exposure to data with current models and pretraining techniques. Therefore, massive datasets are needed to teach models which features are useful for generalizing. The data scale at which we observe RoBERTa beginning to show a linguistic bias (between 1B and 30B words) is similar to the amount of pretraining data used by the first pretrained LMs to achieve major successes at NLU tasks, such as ELMo \cite{peters2018elmo} and BERT \cite{devlin2019bert}. This suggests a crucial data threshold below which language model pretraining is unlikely to be significantly helpful for most applications with current model architectures, and may explain the many-year gap between the development of neural LMs and the first major applications of LM pretraining: The early LMs must have not have been trained sufficiently to cross that threshold, yielding consistently poor results. \section{Related work} There is increasing interest in studying the inductive biases of neural networks. Much of this work has grown out of numerous findings that these models often fail to generalize in ways that task designers intend. For example, \citet{jia2017adversarial} and \citet{mccoy2019right} demonstrate that ambiguity in widely used NLU datasets like SQuAD \cite{rajpurkar2016squad} and MultiNLI \cite{williams2018broad} leads models like BERT to adopt some surface generalizations, despite the fact that they represent linguistic features. This continues to be a problem for models like RoBERTa$_{\subtxt{BASE}}$ which show an overall linguistic bias in our experiments. However, for tasks like NLI, the underlying linguistic feature depends on a combination of significant syntactic knowledge, semantic knowledge, and world knowledge. It stands to reason that representations and preferences for such high level features require more data to learn than the features we probe. Other work has used the poverty of stimulus design to study inductive biases associated with particular neural architectures during syntactic generalization. \citet{ravfogel2019studying} train RNNs on a morphological prediction task using artificial languages derived from naturally occurring English text, finding that RNNs show a recency bias in acquiring agreement rules. \citet{mccoy2018revisiting,mccoy2020does} train a seq2seq models on generated data ambiguous between a surface and a structural generalization to learn the subject-auxiliary inversion rule in English question formation. They find that, while tree-structured models show a structural bias, sequence models do not. \citet{warstadt2020can} conduct related experiments on subject-auxiliary inversion and other English structural rules, and find that BERT likely acquires a structural bias from pretraining. More abstract inductive biases have also been studied. Using zero-shot learning in an artificial language, \citet{lake2018generalization} show that RNNs lack a bias in favor of learning compositional meanings for new symbols. \citet{gandhi2019mutual} and \citet{gulordava2020one} explore conditions under which neural networks exhibit a bias towards learning mutually exclusive meanings for new symbols. Data augmentation and inoculation have also been explored previously as a way to influence how models generalize. \citet{mccoy2019right} and \citet{min2020syntactic} show that small amounts of inoculating data during training on textual entailment help BERT overlook certain surface generalizations. \citet{jha2020does} study inoculation using a constructed language of numerical sequences. Like us, they generate ambiguous datasets, though they only compare features that resemble our surface features. They find that it is relatively easy to nudge models away from shallow generalizations, but harder to nudge them towards deeper ones. Finally, several earlier studies explored how increasing training data impacts linguistic knowledge in LMs. Unlike the present study, these studies evaluate LMs using an unsupervised acceptability judgment task on minimal pairs (i.e.~not during fine-tuning), and do not attempt to separate feature learning from feature preferences. \citet{vanschijndel2019quantity} find the greatest increase in sensitivity to acceptability contrasts occurs between training on 2M and 10M words. \citet{warstadt2020blimp} find that while LMs learn agreement phenomena at a similarly early stage, other phenomena require more data to learn. Finally, \citet{hu2020systematic} find that adopting architectures that build in linguistic bias, such as RNNGs \cite{dyer2016recurrent}, has a bigger effect on the acceptability task than increasing training data from 1M to 40M words. \section{Future Work \& Conclusion} Our experiments shed light on the relationship between pretraining data and an inductive bias towards linguistic generalization. Our results indicate that, although some abstract linguistic features are learnable from relatively small amounts of pretraining data, models require significant pretraining after discovering these features to develop a bias towards \emph{using} them when generalizing. This gives some insight into why extensive pretraining helps general-purpose neural networks adapt to downstream tasks with relative ease. We also introduce MSGS, a new diagnostic dataset for probing the inductive biases of learning algorithms using the poverty of the stimulus design and inoculation, and also introduce a set of 12 RoBERTa models we pretrain on smaller data quantities. These models could prove to be a helpful resource for future studies looking to study learning curves of various kinds with respect to the quantity of pretraining data. Finally, while our results naturally lead to the conclusion that we should continue to pursue models with ever more pretraining, such as GPT-3 \cite{brown2020gpt3}, we do not wish to suggest that this will be the only or best way to build models with stronger inductive biases. Future work might use MSGS\ as a diagnostic tool to measure how effectively new model architectures and self-supervised pretraining tasks can more efficiently equip neural networks with better inductive biases. \section*{Acknowledgments} This project has benefited from financial support to SB by Eric and Wendy Schmidt (made by recommendation of the Schmidt Futures program), by Samsung Research (under the project \textit{Improving Deep Learning using Latent Structure}), by Intuit, Inc., and in-kind support by the NYU High-Performance Computing Center and by NVIDIA Corporation (with the donation of a Titan V GPU). This material is based upon work supported by the National Science Foundation under Grant No. 1850208 and 1922658. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation.
{'timestamp': '2020-10-13T02:26:01', 'yymm': '2010', 'arxiv_id': '2010.05358', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05358'}
arxiv
\section{Introduction} \label{intro} Forms have been a convenient way to collect and show information in many businesses. There is a huge demand in digitizing those forms and extracting important information from them. However, the formats used in forms varies from a situation to another and such wide variations raise a great challenge to automatically extract information. Information from a form includes not only its transcription but also the key-value (or label-value) relationships between text areas in the form. Those relationships play an important role in knowing the semantic meaning of elements in the forms. As stated in \cite{davis2019deep}, the key-value relationships in forms can be purely inferred from visual perspective. In order to support computer vision community in the development of this task, there are two image datasets for key-value extraction: FUNSD~\cite{jaume2019funsd} and NAF\cite{davis2019deep}. The National Archives Forms (NAF) dataset contains historical form images from United States National Archives, in which the annotated data are 165 in total. The 165 images are splitted into train/validation/test as 143/11/11, respectively. The dataset is available at \url{ http://github.com/herobd/NAF_dataset}. In the other hand, the FUNSD has 199 document images and is splitted into train/test with 149/50 ratio. Considering the quality of images and the variety of forms in each dataset, we used FUNSD for further investigation. In this report we will describe several annotating issues in FUNSD and the change we made to it. After that, we will describe the baseline implementation on it and our improved model for the key-value detection problem. The revised version of the FUNSD dataset is publicly available at \url{http://shorturl.at/cowA9}. \section{FUNSD dataset} \label{datastatistic} FUNSD \cite{davis2019deep} is composed of 199 document images, which is a subset sampled from the RVL-CDIP dataset \cite{harley2015evaluation}. The RVL-CDIP dataset consists of 400,000 grayscale images of various documents from the 1980s-1990s. Those images are scanned documents, which have a low resolution of 100 dpi and low quality with various types of noise added by successive scanning and printing procedures. The RVL-CDIP dataset categorized its images into 4 classes: letter, email, magazine, form. The author of the FUNSD dataset manually checked the 25,000 images from the “form” category, discarded unreadable and duplicate images, which leave them with 3,200 images, out of which 199 images were randomly sampled for annotation to make the FUNSD dataset. Originally, the RVL-CDIP is a subset of another dataset called Truth Tobacco Industry Document\footnote{\url{https://www.industrydocuments.ucsf.edu/tobacco/}} (TTID), which is an archive collection of scientific research, marketing and advertising documents of the largest tobacco companies in the US. The forms in the FUNSD dataset are annotated so that they can be used for many document understanding tasks such as text detection, text recognition, spatial layout understanding, and question-answer pair extraction \cite{jaume2019funsd}. \subsection{Data statistics} In the FUNSD dataset, the label of each image is contained in a JSON file, in which the form is represented as a list of interlinked semantic entities. Each entity consists of a group of words that belong together both semantically and spatially. Each semantic entity is associated with a unique identifier, a label (i.e., header, question, answer and other), a bounding box, a list of words belongs to said entity, and a list of links with other entities. Each word is described by its contextual content (i.e., OCR label) and its bounding box. Noted that the “question” and “answer” label is analogous to “key” and “value”; the bounding boxes are in the form of [left, top, right, bottom] and the links are formatted as a pair of entity identifiers with the identifier of the current entity being the first element. In the 199 images, there are in total of over 30,000 word-level annotations and about 10,000 entities. The dataset was split into the training set and the testing set with 149 images in the training set and 50 images in the testing set. More detailed statistics are described in Tab.\ref{form_count} and Tab. \ref{entity_count} (all statistics are according to the FUNSD dataset paper \cite{jaume2019funsd}). \begin{table}[] \caption{Counts of forms, words, entities and relations in the FUNSD dataset} \centering \begin{tabular}{|l|l|l|l|l|} \hline Subset & No. Forms & No. Words & No. Entities & No. Relations \\ \hline Training & 149 & 22,512 & 7,411 & 4,236 \\ \hline Testing & 50 & 8,973 & 2,332 & 1,076 \\ \hline \end{tabular} \label{form_count} \end{table} \begin{table}[] \caption{Class distribution of the semantic entities in FUNSD dataset} \centering \begin{tabular}{|l|l|l|l|l|l|} \hline Subset & Header & Question & Answer & Other & Total \\ \hline Training & 441 & 3,266 & 2,802 & 902 & 7,411 \\ \hline Testing & 122 & 1,077 & 821 & 312 & 2,332 \\ \hline \end{tabular} \label{entity_count} \end{table} \subsection{Inconsistency issues} As well mentioned by the authors of FUNSD \cite{jaume2019funsd}, the main limitation of this dataset comes from the fact that ``there is no exact definition of \textit{what} a form is or \textit{how} we should represent it''. Upon inspecting the FUNSD dataset, there are several annotating errors arise: \begin{itemize} \item Incorrect textual contents (i.e. OCR label). \item Incorrect bounding boxes for words. \item Inconsistency in defining bounding boxes - an entity could be either: one big block of text, lines of text, a word, or a few consecutive words. Sometimes a word is also represented as more than one consecutive words. \item Uncanny relations: some relations that do not follow the same logic of other relations. These relations are most likely created by mistakes or typos. \item Inconsistency in annotating relations. The “header” class is sometimes used to indicates headers, sometimes as a mean to represent chaining relation (i.e., hierarchical relations that have more than 2 levels of depth) (Fig. \ref{fig:wrong_header}, and sometimes it is used ambiguously (Fig. \ref{fig:ambiguous_header}). \end{itemize} \begin{figure} \centering \includegraphics[width=1\textwidth]{media/wrong_header.png} \caption{The ``MEDIA'' and ``SPACE/COLOR'' texts are not actually headers but are just a way to represent changing relation.} \label{fig:wrong_header} \end{figure} \begin{figure} \centering \includegraphics[width=1\textwidth]{./media/ambiguous.png} \caption{``Lorillard'' is not a header but just a logo. The header class is used ambiguously in this case.} \label{fig:ambiguous_header} \end{figure} \section{FUNSD revision} In order to use the data for developing the key-value detection network, the following steps were conducted to revise the dataset: \begin{itemize} \item Visualize the annotation for all images in the dataset, an example is shown in Fig. \ref{fig:revised}a. \item Manually check each image and look for errors in annotations for relations. \item For each relation chain, only the last entity is assigned as “answer”, all other entities in the chain are assigned as “question”. Any entity than not a part of any relationship is labelled as “other”. \item During revising the relation, any incorrectness in textual content and bounding box is also addressed. However, this means that there can still be errors of these types remaining in the revised dataset. \item The result of this process is visualized again, an example is shown in \ref{fig:revised}b. \end{itemize} \begin{figure} \centering \includegraphics[width=1\textwidth]{./media/revised.png} \caption{Visualization of an image with erroneous annotations (a) and the revised annotations (b)} \label{fig:revised} \end{figure} \section{A baseline of key-value detection on FUNSD} \subsection{Layout-aware key-value detection model} We propose an end-to-end key-value detection model directly from document images without text recognition involved. The intuition behind this design is that: human can perform key-value pair detection even without knowing the content of the document, the contextual information is useful when performing key-value pair identification. For example, given a document written in a totally foreign language, one can easily detect groups of text that potential have key-value relation; and if asked for identify phone numbers in the document, only then the person would need to know the semantic meaning of the text. That proves that spatial layout information is enough for the human to detect key-value pairs to some extent, thus motivates the idea of combining text detection and key-value detection in an information extraction system, making the system more layout-aware. The overall pipeline of our model is shown in Fig. \ref{fig:pipeline}. The first stage is a text detection network that produces a text segmentation map. The second stage which is the key-value detection stage takes the direct output of the text mask produced by the text detection step as input. Furthermore, it additionally uses the input image as input to gain access to structural layout information of the input image, making this an end-to-end layout-aware key-value segmentation model. The second stage’s input would be the text mask and the input image concatenated together deep-wise to make a 2-channel mask, and the output is a 4-channel mask with the channels corresponding to 4 classes: key, value, other, and background. \begin{figure} \centering \includegraphics[width=1\textwidth]{./media/pipeline.png} \caption{Overall pipeline of our layout-aware key-value extraction model, where text detection and key-value detection steps are integrated into one end-to-end trainable model.} \label{fig:pipeline} \end{figure} In this paper, we would show that using only spatial information is enough to determine key and value components in a document image. Detected key and value components can then be paired together using nearest neighbour mapping, and lastly processed by an OCR model to get the final output. \subsection{Related works} Much of previous works assume the availability of templates for form types of interest~\cite{barrett2004digital,butt2012information,hammami2015one}. This assumption has been relaxed in later work where a table format, cells, or other regularity can be assumed~\cite{zhou2016irmp,hirayama2011development}. However, many forms do not have table structures. Several approaches treat finding key-value pairs in a form as creating scene graphs from images. In those approaches, the objects in the images are nodes and edges are relationships between the objects. Zhang et al.~\cite{zhang2017relationship} uses a detection network to predict object, and prune the relationships based on whether the locations are spatially coherent. Yang et al.~\cite{yang2018graph} initially only detect and classify objects, but later use a relation-proposal network to predict relationships based on object classes. Yang et al.~\cite{yang2018graph} uses the predicted classes of the objects to hypothesize possible relationships in the relation-proposal network. Davis et al. \cite{davis2019deep} detects text lines using a Fully Convolutional Network (FCN). They also use dilated, non-squared kernels in the FCN text detector to improve the detection accuracy for long text lines. They use a convolutional classifier network to predict which potential relationships are correct using a context window around the relationship. All pairs of bounding boxes whose edges are within line-of-sight of each other, and are not too far away from each other, are consider candidates. \section{Implementation and results} \subsection{Training configurations} \label{training-config} As there are many good out-of-the-box text detectors that have been pre-trained on very large datasets, training a new one would not be necessary. Furthermore, it is not feasible to train the full end-to-end model due to limitation on computational power, the key-value detection network will be trained separately using text segmentation map derived from the revised annotation. This is still adequate to prove that key value components can be determined using only spatial information. \textbf{Data} Out of the 149 images in the training subset, 99 of them are used for training the model and the remaining 50 are used as the validation set. The network is trained with single image input (i.e., batch size = 1). \textbf{Input} The input of the key-value detection network has two channels, one for the text mask and one for the document image in greyscale. \textbf{Architecture} We use an U-Net \cite{ronneberger2015unet} based network that has \([16, 32, 64, 128, 256, 128, 64, 32, 16]\) filters for the key-value detector. It uses \(3 \times 3\) convolutional filters for every convolution layers. Following a convolutional layer are the Rectified Linear Unit (ReLU) activation function and a batch normalization layer. Furthermore, instead of transposed convolution \cite{dumoulin2016guide}, resize-convolution (nearest-neighbour interpolation up-sampling followed by normal convolution) was used as the method of choice for up-sampling the feature map. We also use the same network but with normal convolution replaced by CI-Deformable convolution \cite{cideform}, which helps the network more flexible at spatial modeling. \textbf{Loss Function} A combination of dice loss and categorical cross-entropy loss. The dice loss is only calculated on the first three layers, ignoring the channel corresponding to the background class. For the categorical cross-entropy loss, a weighted version is used. A set of weights proportional to [1.0, 1.0, 1.0, 0.3], which is normalized so that the weights sum up to 1.0, is applied during cross-entropy calculation. This effectively makes the weight of the background be one-third of other classes. Finally, the final loss value is a weighted sum of the dice loss value and the cross-entropy loss value: \begin{equation} loss_{final} = 4 \times loss_{dice} + 0.5 + 0.5 \times loss_{cross-entropy} \label{eq:loss_func} \end{equation} \textbf{Metric} The key-value detection problem is essentially a segmentation task, so the mean IoU score is used to assess the performance. The IoU value is calculated per each channel (i.e. each class) in the output mask and then averaged to get the mean IoU (mIoU) value. \textbf{Other configurations} Kernel weights are initialized with He Normal Initialization [12] and are normalized using L2 normalization with a factor of 0.01. All convolutional layers use “same” padding and kernels of size \(3 \times 3\). During training, Adam optimizer with learning rate = 0.0001 is used. The model is trained for 200 epochs but with early stopping procedure in place, also the weights with the best result will be restored upon termination of training. \subsection{Results} As mention earlier, the network takes both the text mask and the document image as input. It is important to point out that using the input document image together with the text mask yields noteworthy better results than using only the text mask. To verify the effect of such modification, an experiment is conducted where a smaller version of the network described in \ref{training-config} (which starts with only 4 kernels in the first convolution block) is trained on each scenario. According to the results shown in \ref{tab:with-vs-without-text-mask}, even though the network is rather small, it still clearly proves that including the input image in the input provides the network with valuable visual information that improves the result by a large margin. \begin{table} \caption{Comparison between using the text mask with and without the document image as input} \centering \begin{tabular}{lcc} \toprule \cmidrule(r){1-2} Input & Text mask only & Text mask + image \\ \midrule Mean IoU & 0.55 & \textbf{0.69} \\ \bottomrule \end{tabular} \label{tab:with-vs-without-text-mask} \end{table} For the main experiment, the result is shown in \ref{tab:unet-vs-cideform-unet}. Since the last channel (corresponding to the background class) is fairly easy to learn, not taking it into account during mIoU calculation would better reflect the performance of the network, but we still provide the result where the background is included for reference. The results show that using only visual information, it is possible for the network to effectively learn to identify “key” and “value” entities in document images. Moreover, the network converges faster and achieves better results when using CI-Deform Conv \cite{cideform} suggests that better spatial modeling capability corresponds to better performance at this task. \begin{table} \caption{Key and value detection using U-Net \cite{ronneberger2015unet} and U-Net with CI-Deformable convolution \cite{cideform}} \centering \begin{tabular}{ccc} \toprule \cmidrule(r){1-2} & U-Net & \begin{tabular}{c}U-Net \\ with CI-Deform Conv\end{tabular} \\ \midrule Epochs & 205 & 183 \\ \hline Mean IoU & 0.79 & \textbf{0.80} \\ \hline \begin{tabular}{c}Mean IoU \\ (without background)\end{tabular} & 0.72 & \textbf{0.73} \\ \bottomrule \end{tabular} \label{tab:unet-vs-cideform-unet} \end{table} \section{Conclusion} In this report, we have described some labeling issues in FUNSD, one of the limited available dataset for key-value detection problem in document images. We have made some revision to the dataset. The revised FUNSD is expected to be a promising dataset to automatically recognize the semantic relationships (key-value relations) in visual data. We also reported our implementation of for key-value detection on FUNSD using a UNet model as baseline results and an improved UNet model with Channel-Invariant Deformable Convolution. \bibliographystyle{unsrt}
{'timestamp': '2020-10-13T02:24:49', 'yymm': '2010', 'arxiv_id': '2010.05322', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05322'}
arxiv
\subsection*{Acknowledgments} The authors would like to thank Zachary Charles for the invaluable feedback that influenced the design of the methods and experiments, and Brendan McMahan, Zachary Garrett, Sean Augenstein, Jakub Konečný, Daniel Ramage, Sanjiv Kumar, Sashank Reddi, Jean-François Kagy for many insightful discussions, and Willie Neiswanger for helpful comments on the early drafts. \bibliographystyle{iclr2021_conference} \section{Conclusion and Future Directions} \label{sec:conclusion} In this work, we presented a new perspective on federated learning based on the idea of global posterior inference via averaging of local posteriors. Applying this perspective, we designed a new algorithm that generalizes federated averaging, is similarly practical and efficient, and yields state-of-the-art results on multiple challenging benchmarks. While our algorithm required a number of specific approximation and design choices, we believe that the underlying approach has potential to significantly broaden the design space for FL algorithms beyond purely optimization techniques. \vspace{-1.5ex} \paragraph{Limitations and future work.} As we mentioned throughout the paper, our method has a number of limitations due to the design choices, such as specific posterior sampling and covariance estimation techniques. While in the appendix we analyzed the effects of some of these design choices, exploration of: (i) other sampling strategies, (ii) more efficient covariance estimators~\citep{hsieh2013big}, (iii) alternatives to MCMC (such as variational inference), and (iv) more general connections with Bayesian deep learning are all interesting directions to pursue next. Finally, while there is a known, interesting connection between posterior sampling and differential privacy~\citep{wang2015privacy}, better understanding of privacy implications of posterior inference in federated settings is an open question. \section{Related Work} \label{sec:related-work} \paragraph{Federated optimization.} Starting with the seminal paper by \citet{mcmahan2017communication}, a lot of recent effort in federated learning has focused on understanding of \FedAvg (also known as local SGD) as an optimization algorithm. Multiple works have provided upper bounds on the convergence rate of \FedAvg in the homogeneous i.i.d.\ setting~\citep{yu2019parallel, karimireddy2019scaffold, woodworth2020local} as well as explored various non-i.i.d.\ settings with different notions of heterogeneity~\citep{zhao2018federated, sahu2018convergence, hsieh2019non, li2019convergence, wang2020tackling, woodworth2020minibatch}. \citet{reddi2020adaptive} reformulated \FedAvg in a way that enabled adaptive optimization and derived corresponding convergence rates, noting that \FedAvg requires careful tuning of learning rate schedules in order to converge to the desired optimum, which was further analyzed by \citet{charles2020outsized}. To the best of our knowledge, our work is perhaps the first to connect, reinterpret, and analyze federated optimization from the probabilistic inference perspective. \vspace{-1.75ex} \paragraph{Distributed MCMC.} Part of our work builds on the idea of sub-posterior aggregation, which was originally proposed for scaling up Markov chain Monte Carlo techniques to large datasets~\citep[known as the \emph{concensus Monte Carlo},][]{neiswanger2013asymptotically, scott2016bayes}. One of the goals of this paper is to highlight the connection between distributed inference and federated optimization and develop inference techniques that can be used under FL-specific constraints. \section{Introduction} \label{sec:introduction} Federated learning (FL) is a framework for learning statistical models from heterogeneous data scattered across multiple entities (or clients) under the coordination of a central server that has no direct access to the local data~\citep{kairouz2019advances}. To learn models without any data transfer, clients must process their own data locally and only infrequently communicate some model updates to the server which aggregates these updates into a global model~\citep{mcmahan2017communication}. While this paradigm enables efficient distributed learning from data stored on millions of remote devices~\citep{hard2018federated}, it comes with many challenges~\citep{li2020federated}, with the communication cost often being the critical bottleneck and the heterogeneity of client data affecting convergence. Canonically, FL is formulated as a distributed optimization problem with a few distinctive properties such as unbalanced and non-i.i.d.\ data distribution across the clients and limited communication. The \emph{de facto} standard algorithm for solving federated optimization is federated averaging~\citep[\FedAvg,][]{mcmahan2017communication}, which proceeds in rounds of communication between the server and a random subset of clients, synchronously updating the server model after each round~\citep{bonawitz2019towards}. By allowing the clients perform \emph{multiple} local SGD steps (or epochs) at each round, \FedAvg can reduce the required communication by orders of magnitude compared to mini-batch (MB) SGD. However, due to heterogeneity of the client data, more local computation often leads to biased client updates and makes \FedAvg stagnate at inferior optima. As a result, while slow during initial training, MB-SGD ends up dominating \FedAvg at convergence (see example in \cref{fig:illustration-2d}). This has been observed in multiple empirical studies~\citep[\eg,][]{charles2020outsized}, and recently was shown theoretically~\citep{woodworth2020minibatch}. Using stateful clients~\citep{karimireddy2019scaffold, pathak2020fedsplit} can help to remedy the convergence issues in the \emph{cross-silo} setting, where relatively few clients are queried repeatedly, but is not practical in the \emph{cross-device} setting (\ie, when clients are mobile devices) for several reasons~\citep{kairouz2019advances, li2020federated, lim2020federated}. One key issue is that the number of clients in such a setting is extremely large and the average client will only ever participate in a single FL round. Thus, the state of a stateful algorithm is never used. \emph{Is it possible to design FL algorithms that exhibit both fast training and consistent convergence with stateless clients?} In this work, we answer this question affirmatively, by approaching federated learning not as optimization but rather as posterior inference problem. We show that modes of the global posterior over the model parameters correspond to the desired optima of the federated optimization objective and can be inferred by aggregating information about local posteriors. Starting with an analysis of federated quadratics, we introduce a general class of \emph{federated posterior inference} algorithms that run local posterior inference on the clients and global posterior inference on the server. In contrast with federated optimization, posterior inference can, with stateless clients, benefit from an increased amount of local computation without stagnating at inferior optima (illustrated in \cref{fig:illustration-2d}). % However, a na\"{i}ve approach to federated posterior inference is practically infeasible because its computation and communication costs are cubic and quadratic in the model parameters, respectively. Apart from the new perspective, our key technical contribution is the design of an efficient algorithm with linear computation and communication costs. \input{figures/illustration2d} \vspace{-1.5ex} \paragraph{Contributions.} The main contributions of this paper can be summarized as follows: \begin{enumerate}[topsep=-4pt,itemsep=0pt,leftmargin=20pt] \item We introduce a new perspective on federated learning through the lens of posterior inference which broadens the design space for FL algorithms beyond purely optimization techniques. \item With this perspective, we design a computation- and communication-efficient approximate posterior inference algorithm---\emph{federated posterior averaging} (\FedPA). \FedPA works with stateless clients and its computational complexity and memory footprint are similar to \FedAvg. \item We show that \FedAvg with many local steps is in fact a special case of \FedPA that estimates local posterior covariances with identities. These biased estimates are the source of inconsistent updates and explain why \FedAvg has suboptimal convergence even in simple quadratic settings. \item Finally, we compare \FedPA with strong baselines on realistic FL benchmarks introduced by \citet{reddi2020adaptive} and achieve state-of-the-art results with respect to multiple metrics of interest. \end{enumerate} \section{Preliminary Analysis and Ablations} \label{sec:analysis} In \cref{sec:federated-posterior-averaging}, we derived federated posterior averaging (\FedPA) starting with the global posterior decomposition (\cref{prop:posterior-decomposition}, which is exact) and applying the following three approximations: \begin{enumerate}[topsep=0pt,itemsep=0pt,leftmargin=20pt] \item The Laplace approximation of the local and global posterior distributions. \item The shrinkage estimation of the local moments. \item Approximate sampling from the local posteriors using MCMC. \end{enumerate} We have also observed that \FedAvg is a special case of \FedPA (from the algorithmic point of view), since it can be viewed as also using the Laplace approximation for the posteriors, but estimating local covariances $\hat \Sigmav_i$'s with identities and local means using the final iterates of local SGD. In this section, we analyze the effects of approximations 2 and 3 on the convergence of \FedPA. Specifically, we first discuss the convergence rates of \FedAvg and \FedPA as \emph{biased} stochastic gradient optimization methods~\citep{ajalloeian2020analysis}. We show how the bias and variance of the client deltas behave for \FedAvg and \FedPA as functions of the number samples. We also analyze the quality of samples produced by IASG~\citep{mandt2017stochastic} and how they depend on the amount of local computation and hyperparameters. Our analyses are conducted empirically. \subsection{Discussion of the Convergence of \FedPA vs. \FedAvg} \label{app:fedpa-exact-sampling-convergence} First, observe that if each client is able to perfectly estimate their $\Deltav_i = \Sigmav_i^{-1} (\thetav - \muv)$, the problem solved by \cref{alg:generalized-fed-opt} simply becomes an optimization of a quadratic objective using unbiased stochastic gradients, $\Deltav := \frac{1}{M} \sum_{i=1}^M \Deltav_i$. The noise in the gradients in this case comes from the fact that the server interacts with only a small subset of $M$ out of $N$ clients in each round. This is a classical stochastic optimization problem with well-known convergence rates under some assumptions on the norm of the stochastic gradients~\citep[\eg,][]{nemirovski2009robust}. The rate of convergence for SGD with a $\Oc(t^{-1})$ decaying learning rate used on the server is $\Oc(1 / \sqrt{t})$. It can be further improved to $\Oc(1 / t)$ using Polyak momentum~\citep{polyak1964momentum} or iterate averaging~\citep{polyak1992acceleration}. In reality, both \FedAvg and \FedPA produce biased estimates $\hat \Deltav_\text{\FedAvg}$ and $\hat \Deltav_\text{\FedPA}$, respectively. Thus, we can analyze the problem as SGD with biased stochastic gradient estimates and let $\hat \Deltav_t := \nabla F(\thetav_t) + \bv(\thetav_t) + \nv(\thetav_t)$ where $\bv(\thetav_t)$ and $\nv(\thetav_t, \xi)$ are bias and noise terms. Following \citet{ajalloeian2020analysis}, we can further assume that the bias and noise terms are norm-bounded as follows. \vspace{-1ex} \begin{assumption}[$(m, \zeta^2)$-bounded bias] \label{asm:bounded-bias} There exist constants $0 \leq m < 1$ and $\zeta^2 \geq 0$ such that \begin{equation} \|\bv(\thetav)\|^2 \leq m \|\nabla F(\thetav)\|^2 + \zeta^2, \quad \forall \thetav \in \Rb^d. \end{equation} \end{assumption} \vspace{-1.5ex} \begin{assumption}[$(M, \sigma^2)$-bounded noise] \label{asm:bounded-noise} There exist constants $0 \leq M < 1$ and $\sigma^2 \geq 0$ such that \begin{equation} \ep[\xi]{\|\nv(\thetav, \xi)\|^2} \leq M \|\nabla F(\thetav)\|^2 + \sigma^2, \quad \forall \thetav \in \Rb^d. \end{equation} \end{assumption} \vspace{-1ex} Under these general assumptions, the following convergence result holds. \vspace{-1ex} \begin{theorem}[\citet{ajalloeian2020analysis}, Theorem 2] \label{thm:biased-sgd-convergence} Let $F(\thetav)$ be $L$-smooth. Then SGD with a learning rate $\alpha := \min\left\{\frac{1}{L}, \frac{1 - m}{2ML}, \left(\frac{LF}{\sigma^2 T}\right)^{1/2}\right\}$ and gradients that satisfy Assumptions \ref{asm:bounded-bias}, \ref{asm:bounded-noise} achieves the vicinity of a stationary point, $\ep{\|\nabla F(\thetav)\|^2} = \Oc\left(\varepsilon + \frac{\zeta^2}{1 - m}\right)$, in $T$ iterations, where \begin{equation} T = \Oc\left(\frac{1}{\varepsilon} \left[ 1 + \frac{M}{1 - m} + \frac{\sigma^2}{\varepsilon (1 - m)} \right] \right) \frac{LF}{1 - m}. \end{equation} \end{theorem} \vspace{-1ex} Note that SGD with biased gradients is able to converge to a vicinity of the optimum determined by the bias term $\zeta^2 / (1 - m)$. For \FedAvg, since the bias is not countered, this term determines the distance between the stationary point and the true global optimum. For \FedPA, since $\hat \Deltav_\text{\FedPA} \rightarrow \Deltav$ with more local samples, the bias should vanish as we increase the amount of local computation. Determining the precise statistical dependence of the gradient bias on the local samples is beyond the scope of this work. However, to gain more intuition about the differences in behavior of \FedPA and \FedAvg, below we conduct an empirical analysis of the bias and variance of the estimated client deltas on synthetic least squares problems, for which exact deltas can be computed analytically. \input{figures/bias-variance-tradeoffs} \paragraph{Quantifying empirically the bias and variance of $\hat \Deltav$ for \FedPA and \FedAvg.} We measure the empirical bias and variance of the client deltas computed by each of the methods on the synthetic least squares linear regression problems generated according to~\citet{guyon2003design} using the \texttt{make\_regression} function from scikit-learn.\footnote{\url{https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_regression.html}} The problems were generated as follows: for each dimensionality (10, 100, and 1000 features), we generated 10 random least squares problems, each of which consisted of 500 synthetic data points. Next, for each of the problems we generated 10 random initial model parameters $\{\thetav_1, \dots, \thetav_{10}\}$ and for each of the parameters we computed the exact $\Deltav_i$ as well as $\hat \Deltav_{\text{\FedAvg}, i}$ and $\hat \Deltav_{\text{\FedPA}, i}$ for different numbers of local steps; for $\hat \Deltav_\text{\FedPA}$ we also varied the shrinkage hyperparameter. Using these sample estimates, we further computed the $L_2$-norm of the bias and the Frobenius norm of the covariance matrices as functions of the number of local steps. The results are presented on \cref{fig:bias-variance-tradeoffs}. From \cref{fig:fedavg-bias-variance}, we see that as the amount of local computation increases, the bias in \FedAvg delta estimates grows and the variance reduces. For \FedPA (\cref{fig:fedpa-bias-variance-steps}), the trends turn out to be the opposite: as the number of local steps increases, the bias consistently reduces; the variance initially goes up, but with enough samples joins the downward trend. Note that the initial upward trend in the variance is due to the fact that we used the same \emph{fixed} shrinkage $\rho$ regardless of the number of local steps. To avoid sharp increases in the variance, $\rho$ must be selected for each number of local steps separately; \cref{fig:fedpa-bias-variance-rho} demonstrates how the bias and variance depend on the shrinkage hyperparameter for some fixed number of local steps.\footnote{% One could also use posterior samples to estimate the best possible $\rho$ that balance the bias-variance tradeoff \citep[\eg,][]{chen2010shrinkage} and avoids sharp increases in the variance.} \subsection{Analysis of the Quality of IASG-based Sampling and Covariance} \label{app:iasg-quality-analysis} The more and better samples we can obtain locally, the lower the bias and variance of the gradients of $\Qc(\thetav)$ will be, resulting in faster convergence to a fixed point closer to the global optimum. For local sampling, we proposed to use a variant of SG-MCMC called Iterate Averaged Stochastic Gradient (IASG) developed by \citet{mandt2017stochastic}, given in \cref{alg:iasg-sampling}. The algorithm generates samples by simply averaging every $K$ intermediate iterates produced by a client optimizer (typically, SGD with some a fixed learning rate $\alpha$) after skipping the first $B$ iterates as a burn-in phase.\footnote{% Note that in our experiments in \cref{sec:experiments}, instead of using $B$ local steps for burn-in at each round, we used several \emph{initial rounds} as burn-in-only rounds, running \FedPA in the \FedAvg regime.} \vspace{1ex} \emph{How good are the samples produced by IASG and how do different parameters of the algorithm affect the quality of the samples?} To answer this question, we run IASG on synthetic least squares problems, for which we can compute the actual posterior distribution and measure the quality of the samples by evaluating the effective sample size~\citep[ESS,][]{liu1996metropolized, owen2013mcbook}. Given $\ell$ approximate posterior samples $\{\thetav_1, \ldots, \thetav_\ell\}$, the ESS statistic can be computed as follows: \vspace{-1ex} \begin{equation*} \label{eq:effective-sample-size} \mathrm{ESS}\left(\{\thetav_i\}_{j=1}^\ell\right) := \left. \left(\sum_{j=1}^\ell w_j \right)^2 \middle/ \sum_{j=1}^\ell w_j^2 \right., \end{equation*} \vspace{-1.75ex} where weights $w_j$ must be proportional to the posterior probabilities, or equivalently to the loss. \paragraph{Effects of the dimensionality, the number of data points, and IASG parameters on ESS.} The results of our synthetic experiments are presented below in \cref{fig:ess}. The takeaways are as follows: \begin{itemize}[topsep=0pt,itemsep=0pt,leftmargin=20pt] \item More burn-in steps (or epochs) generally improve the quality of samples. \item The larger the number of steps per sample the better (less correlated) the samples are. \item The learning rate is the most sensitive and important hyperparameter---if too large, IASG might diverge (happened in the 1000 dimensional case); if too small, the samples become correlated. \item Finally, the quality of the samples deteriorates with the increase in the number of dimensions. \end{itemize} \input{figures/effective-sample-size} \section{A Posterior Inference Perspective on Federated Learning} \label{sec:federated-posterior-inference} Federated learning is typically formulated as the following optimization problem: \begin{equation} \label{eq:fl-opt} \min_{\thetav \in \Rb^d} \left\{ F(\thetav) := \sum_{i=1}^N q_i f_i(\thetav) \right\}, \quad f_i(\thetav) := \frac{1}{n_i} \sum_{j=1}^{n_i} f(\thetav; z_{ij}), \end{equation} where the global objective function $F(\thetav)$ is a weighted average of the local objectives $f_i(\thetav)$ over $N$ clients; each client's objective is some loss $f(\thetav; z)$ computed on the local data $D_i = \{z_{i1}, \ldots, z_{i n_i}\}$. In real-world cross-device applications, the total number of clients $N$ can be extremely large, and hence optimization of $F(\thetav)$ is done over multiple rounds with only a small subset of $M$ clients participating in each round. The weights $\{q_i\}$ are typically set proportional to the sizes of the local datasets $\{n_i\}$, which makes $F(\thetav)$ coincide with the training objective of the centralized setting. Typically, $f(\thetav; z)$ is negative log likelihood of $z$ under some probabilistic model parametrized by $\thetav$, \ie, $f(\thetav; z) := - \log \prob{z \mid \thetav}$. For example, least squares loss corresponds to likelihood under a Gaussian model, cross entropy loss corresponds to likelihood under a categorical model, etc.~\citep{murphy2012book}. Thus, \cref{eq:fl-opt} corresponds to \emph{maximum likelihood estimation} (MLE) of the model parameters $\thetav$. An alternative (Bayesian) approach to maximum likelihood estimation is \emph{posterior inference} or estimation of the posterior distribution of the parameters given all the data: $\prob{\thetav \mid D \equiv D_1 \cup \dots \cup D_N}$. The posterior is proportional to the product of the likelihood and a prior, $\prob{\thetav \mid D} \propto \prob{D \mid \thetav} \prob{\thetav}$, and, if the prior is uninformative (uniform over all $\thetav$), the modes of the global posterior coincide with MLE solutions or optima of $F(\thetav)$ in \cref{eq:fl-opt}. While this simple observation establishes an equivalence between the inference of the posterior mode and optimization, the advantage of this perspective comes from the fact that the global posterior \emph{exactly} decomposes into a product of local posteriors.\footnote{% Note that from the optimization point of view, the global optimum generally cannot be represented as any weighted combination of the local optima even in simple 2D settings (see \cref{fig:illustration-2d}, left).} \vspace{-1.25ex} \begin{restatable}[Global Posterior Decomposition]{proposition}{posteriordecomposition} \label{prop:posterior-decomposition} Under the uniform prior, any global posterior distribution that exists decomposes into a product of local posteriors: $\prob{\thetav \mid D} \propto \prod_{i=1}^N \prob{\thetav \mid D_i}$. \end{restatable} \vspace{-1.5ex} \noindent \cref{prop:posterior-decomposition} suggests that as long as we are able to compute local posterior distributions $\prob{\thetav \mid D_i}$ and communicate them to the server, we should be able to solve \cref{eq:fl-opt} by multiplicatively aggregating them to find the mode of the global posterior $\prob{\thetav \mid D}$ on the server. Note that posterior inference via multiplicative averaging has been successfully used to scale Monte Carlo methods to large datasets, where the approach is \emph{embarrassingly parallel} \citep{neiswanger2013asymptotically, scott2016bayes}. In the FL context, this means that once all clients have sent their local posteriors to the server, we can construct the global posterior without any additional communication. However, there remains the challenge of making the local and global inference and communication efficient enough for real federated settings. The example below illustrates how this can be difficult even for a simple model and loss function. \vspace{-1.5ex} \paragraph{Federated least squares.} Consider federated least squares regression with a linear model, where $z := (\xv, y)$ and the loss $f(\thetav; \xv, y) := \frac{1}{2} (\xv^\top \thetav - y)^2$ is quadratic. Then, the client objective becomes: \begin{equation} \label{eq:least-squares-client-objective} f_i(\thetav) = \log \exp \left\{ \frac{1}{2} \|\Xv_i \thetav - \yv_i\|^2 \right\} = \log \exp \left\{ \frac{1}{2} (\thetav - \muv_i)^\top \Sigmav_i^{-1} (\thetav - \muv_i) \right\} + \mathrm{const}, \end{equation} where $\Xv_i \in \Rb^{n_i \times d}$ is the design matrix, $\yv_i \in \Rb^{n_i}$ is the response vector, $\Sigmav_i^{-1} := \Xv_i^\top \Xv_i$ and $\muv_i := \left(\Xv_i^\top \Xv_i\right)^{-1} \Xv_i^\top \yv_i$. Note that the expression in \cref{eq:least-squares-client-objective} is the log likelihood for a multivariate Gaussian distribution with mean $\muv_i$ and covariance $\Sigmav_i$. Therefore, each local posterior (under the uniform prior) is Gaussian, and, as a product of Gaussians, the global posterior is also Gaussian with the following mean (which coincides with the posterior mode): \begin{equation} \label{eq:least-squares-global-posterior-mean} \muv := \left( \sum_{i=1}^N q_i \Sigmav_i^{-1} \right)^{-1} \left( \sum_{i=1}^N q_i \Sigmav_i^{-1} \muv_i \right). \end{equation} Concretely, in the case of least squares regression, this suggests that it is sufficient for clients to infer the means $\{\muv_i\}$ and inverse covariances $\{\Sigmav_i^{-1}\}$ of their local posteriors and communicate that information to server for the latter to be able to find the global optimum. However, a straightforward application of \cref{eq:least-squares-global-posterior-mean} would require $\Oc(d^2)$ space and $\Oc(d^3)$ computation, both on the clients and on the server, which is very expensive for the typical cross-device FL setting. Similarly, the communication cost would be $\Oc(d^2)$, while standard FL algorithms have communication cost of $\Oc(d)$. \paragraph{Approximate federated posterior inference.} Apart from the computation and communication issues discussed in the simple example above, we also have to contend with the fact that, generally, posteriors are non-Gaussian and closed form expressions for global posterior modes may not exist.\footnote{% Gaussian posteriors can be further generalized to the exponential family for which closed form expressions can be obtained under appropriate priors~\citep{wainwright2008graphical}. We leave this extension to future work.} In such cases, we propose to use the \emph{Laplace approximation for local and global posteriors}, \ie, approximate them with the best-fitting Gaussians. While imperfect, this approximation will allow us to compute the (approximate) global posterior mode in a computation- and communication-efficient manner using the following three steps: (i) infer approximate local means $\{\hat \muv_i\}$ and covariances $\{\hat \Sigmav_i\}$, (ii) communicate these to the server, and (iii) compute the posterior mode given by \cref{eq:least-squares-global-posterior-mean}. Note that directly computing and communicating these quantities would be completely infeasible for the realistic setting where models are neural networks with millions of parameters. In the following section, we design a practical algorithm where all costs are linear in the number of model parameters. \section{Federated Posterior Averaging: A Practical Algorithm} \label{sec:federated-posterior-averaging} Federated averaging~\citep[\FedAvg,][]{mcmahan2017communication} solves the problem from~\cref{eq:fl-opt} over $T$ rounds by interacting with $M$ random clients at each round in the following way: (i) broadcasting the current model parameters $\thetav$ to the clients, (ii) running SGD for $K$ steps on each client, and (iii) updating the global model parameters by collecting and averaging the final SGD iterates. \citet{reddi2020adaptive} reformulated the same algorithm in the form of server- and client-level optimization (\cref{alg:generalized-fed-opt}), which allowed them to bring techniques from the adaptive optimization literature to FL. \input{figures/algorithm-gen-fed-opt} \FedAvg is efficient in that it requires only $\Oc(d)$ computation on both the clients and the server, and $\Oc(d)$ communication between each client and the server. To arrive at a similarly efficient algorithm for % posterior inference, we focus on the following questions: (a) how to estimate local and global posterior moments efficiently? (b) how to communicate local statistics to the server efficiently? \vspace{-1.5ex} \paragraph{(1) Efficient global posterior inference.} There are two issues with computing an estimate of the global posterior mode $\muv$ directly using \cref{eq:least-squares-global-posterior-mean}. First, it requires computing the inverse of a $d \times d$ matrix on the server, which is an $\Oc(d^3)$ operation. Second, it relies on acquiring local means and inverse covariances, which would require $\Oc(d^2)$ communication from each client. We propose to solve both issues by converting the global posterior estimation into an equivalent optimization problem. \vspace{-1.5ex} \begin{restatable}[Global Posterior Inference]{proposition}{posteriorinference} \label{prop:global-posterior-inference} The global posterior mode $\muv$ given in \cref{eq:least-squares-global-posterior-mean} is the minimizer of a quadratic $\Qc(\thetav) := \frac{1}{2} \thetav^\top \Av \thetav - \bv^\top \thetav$, where $\Av := \sum_{i=1}^N q_i \Sigmav_i^{-1}$ and $\bv := \sum_{i=1}^N q_i \Sigmav_i^{-1} \muv_i$. \end{restatable} \vspace{-1.5ex} \cref{prop:global-posterior-inference} allows us to obtain a good estimate of $\muv$ by running stochastic optimization of the quadratic objective $\Qc(\thetav)$ on the server. Note that the gradient of $\Qc(\thetav)$ has the following form: \vspace{-1ex} \begin{equation} \label{eq:server-objective-gradient} \nabla \Qc(\thetav) := \sum_{i=1}^N q_i \Sigmav_i^{-1} (\thetav - \muv_i), \end{equation} which suggests that we can obtain $\muv$ by using the same \cref{alg:generalized-fed-opt} as \FedAvg but using different client updates: $\Deltav_i := \Sigmav_i^{-1} (\thetav - \muv_i)$. Importantly, as long as clients are able to compute $\Deltav_i$'s, this approach will result in $\Oc(d)$ communication and $\Oc(d)$ server computation cost per round. \input{figures/algorithm-iasg-sampling} \paragraph{(2) Efficient local posterior inference.} To compute $\Deltav_i$, each client needs to be able to estimate the local posterior means and covariances. We propose to use stochastic gradient Markov chain Monte Carlo~\citep[SG-MCMC,][]{welling2011bayesian, ma2015complete} for approximate sampling from local posteriors on the clients, so that these samples can be used to estimate $\hat \muv_i$'s and $\hat \Sigmav_i$'s. Specifically, we use a variant of SG-MCMC\footnote{% While in this work we use a variant of SG-MCMC, other techniques such as HMC~\citep{neal2011mcmc} or NUTs~\citep{hoffman2014no} can be used, too. We leave analysis of other approaches to future work.} with iterate averaging~\citep[IASG,][]{mandt2017stochastic}, which involves: (a) running local SGD for some number of steps to mix in the Markov chain, then (b) continued running of SGD for more steps to periodically produce samples via Polyak averaging~\citep{polyak1992acceleration} of the intermediate iterates (\cref{alg:iasg-sampling}). The more computation we can run locally on the clients each round, the more posterior samples can be produced, resulting in better estimates of the local moments. \vspace{-1.5ex} \paragraph{(3) Efficient computation of the deltas.} Even if we can obtain samples $\{\hat\thetav_1, \ldots, \hat\thetav_{\ell}\}$ via MCMC and use them to estimate local moments, $\hat \muv_i$ and $\hat \Sigmav_i$, computing $\Deltav_i$ na\"{i}vely would still require inverting a $d \times d$ matrix, \ie, $\Oc(d^3)$ compute and $\Oc(d^2)$ memory. The good news is that we are able to show that clients can compute $\Deltav_i$'s much more efficiently, in $\Oc(d)$ time and memory, using a dynamic programming algorithm and appropriate mean and covariance estimators. \vspace{-1.5ex} \begin{restatable}{theorem}{clientdeltadp} \label{thm:client-delta-dp-algorithm} Given $\ell$ approximate posterior samples $\{\hat\thetav_1, \ldots, \hat\thetav_{\ell}\}$, let $\hat \muv_\ell$ be the sample mean, $\hat \Sv_\ell$ be the sample covariance, and $\hat \Sigmav_\ell := \rho_\ell \Iv + (1 - \rho_\ell) \hat \Sv_\ell$ be a shrinkage estimator~\citep{ledoit2004well} of the covariance with $\rho_\ell := 1 / (1 + (\ell - 1) \rho)$ for some $\rho \in [0, +\infty)$. Then, for any $\thetav$, we can compute $\hat \Deltav_\ell = \hat \Sigmav_\ell^{-1} (\thetav - \hat \muv_\ell)$ in $\Oc(\ell^2 d)$ time and using $\Oc(\ell d)$ memory. \end{restatable} \vspace{-2ex} \begin{proof}[Sketch] We give a constructive proof by designing an efficient algorithm for computing $\hat \Deltav_\ell$. Our approach is based on two key ideas: \begin{enumerate}[topsep=0pt,itemsep=0pt,leftmargin=20pt] \item We prove that the specified shrinkage estimator of the covariance has a recursive decomposition into rank-1 updates, \ie, $\hat \Sigmav_t = \hat \Sigmav_{t - 1} + c_t \cdot \xv_t^\top \xv_t$, where $c_t$ is a constant and $\xv_t$ is some vector. This allows us to leverage the Sherman-Morrison formula for computing the inverse of $\hat \Sigmav_\ell$. \item Further, we design a dynamic programming algorithm for computing $\hat \Deltav_\ell$ exactly without storing the covariance matrix or its inverse. Our algorithm is online and allows efficient updates of $\hat \Deltav_\ell$ as more posterior samples become available. \end{enumerate} See \cref{sec:client-delta-computation-dp} for the full proof and derivation of the algorithm. \end{proof} \input{tables/complexity} Note that the computational cost of $\hat \Deltav_\ell$ consists of two components: (i) the cost of producing $\ell$ approximate local posterior samples using IASG and (ii) the cost of solving a linear system using dynamic programming. How much of an overhead does it add compared to simply running local SGD? It turns out that in practical settings the overhead is almost negligible. \cref{tab:complexity} shows the time it takes a client to compute the updates based on 5 local epochs (100 steps per epoch) using different algorithms (\FedAvg vs. our approach with exact or dynamic programming (DP) matrix inversion) on synthetic linear regressions. As the dimensionality grows, computational complexity of DP-based estimation of $\hat \Deltav_\ell$ becomes nearly identical to \FedAvg, which indicates that the majority of the cost in practice would come from SGD steps rather than our dynamic programming procedure. \paragraph{The final algorithm, discussion, and implications.} Putting all the pieces together, we arrive at the \emph{federated posterior averaging} (\FedPA) algorithm for approximately computing the mode of the global posterior over multiple communication rounds. Our algorithm is a variant of generalized federated optimization (\cref{alg:generalized-fed-opt}) with a new client update procedure (\cref{alg:fedpa-client-update}). Importantly, this also implies that \FedAvg can be viewed as posterior inference algorithm that estimates $\hat \Sigmav$ with an identity and, as a result, obtains biased client deltas $\hat \Deltav_\text{\FedAvg} := \Iv (\thetav - \hat \muv)$. In \cref{fig:illustration-2d} in the introduction, we demonstrate the differences in behavior between \FedAvg and \FedPA that stem from the differences in their client updates. Biased client updates make \FedAvg converge to a suboptimal point; moreover, increasing local computation only pushes the fixed point further away from the global optimum. On the other hand, \FedPA converges faster and to a better optimum, trading off bias for slightly more variance (becomes visible only closer to convergence). We see that \FedPA also substantially benefits from more local computation (more local samples). Since the main difference between \FedAvg and \FedPA is, in fact, the bias-variance trade off in the server gradient estimates (\cref{eq:server-objective-gradient}), we can view both methods as \emph{biased} SGD~\citep{ajalloeian2020analysis} and reason about their convergence rates as well as distances between their fixed points and correct global optima as functions of the gradient bias. In \cref{sec:analysis}, we provide further details, discuss convergence, empirically quantify the bias and variance of the client updates for both methods, and analyse the effects of the sampling-based approximations on the behavior of \FedPA. \section{Experiments} \label{sec:experiments} Using a suite of realistic benchmark tasks introduced by \citet{reddi2020adaptive}, we evaluate \FedPA against several competitive baselines: the best versions of \FedAvg with adaptive optimizers as well as \MIME~\citep{karimireddy2020mime}---a recently-proposed \FedAvg variant that also works with stateless clients, but uses control-variates and server-level statistics to mitigate convergence issues. \input{tables/datasets} \subsection{The Setup} \label{sec:exp-setup} \paragraph{Datasets and tasks.} The four benchmark tasks are based on the following three datasets (\cref{tab:datasets}): EMNIST~\citep{cohen2017emnist}, CIFAR100~\citep{krizhevsky2009learning}, and StackOverflow~\citep{stackoverflow2016data}. EMNIST (handwritten characters) and CIFAR100 (RGB images) are used for multi-class image classification tasks. StackOverflow (text) is used for next-word prediction (also a multi-class classification task, historically denoted NWP) and tag prediction (a multi-label classification task, historically denoted LR because a logistic regression model is used). EMNIST was partitioned by authors~\citep{caldas2018leaf}, CIFAR100 was partitioned randomly into 600 clients with a realistic heterogeneous structure~\citep{reddi2020adaptive}, and StackOverflow was partitioned by its unique users. All datasets were preprocessed using the code provided by~\citet{reddi2020adaptive}. \vspace{-2ex} \paragraph{Methods and models.} We use a generalized framework for federated optimization (\cref{alg:generalized-fed-opt}), which admits arbitrary adaptive server optimizers and expects clients to compute model deltas. As a baseline, we use federated averaging with adaptive optimizers (or with momentum) on the server and refer to it as \FedAvg[1] or \FedAvg[M], which stands for 1 or multiple local epochs performed by clients at each round, respectively.\footnote{\citet{reddi2020adaptive} referred to federated averaging with adaptive server optimizers as \textsc{FedAdam}, \textsc{FedYogi}, etc. Instead, we select the best optimizer for each task and refer to the corresponding method simply as \FedAvg.} The number of local epochs in the multi-epoch versions is a hyperparameter. We use the same framework for federated posterior averaging and refer to it as \FedPA[M]. As our clients use IASG to produce approximate posterior samples, collecting a single sample per epoch is optimal~\citep{mandt2017stochastic}. Thus \FedPA[M] uses \textsc{M} samples to estimate client deltas and has the same local and global computational complexity as \FedAvg[M] but with two extra hyperparameters: the number of burn-in rounds and the shrinkage coefficient $\rho$ from \cref{thm:client-delta-dp-algorithm}. As in \citet{reddi2020adaptive}, we use the following model architectures for each task: CNN for \emnist, ResNet-18 for \cifar, LSTM for \stackoverflow NWP, and multi-label logistic regression on bag-of-words vectors for \stackoverflow LR (for details see \cref{app:exp-details}). \input{figures/learning_curves} \vspace{-2ex} \paragraph{Hyperparameters.} For hyperparameter tuning, we first ran small grid searches for \FedAvg[M] using the best server optimizer and corresponding learning rate grids from \citet{reddi2020adaptive}. Then, we used the best \FedAvg[M] configuration and did a small grid search to tune the additional hyperparameters of \FedPA[M], which turned out not to be very sensitive (\ie, many configurations provided results superior to \FedAvg). More hyperparameter details can be found in \cref{app:exp-details}. \vspace{-2ex} \paragraph{Metrics.} Since both speed of learning as well as final performance are important quantities for federated learning, we measure: (i) the number of rounds it takes the algorithm to attain a desired level of an evaluation metric and (ii) the best performance attained within a specified number of rounds. For \emnist, we measure the number of rounds it takes different methods to achieve 84\% and 86\% evaluation accuracy\footnote{Centralized optimization of the CNN model on \emnist attains the evaluation accuracy of 88\%.}, and the best validation accuracy attained within 500 and 1500 rounds. For \cifar, we use the same metrics but use 30\% and 40\% as evaluation accuracy cutoffs and 1000 and 1500 as round number cutoffs. Finally, for \stackoverflow, we measure the the number of rounds it takes to the best performance and evaluation accuracy (for the NWP task) and precision, recall at 5, macro- and micro-F1 (for the LR task) attained by round 1500. We note that the total number of rounds was selected based on computational considerations (to ensure reproducibility within a reasonable amount of computational cost) and the intermediate cutoffs were selected qualitatively to highlight some performance points of interest. In addition, we provide plots of the evaluation loss and other metrics for all methods over the course of training which show a much fuller picture of the behavior of the algorithms (most of the plots are given in \cref{app:exp-additional-results}). \vspace{-2ex} \paragraph{Implementation and reproducibility.} All our experiments on the benchmark tasks were conducted in simulation using TensorFlow Federated~\citep[TFF,][]{ingerman2019tff}. Synthetic experiments were conducted using JAX~\citep{jax2018github}. The JAX implementation of the algorithms is available at \url{https://github.com/alshedivat/fedpa}. The TFF implementation will be released through \url{https://github.com/google-research/federated}. \subsection{Results on Benchmark Tasks} \label{sec:exp-benchmarks} \input{tables/results} \paragraph{The effects of posterior correction of client deltas.} As we demonstrated in \cref{sec:federated-posterior-averaging}, \FedPA essentially generalizes \FedAvg and only differs in the computation done on the clients, where we compute client deltas using an estimator of the local posterior inverse covariance matrix, $\Sigmav_i^{-1}$, which requires sampling from the posterior. To be able to use SG-MCMC for local sampling, we first run \FedPA in the \emph{burn-in regime} (which is identical to \FedAvg) for a number of rounds to bring the server state closer to the clients' local optima,\footnote{If SGD cannot reach the vicinity of clients' local optima within the specified number of local steps or epochs, estimated local means and covariances based on the SGD iterates can be arbitrarily poor.} after which we ``turn on'' the local posterior sampling. The effect of switching from \FedAvg to \FedPA for \cifar (after 400 burn-in rounds) and \stackoverflow LR (after 800 burn-in rounds) is presented on \cref{fig:learning-curves-cifar100,fig:learning-curves-so-lr}, respectively.\footnote{The number of burn-in rounds is a hyperparamter and was selected for each task to maximize performance.\\See more details in \cref{app:exp-details}.} During the burn-in phase, evaluation performance is identical for both methods, but once \FedPA starts computing client deltas using local posterior samples, the loss immediately drops and the convergence trajectory changes, indicating that \FedPA is able to avoid stagnation and make progress towards a better optimum. Similar effects are observed across all other tasks (see \cref{app:exp-additional-results}).\footnote{% We note that running burn-in for a fixed number of rounds before switching to sampling was a design choice; other, more adaptive strategies for determining when to switch from burn-in to sampling are certainly possible (\eg, use local loss values to determine when to start sampling). We leave such alternatives as future work.} While the improvement of \FedPA over \FedAvg on some of the tasks is visually apparent (\cref{fig:learning-curves}), we provide a more detailed comparison of the methods in terms of the speed of learning and the attained performance on all four benchmark tasks, summarized in \cref{tab:results} and discussed below. \vspace{-1.5ex} \paragraph{Results on \emnist and \cifar.} In \cref{tab:results-emnist,tab:results-cifar}, we present a comparison of \FedPA against: tuned \FedAvg with a fixed client learning rate (denoted \FedAvg[1] and \FedAvg[M]), the best variation of adaptive \FedAvg from \citet{reddi2020adaptive} with exponentially decaying client learning rates (denoted \AFO), and \MIME of \citet{karimireddy2020mime}. With more local epochs, we see significant improvement in terms of speed of learning: both \FedPA[M] and \FedAvg[M] achieve 84\% accuracy on \emnist in under 100 rounds (similarly, both methods attain 30\% on \cifar by round 350). However, more local computation eventually hurts \FedAvg leading to worse optima: on \emnist, \FedAvg[M] is not able to consistently achieve 86\% accuracy within 1500 rounds; on \cifar, it takes extra 350 rounds for \FedAvg[M] to get to 40\% accuracy. Finally, federated posterior averaging achieves the best performance on both tasks in terms of evaluation accuracy within the specified limit on the number of training rounds. On \emnist in particular, the final performance of \FedPA[M] after 1500 training rounds is 87.3\%, which, while only a 0.5\% absolute improvement, bridges \textbf{41.7\%} of the gap between the centralized model accuracy (88\%) and the best federated accuracy from previous work~\citep[86.8\%,][]{reddi2020adaptive}. \vspace{-1.5ex} \paragraph{Results on \stackoverflow NWP and LR.} Results for \stackoverflow are presented in \cref{tab:results-so}. Although not as pronounced as for image datasets, we observe some improvement of \FedPA over \FedAvg here as well. For NWP, we have an accuracy gain of 0.4\% over the best baseline. For the LR task, we compare methods in terms of average precision, recall at 5, and macro-/micro-F1. The first two metrics have appeared in some prior FL work, while the latter two are the primary evaluation metrics typically used in multi-label classification work~\citep{gibaja2015tutorial}. Interestingly, while \FedPA underperforms in terms of precision and recall, it substantially outperforms in terms of micro- and macro-averaged F1, especially the macro-F1. This indicates that while \FedAvg learns a model that can better predict high-frequency labels, \FedPA learns a model that better captures rare labels~\citep{yang1999evaluation, yang1999re}. Interestingly, note while \FedPA improves on F1 metrics and has almost the same recall at 5, it's precision after 1500 rounds is worse than \FedAvg. A more detailed discussion along with training curves for each evaluation metric are provided in \cref{app:exp-additional-results}. \section{Proofs} \label{sec:proofs} \posteriordecomposition* \begin{proof} Under the uniform prior, the following equivalence holds for $\prob{\thetav \mid D}$ as a function of $\thetav$: \begin{equation} \label{eq:posterior-decomposition} \prob{\thetav \mid D} \propto \prob{D \mid \thetav} = \prod_{z \in D} \prob{z \mid \thetav} = \prod_{i=1}^N \underbrace{\prod_{z \in D_i} \prob{z \mid \thetav}}_\text{local likelihood} \propto \prod_{i=1}^N \prob{\thetav \mid D_i} \end{equation} The proportionality constant between the left and right hand side in \cref{eq:posterior-decomposition} is $\prod_{i=1}^N \prob{D_i} / \prob{D}$. \end{proof} \posteriorinference* \begin{proof} The statement of the proposition (implicitly) assumes that all matrix inverses exist. Then, the quadratic $\Qc(\thetav)$ is positive definite (PD) since $\Av$ is PD as a convex combination of PD matrices $\Sigmav_i^{-1}$. Thus, the quadratic has a unique solution $\thetav^\star$ where the gradient of the objective vanishes: \begin{equation} \Av \thetav^\star - \bv = 0 \quad \Rightarrow \quad \thetav^\star = \Av^{-1} \bv = \left(\sum_{i=1}^N q_i \Sigmav_i^{-1}\right)^{-1} \sum_{i=1}^N q_i \Sigmav_i^{-1} \muv_i \equiv \muv, \end{equation} which implies that $\muv$ is the unique minimizer of $\Qc(\thetav)$. \end{proof} \section{Computation of Client Deltas via Dynamic Programming} \label{sec:client-delta-computation-dp} In this section, we provide a constructive proof for the following theorem by designing an efficient algorithm for computing $\hat \Deltav_\ell := \hat \Sigmav_\ell^{-1} (\thetav - \hat \muv_\ell)$ on the clients in time and memory linear in the number of dimensions $d$ of the parameter vector $\thetav \in \Rb^d$. \clientdeltadp* The na\"{i}ve computation of update vectors (\ie, where we first estimate $\hat \muv_\ell$ and $\hat \Sigmav_\ell$ from posterior samples and use them to compute deltas) requires $\Oc(d^2)$ storage and $\Oc(d^3)$ compute on the clients and is both computationally and memory intractable. We derive an algorithm that, given $\ell$ posterior samples, allows us to compute $\hat \Deltav_\ell$ using only $\Oc(\ell d)$ memory and $\Oc(\ell^2 d)$ compute. The algorithm makes use of the following two components: \begin{enumerate} \item The shrinkage estimator of the covariance~\citep{ledoit2004well}, which is known to be well-conditioned even in high-dimensional settings (\ie, when the number of samples is smaller than the number of dimensions) and is widely used in econometrics~\citep{ledoit2004honey} and computational biology~\citep{schafer2005shrinkage}. \item Incremental computation of $\hat \Sigmav_\ell^{-1} (\thetav_\ell - \hat \muv_\ell)$ that exploits the fact that each new posterior sample only adds a rank-1 component to $\hat \Sigmav_\ell$ and applies the Sherman-Morrison formula to derive a dynamic program for updating $\hat \Deltav_\ell$. \end{enumerate} \paragraph{Notation.} For the sake of this discussion, we denote $\thetav$ (\ie, the server state broadcasted to the clients at round $t$) as $\xv_0$, drop the client index $i$, denote posterior samples as $\xv_j$, sample mean as $\bar \xv_\ell := \frac{1}{\ell} \sum_{j=1}^\ell \xv_j$, and sample covariance as $\hat \Sv_\ell := \frac{1}{\ell - 1} \sum_{j=1}^\ell (\xv_j - \bar \xv_\ell) (\xv_j - \bar \xv_\ell)^\top$. \subsection{The Shrinkage Estimator of the Covariance} \label{app:covariance-shrinkage-estimator} \citet{ledoit2004well} proposed to estimate a high-dimensional covariance matrix using a convex combination of identity matrix and sample covariance (known as the LW or shrinkage estimator): \begin{equation} \label{eq:ledoit-wolf-cov-estimator} \hat \Sigmav_\ell(\rho_\ell) := \rho_\ell \Iv + (1 - \rho_\ell) \Sv_\ell, \end{equation} where $\rho_\ell$ is a scalar parameter that controls the bias-variance tradeoff of the estimator. As an aside, while $\rho_\ell$ can be arbitrary and the optimal $\rho_\ell$ requires knowing the true covariance $\Sigmav$, there are near-optimal ways to estimate $\hat \rho_\ell$ from the samples~\citep{chen2010shrinkage}, which we discuss at the end of this section. In this section, we focus on deriving an expression for $\rho_t$ as a function of $t = 1, \ldots, \ell$ that ensures that the difference between $\hat \Sigmav_t$ and $\hat \Sigmav_{t-1}$ is a rank-1 matrix (this is not the case for arbitrary $\rho$'s). \paragraph{Derivation of a shrinkage estimator that admits rank-1 updates.} Consider the following matrix: \begin{equation} \label{eq:tilde-sigma} \tilde \Sigmav_t := \Iv + \beta_t \hat \Sv_t, \end{equation} where $\beta_t$ is a scalar function of $t = 1, 2, \ldots, \ell$. We would like to find $\beta_t$ such that $\tilde \Sigmav_t = \tilde \Sigmav_{t-1} + \gamma_t \Uv_t$, where $\Uv_t$ is a rank-1 matrix, \ie, the following equality should hold: \begin{equation} \label{eq:tilde-sigma-equality} \beta_t \hat \Sv_t = \beta_{t-1} \hat \Sv_{t-1} + \gamma_t \Uv_t \end{equation} To determine the functional form of $\beta_t$, we need recurrent relationships for $\bar \xv_{t}$ and $\hat \Sv_t$. For the former, note that the following relationship holds for two consecutive estimates of the sample mean, $\bar \xv_{t-1}$ and $\bar \xv_{t}$: \begin{equation} \label{eq:consecutive-mean-estimates} \bar \xv_t = \frac{(t-1) \bar \xv_{t-1} + \xv_t}{t} = \bar \xv_{t-1} + \frac{1}{t} (\xv_t - \bar \xv_{t-1}) \end{equation} This allows us to expand $\hat \Sv_t$ as follows: \begin{equation} \label{eq:sample-covariance-sum-recurrence} \begin{aligned} (t - 1) \hat \Sv_t =\ & \sum_{j=1}^t (\xv_j - \bar \xv_t) (\xv_j - \bar \xv_t)^\top \\ =\ &\sum_{j=1}^t \left( \xv_j - \bar \xv_{t-1} - \frac{\xv_t - \bar \xv_{t-1}}{t} \right) \left( \xv_j - \bar \xv_{t-1} - \frac{\xv_t - \bar \xv_{t-1}}{t} \right)^\top \\ =\ &\underbrace{\sum_{j=1}^{t-1} \left( \xv_j - \bar \xv_{t-1} \right) \left( \xv_j - \bar \xv_{t-1} \right)^\top}_{= (t - 2) \hat \Sv_{t-1}} - 2\frac{\xv_t - \bar \xv_{t-1}}{t} \underbrace{\sum_{j=1}^{t-1} \left( \xv_j - \bar \xv_{t-1} \right)^\top}_{= 0} + \\ &\frac{t - 1}{t^2} (\xv_t - \bar \xv_{t-1}) (\xv_t - \bar \xv_{t-1})^\top + \left(\frac{t - 1}{t}\right)^2 (\xv_t - \bar \xv_{t-1}) (\xv_t - \bar \xv_{t-1})^\top \\ =\ & (t - 2) \hat \Sv_{t - 1} + \frac{t - 1}{t} (\xv_t - \bar \xv_{t-1}) (\xv_t - \bar \xv_{t-1})^\top \end{aligned} \end{equation} Thus, we have the following recurrent relationship between $\hat \Sv_t$ and $\hat \Sv_{t-1}$: \begin{equation} \label{eq:sample-covariance-recurrence} \hat \Sv_t = \left( \frac{t - 2}{t - 1} \right) \hat \Sv_{t - 1} + \frac{1}{t} (\xv_t - \bar \xv_{t-1}) (\xv_t - \bar \xv_{t-1})^\top \end{equation} Now, we can plug \eqref{eq:sample-covariance-recurrence} into \eqref{eq:tilde-sigma-equality} and obtain the following equation: \begin{equation} \label{eq:tilde-sigma-equation} \beta_t \left( \frac{t - 2}{t - 1} \right) \hat \Sv_{t - 1} + \frac{\beta_t}{t} (\xv_t - \bar \xv_{t-1}) (\xv_t - \bar \xv_{t-1})^\top = \beta_{t-1} \Sv_{t-1} + \gamma_t \Uv_t, \end{equation} which implies that $\Uv_t := (\xv_t - \bar \xv_{t-1}) (\xv_t - \bar \xv_{t-1})^\top$, $\gamma_t := \beta_t / t$, and the following telescoping expressions for $\beta_t$: \begin{equation} \label{eq:beta-n-relationship} \beta_t = \left( \frac{t - 1}{t - 2} \right) \beta_{t-1} = \left( \frac{t - 1}{\cancel{t - 2}} \cdot \frac{\cancel{t - 2}}{t - 3} \right) \beta_{t-2} = \dots = (t - 1) \beta_{2}, \end{equation} where we set $\beta_2 \equiv \rho \in [0, +\infty)$ to be a constant. Thus, if we define $\tilde \Sigmav_t := \Iv + \rho (t - 1) \hat \Sv_t$, then the following recurrent relationships will hold: \begin{align} \label{eq:tilde-sigma-recurrence} \tilde \Sigmav_1 &= \Iv, \nonumber \\ \tilde \Sigmav_2 &= \Iv + \rho \hat \Sv_2 = \tilde \Sigmav_1 + \frac{\rho}{2} (\xv_2 - \bar \xv_1) (\xv_2 - \bar \xv_1)^\top, \nonumber \\ \tilde \Sigmav_3 &= \Iv + 2 \rho \hat \Sv_3 = \tilde \Sigmav_2 + \frac{2 \rho}{3} (\xv_3 - \bar \xv_2) (\xv_3 - \bar \xv_2)^\top, \nonumber \\ &\dots \nonumber \\ \tilde \Sigmav_t &= \Iv + (t - 1) \rho \hat \Sv_{t-1} = \tilde \Sigmav_{t-1} + \frac{(t - 1) \rho}{t} (\xv_t - \bar \xv_{t-1}) (\xv_t - \bar \xv_{t-1})^\top \end{align} Finally, we can obtain a shrinkage estimator of the covariance from $\tilde \Sigmav_n$ by normalizing coefficients: \begin{equation} \label{eq:our-shrinkage-estimator} \hat \Sigmav_t := \underbrace{\frac{1}{1 + (t - 1) \rho}}_{\rho_t} \Iv + \underbrace{\frac{(t - 1) \rho}{1 + (t - 1) \rho}}_{1 - \rho_t} \hat \Sv_t = \rho_t \tilde \Sigmav_t \end{equation} Note that $\hat \Sigmav_1 \equiv \Iv$ and $\hat \Sigmav_t \rightarrow \Sv_t$ as $t \rightarrow \infty$. \subsection{Computing Deltas using Sherman-Morrison and Dynamic Programming} \label{app:deltas-sherman-morrison-dp} Since $\hat \Sigmav_\ell$ is proportional to $\tilde \Sigmav_\ell$ and the latter satisfies recurrent rank-1 updates given in \cref{eq:tilde-sigma-recurrence}, denoting $\uv_\ell := \xv_\ell - \bar \xv_{\ell-1}$, we can express $\hat \Sigmav_\ell^{-1} = \tilde \Sigmav_\ell^{-1} / \rho_\ell$ using the Sherman-Morrison formula: \begin{equation} \label{eq:hat-sigma-inverse-sherman-morrison} \tilde \Sigmav_\ell^{-1} = \tilde \Sigmav_{\ell-1}^{-1} - \frac{\gamma_\ell \left( \tilde \Sigmav_{\ell-1}^{-1} \uv_\ell \uv_\ell^\top \tilde \Sigmav_{\ell-1}^{-1} \right)}{1 + \gamma_\ell \left( \uv_\ell^\top \tilde \Sigmav_{\ell-1}^{-1} \uv_\ell \right)} \end{equation} Note that we would like to estimate $\hat \Deltav_\ell := \hat \Sigmav_\ell^{-1} (\xv_0 - \bar \xv_\ell)$, which can be done without computing or storing any matrices if we know $\tilde \Sigmav_{\ell-1}^{-1} \uv_\ell$ and $\tilde \Sigmav_{\ell-1}^{-1} (\xv_0 - \bar \xv_\ell)$. Denoting $\tilde \Deltav_t := \tilde \Sigmav_t^{-1} (\xv_0 - \bar \xv_t)$, and knowing that $\xv_0 - \bar \xv_\ell = (\xv_0 - \bar \xv_{\ell-1}) - \uv_\ell / \ell$ (which follows from \cref{eq:consecutive-mean-estimates}), we can compute $\hat \Deltav_\ell$ using the following recurrence: \begin{align} \tilde \Deltav_1 &:= \xv_0 - \bar \xv_1, \quad \vv_{1,2} := \xv_2 - \bar \xv_1, && \text{\color{gray}// initial conditions} \\ \uv_t &:= \xv_t - \bar \xv_{t-1}, \quad \vv_{t-1,t} := \tilde \Sigmav_{t-1}^{-1} \uv_t && \text{\color{gray}// recurrence for $\uv_t$ and $\vv_{t-1,t}$} \\ \tilde \Deltav_t &= \tilde \Deltav_{t-1} - \left[ 1 + \frac{\gamma_t \left(t \uv_t^\top \tilde \Deltav_{t-1} - \uv_t^\top \vv_{t-1,t} \right)}{1 + \gamma_t \left(\uv_t^\top \vv_{t-1,t}\right)} \right] \frac{\vv_{t-1,t}}{t} && \text{\color{gray}// recurrence for $\tilde \Deltav_t$} \\ \hat \Deltav_t &= \tilde \Deltav_t / \rho_t && \text{\color{gray}// final step for $\hat \Deltav_t$} \end{align} Remember that our goal is to avoid storing $d \times d$ matrices throughout the computation. In the above recursive equations, all expressions depend only on vector-vector products except the one for $\vv_{t-1,t}$ which needs a matrix-vector product. To express the latter one in the form of vector-vector products, we need another 2-index recurrence on $\vv_{i, j} := \tilde \Sigmav_{i}^{-1} \uv_j$: \begin{align} \vv_{1, 2} &= \uv_2, \quad \vv_{1, 3} = \uv_3, \quad \ldots \quad \vv_{1, t} = \uv_t && \text{\color{gray}// initial conditions} \\ \vv_{t-1, t} &= \left[ \tilde \Sigmav_{t-2}^{-1} - \frac{\gamma_{t-1} \left( \tilde \Sigmav_{t-2}^{-1} \uv_{t-1} \uv_{t-1}^\top \tilde \Sigmav_{t-2}^{-1} \right)}{1 + \gamma_{t-1} \left( \uv_{t-1}^\top \tilde \Sigmav_{t-2}^{-1} \uv_{t-1} \right)} \right] \uv_t && \text{\color{gray}// Sherman-Morrison} \\ &= \vv_{t-2, t} - \frac{\gamma_{t-1} \left( \vv_{t-2, t-1}^\top \uv_t \right)}{1 + \gamma_{t-1} \left( \vv_{t-2, t-1}^\top \uv_{t-1} \right)} \vv_{t-2, t-1} \\ &= \vv_{1, t} - \sum_{k=2}^{t-1} \frac{\gamma_{k} \left( \vv_{k-1, k}^\top \uv_t \right)}{1 + \gamma_{k} \left( \vv_{k-1, k}^\top \uv_{k} \right)} \vv_{k-1, k} && \text{\color{gray}// final expression for $\vv_{t-1, t}$} \end{align} Now, equipped with these two recurrences, given a stream of samples $\xv_1, \xv_2, \dots, \xv_t, \dots$, we compute $\hat \Deltav_t$ for $t \geq 2$ based on $\xv_t$, $\{\uv_k\}_{k=1}^{t-1}$, $\{\vv_{k-2, k-1}\}_{k=1}^{t-1}$ and $\hat \Deltav_{t-1}$ using the following two steps: \begin{enumerate} \item Compute $\uv_t$ and $\vv_{t-1,t}$ using the second recurrence. \item Compute $\hat \Deltav_t$ from $\uv_t$, $\vv_{t-1,t}$, and $\hat \Deltav_{t-1}$ using the first recurrence. \end{enumerate} For each new sample in the sequence, we repeat the two steps to obtain the updated $\hat \Deltav_t$ estimate, until we have processed all $\ell$ samples. Note that the first step requires $\Oc(t)$ vector-vector multiplies, \ie, $\Oc(td)$ compute, and $\Oc(d)$ memory, and the second step a $\Oc(1)$ number of vector-vector multiplies. As a result, the computational complexity of estimating $\hat \Deltav_\ell$ is $\Oc(\ell^2 d)$ and the storage needed for the dynamic programming state represented by a tuple $\left(\{\uv_k\}_{k=1}^{t-1}, \{\vv_{k-2, k-1}\}_{k=1}^{t-1}, \hat \Deltav_{t-1}\right)$ is $\Oc(\ell d)$. \paragraph{The any-time property of the resulting algorithm.} Interestingly, the above algorithm is online as well as \emph{any-time} in the following sense: as we keep sampling more from the posterior, the estimate of $\hat \Deltav$ keeps improving, but if stopped at any time, the algorithm still produces the best possible estimate under the given time constraint. If the posterior sampler is stopped during the burn-in phase or after having produced only 1 posterior sample, the returned delta will be identical to \FedAvg. By spending more compute on the clients (and a bit of extra memory), with each additional posterior sample $\xv_t$, we have $\hat \Deltav_t \underset{t \rightarrow \infty}{\longrightarrow} \Sigmav^{-1} (\xv_0 - \muv)$. \paragraph{Optimal selection of $\rho$.} Note that to be able to run the above described algorithm in an online fashion, we have to select and commit to a $\rho$ before seeing any samples. Alternatively, if the online and any-time properties of the algorithm are unnecessary, we can first obtain $\ell$ posterior samples $\{\xv_k\}_{k=1}^\ell$, then infer a near-optimal $\hat \rho_\star$ from these samples---\eg, using the Rao-Blackwellized version of the LW estimator (RBLW) or the oracle approximating shrinkage (OAS), both proposed and analyzed by~\citet{chen2010shrinkage}---and then use the inferred $\hat \rho_\star$ to compute the corresponding delta using our dynamic programming algorithm. \section{Details on the Experimental Setup} \label{app:exp-details} In this part, we provide additional details on our experimental setup, including a more detailed description of the datasets and tasks, models, methods, and hyperparameters. \subsection{Datasets, Tasks, and Models} \label{app:exp-details-datasets-models} Statistics of the datasets used in our empirical study can be found in \cref{tab:datasets}. All the datasets and tasks considered in our study are a subset of the tasks introduced by \citet{reddi2020adaptive}. \paragraph{\emnist.} The dataset is comprised of $28 \times 28$ images of handwritten digits and lower and upper case English characters (62 different classes total). The federated version of the dataset was introduced by~\citet{caldas2018leaf}, and is partitioned by the author of each character. The heterogeneity of the dataset is coming from the different writing style of each author. We use this dataset for the character recognition task, termed EMNIST CR in \citet{reddi2020adaptive} and the same model architecture, which is a 2-layer convolutional network with $3 \times 3$ kernel, max pooling, and dropout, followed by a 128-unit fully connected layer. The model was adopted from the TensorFlow Federated library: \url{https://bit.ly/3l41LKv}. \paragraph{\cifar.} The federated version of \cifar was introduced by \citet{reddi2020adaptive}. The training set of the dataset is partitioned among 500 clients, 100 data points per client. The partitioning was created using a two-step latent Dirichlet allocation (LDA) over to ``coarse'' to ``fine'' labels which created a label distribution resembling a more realistic federated setting. For the model, also following \citet{reddi2020adaptive}, we used a modified ResNet-18 with group normalization layer instead of batch normalization, as suggested by \citet{hsieh2019non}. The model was adopted from the TensorFlow Federated library: \url{https://bit.ly/33jMv6g}. \paragraph{\stackoverflow.} The dataset consists of text (questions and answers) asked and answered by the total of 342,477 unique users, collected from \url{https://stackoverflow.com}. The federated version of the dataset partitions it into clients by the user. In addition, questions and answers in the dataset have associated metadata, which includes tags. We consider two tasks introduced by \citet{reddi2020adaptive}: the next word prediction task (NWP) and the tag prediction task via multi-label logistic regression. The vocabulary of the dataset is restricted to 10,000 most frequently used words for each task (\ie, the NWP task becomes a multi-class classification problem with 10,000 classes). The tags are similarly restricted to 500 most frequent ones (\ie, the LR task becomes a multi-label classification proble with 500 labels). For tag prediction, we use a simple linear regression model where each question or answer are represented by a normalized bag-of-words vector. The model was adopted from the TensorFlow Federated library: \url{https://bit.ly/2EXjAeY}. For the NWP task, we restrict each client to the first 128 sentences in their dataset, perform padding and truncation to ensure that sentences have 20 words, and then represent each sentence as a sequence of indices corresponding to the 10,000 frequently used words, as well as indices representing padding, out-of-vocabulary (OOV) words, beginning of sentence (BOS), and end of sentence (EOS). We note that accuracy of next word prediction is measured only on the content words and \emph{not} on the OOV, BOS, and EOS symbols. We use an RNN model with 96-dimensional word embeddings (trained from scratch), 670-dimensional LSTM layer, followed by a fully connected output softmax layer. The model was adopted from the TensorFlow Federated library: \url{https://bit.ly/2SoSi3X}. \subsection{Methods} \label{app:exp-details-models-methods} \input{tables/optimizers} As mentioned in the main text, we used \FedAvg with adaptive server optimizers with 1 or multiple local epochs per client as our baselines. For each task, we selected the best server optimizer based on the results reported by \citet{reddi2020adaptive}, given in \cref{tab:optimizers}. We emphasize, even though we refer to all our baseline methods as \FedAvg, the names of the methods as given by \citet{reddi2020adaptive} should be \textsc{FedAvgM} for \emnist and \cifar, \textsc{FedAdam} for \stackoverflow NWP and \textsc{FedAdagrad} for \stackoverflow LR. Another difference between our baselines and \citet{reddi2020adaptive} is that we ran SGD \emph{with momentum} on the clients for \emnist, \cifar, and \stackoverflow LR, as that improved performance of the methods with multiple epochs per client. Our \FedPA methods used the same configurations as \FedAvg baselines; moreover, \FedPA and \FedAvg were identical (algorithmically) during the burn-in phase and only different in the client-side computation during the sampling phase of \FedPA. \subsection{Hyperparameters and Grids} \label{app:exp-details-hypers} \input{tables/hyperparams} All hyperparameter grids are given in \cref{tab:hyperparams-grids}. The best server and client learning rates were selected based on the \FedAvg performance and used for \FedPA. The best selected hyperparameters are given in \cref{tab:hyperparams-best}. \section{Additional Experimental Results} \label{app:exp-additional-results} We provide additional experimental results. As mentioned in the main text, the results presented in \cref{tab:results} were selected to highlight the differences between the methods with respect to two metrics of interest: (i) the number of rounds until the desired performance, and (ii) the performance achievable within a fixed number of rounds. A much fuller picture is given by the learning curves of each method. Therefore, we plot evaluation losses, accuracies, and metrics of interest over the course of training. On the plots, individual values at each round are indicated with $\times$-markers and the 10-round running average with a line of the corresponding color. \paragraph{\emnist.} Learning curves for \FedAvg and \FedPA on \emnist are given in \cref{fig:learning-curves-appendix-emnist}. \cref{fig:learning-curves-emnist-appendix-5} shows the best \FedAvg[1], \FedAvg[5], and \FedPA[5] models and \cref{fig:learning-curves-emnist-appendix-20} shows the best \FedAvg[20], and \FedPA[20]. Apart from the fact that multi-epoch versions converge significantly faster than the 1-epoch \FedAvg[1], note that the effect of bias reduction when switching from the burn-in to sampling in \FedPA becomes much more pronounced in the 20-epoch version. \paragraph{\cifar and \stackoverflow.} Learning curves for various models on \cifar and \stackoverflow tasks are presented in \cref{fig:learning-curves-appendix-cifar-so-nwp,fig:learning-curves-appendix-so-lr}. The takeaways for \cifar and \stackoverflow~NWP are essentially the same as for \emnist---much faster convergence with the increased number of local epochs and visually noticeable improvement in losses and accuracies due to sampling-based bias correction in client deltas after the burn-in phase is over. Interestingly, we see that on \stackoverflow~LR task \FedAvg[1] clearly dominates multi-epoch methods in terms of the loss and recall at 5, losing in precision and macro-F1. Even more puzzling is the significant drop in the average precision of \FedPA[M] after the switching to sampling, while at the same time a jump in recall and F1 metrics. This indicates that the global model moves to a different fixed point where it over-predicts positive labels (\ie, less precise) but also less likely to miss rare labels (\ie, higher recall on rare labels, and as a result a jump in macro-F1). The reason why this happens, however, is unclear. \input{figures/learning_curves_appendix}
{'timestamp': '2021-02-02T02:04:43', 'yymm': '2010', 'arxiv_id': '2010.05273', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05273'}
arxiv
\section{Introduction} \label{sec:introduction} Direct transcription \cite{betts2010practical} is an effective approach to formulate and solve trajectory optimization problems. It works by converting the original trajectory optimization problem (which is \emph{continuous} in time) into a numerical optimization problem that is \emph{discrete} in time, and which in turn can be solved using an off-the-shelf \gls{NLP} solver. First, the trajectory is divided into segments and then, at the beginning of each segment, the system state and control inputs are explicitly discretized---these are the decision variables of the optimization problem. Due to this discretization approach, direct transcription falls under the class of \emph{simultaneous} methods. Finally, a set of mathematical constraints is defined to enforce boundary and path constraints, e.g., initial and final conditions, or intermediate goals. In dynamic trajectory optimization, there exists a specific set of constraints dedicated to enforce the equations of motion of the system, the so-called \emph{defect constraints}. This paper discusses different ways of defining these constraints, as well as their implications. The dynamics defects are one of the most important constraints in optimization problems when planning highly dynamic motions for complex systems, such as legged robots. Satisfaction of these constraints ensures that the computed motion is reliable and physically consistent with the nonlinear dynamics of the system. The dynamics defect constraints are usually at the very core of optimal control formulations, and require computing rigid-body dynamics and their derivatives---which account for a significant portion of the optimization computation time. Therefore, it is of utmost importance to use an algorithm that allows to compute the dynamics of the system reliably, while achieving low computational time. \begin{figure}[t] \captionsetup{font=small} \begin{subfigure}[t]{0.5\linewidth}\includegraphics[width=0.99\linewidth,left]{snapshot_talos_jump_01}\end{subfigure}\hfill% \begin{subfigure}[t]{0.5\linewidth}\includegraphics[width=0.99\linewidth,right]{snapshot_talos_jump_02}\end{subfigure}\hfill% \vspace{0.01\linewidth} \begin{subfigure}[t]{\linewidth}\includegraphics[width=\linewidth,center]{snapshot_talos_jump_03}\end{subfigure} \caption{Snapshots of the humanoid TALOS~\cite{stasse2017talos} jumping.}\label{figure:cover} \vspace{-12pt} \end{figure} In the study of the dynamics of open-chain robots, the \emph{forward dynamics} problem determines the joint accelerations resultant from a given set of joint forces and torques applied at a given state. On the other hand, the \emph{inverse dynamics} problem determines the joint torques and forces required to meet some desired joint accelerations at a given state. In trajectory optimization, most direct formulations use forward dynamics to enforce dynamical consistency \cite{pardo2016evaluating}. However, benchmarks have shown that most dynamics libraries solve the \emph{inverse dynamics} problem (e.g., with the Recursive Newton-Euler Algorithm) faster than the \emph{forward dynamics} problem (e.g., with the Articulated Body Algorithm) \cite{koolen2019julia,neuman2019benchmarking}. For example, for the humanoid robot TALOS~\cite{stasse2017talos}, the library Pinocchio~\cite{carpentier2019pinocchio} solves the inverse dynamics problem in just \SI{4}{\micro\second}, while the forward dynamics problem takes \SI{10}{\micro\second}. These differences in performance motivated us to question whether the computational advantage of inverse dynamics would translate to direct transcription---where the dynamics problem needs to be solved several times while computing the defect constraints. Moreover, there is biological evidence suggesting that inverse dynamics is employed by the nervous system to generate feedforward commands~\cite{schweighofer1998role}, while other studies support the existence of a forward model~\cite{mehta2002forward}---which increased our interest in this topic. In this work, we present a trajectory optimization framework for domains with rigid contacts, using a direct transcription approach. Particularly, our formulation allows to define dynamics defect constraints employing either forward dynamics or inverse dynamics. We defined a set of evaluation tasks across different classes of robot platforms, including fixed- and floating-base systems, with point and surface contacts. Our results showed that inverse dynamics leads to significant improvements in computational performance when compared to forward dynamics---supporting our initial hypothesis. \section{Related Work} \label{sec:related_work} \gls{RBD.jl}~\cite{rigidbodydynamicsjl}, RBDL~\cite{felis2016rbdl}, Pinocchio~\cite{carpentier2019pinocchio}, and RobCoGen~\cite{frigerio2016robcogen} are all state-of-the-art software implementations of key rigid-body dynamics algorithms. Recently, Neuman \textit{et al.} \cite{neuman2019benchmarking} benchmarked these libraries and revealed interesting trends. One such trend is that implementations of inverse dynamics algorithms have faster runtimes than forward dynamics.\footnote{% RobCoGen is an exception to this observation as it implements a hybrid dynamics solver which has a higher computational cost, and is significantly different from the implementations used by the other libraries. } Koolen and Deits \cite{koolen2019julia} also compared \gls{RBD.jl} with RBDL, and their results showed that solving inverse dynamics was at least two times faster than solving forward dynamics for the humanoid robot Atlas. Both of these studies only consider computation time of rigid-body dynamics; they do not provide insight into how these algorithms perform when used in trajectory optimization. Lee \textit{et al.} \cite{lee2005newton} have proposed Newton and quasi-Newton algorithms to optimize motions for serial-chain and closed-chain mechanisms using inverse dynamics. However, they used relatively simple mechanisms for which analytic derivatives can be obtained. In this work, we are interested in dynamic motions of complex mechanisms in domains with contact, for which the derivation of analytic derivatives is an error-prone process, involving significant effort. In the same spirit, Erez and Todorov \cite{erez2012trajectory} generated a running gait for a humanoid based on inverse dynamics under external contacts. This method allowed them to formulate an \emph{unconstrained} optimization where all contact states can be considered equally, contact timings and locations are optimized, and reaction forces are computed using a smooth and invertible contact model \cite{todorov2011convex} with convex optimization. However, their approach requires ``helper forces'', as well as tuning of contact smoothness and of the penalty parameters on the helper forces to achieve reasonable-looking behavior. In contrast, our approach does not require helper forces or any tuning whatsoever; we consider contact forces as decision variables and model contacts rigidly. Another difference is that we formulate a \emph{constrained} optimization problem and enforce the nonlinear system dynamics with hard constraints, which results in high-fidelity motions. This is especially important for deployment on real hardware, where dynamic consistency and realism are imperative. The main focus of our paper is not the contact problem, and we assume contact locations and contact times are known \textit{a priori}. Finally, to the best of our knowledge, there is no current work directly comparing inverse dynamics against forward dynamics in the context of direct methods. Posa \textit{et al.} \cite{posa2014direct} also identified that a formal comparison is important, but missing so far. They argued that one of the reasons for this was that the field had not yet agreed upon a set of canonical and hard problems. In this paper, we tackle this issue, and compare the two approaches on robots of different complexity on a set of dynamic tasks. The main contributions of this work are: \begin{enumerate} \item A direct transcription formulation that uses \emph{inverse dynamics} to enforce physical consistency, for constrained trajectory optimization in domains with rigid contacts. \item Evaluation of the performance of direct transcription formulations using either forward or inverse dynamics, for different classes of robot platforms: a fixed-base manipulator, a quadruped, and a humanoid. \item Comparison of performance for different linear solvers, and across strategies to handle the barrier parameter of the interior point optimization algorithm. \end{enumerate} We validated our trajectories in full-physics simulation and with hardware experiments. We also open-sourced a version of our framework for fixed-base robots, TORA.jl~\cite{torajl}. \section{Trajectory Optimization} \label{sec:trajectory_optimization} \subsection{Robot Model Formulation} We formulate the model of a legged robot as a free-floating base $B$ to which limbs are attached. The motion of the system can be described \gls{wrt} a fixed inertial frame $I$. We represent the position of the free-floating base \gls{wrt} the inertial frame, and expressed in the inertial frame, as ${}_I\bm{r}_{IB} \in \mathbb{R}^3$; and the orientation of the base as $\bm{\psi}_{IB} \in \overline{\mathbb{R}}{}^3$, using \gls{MRP}~\cite{gormley1945stereographic,terzakis2018modified}. The joint angles describing the configuration of the limbs of the robot (legs or arms) are stacked in a vector $\bm{q}_j \in \mathbb{R}^{n_j}$, where $n_j$ is the number of actuated joints. The generalized coordinates vector $\bm{q}$ and the generalized velocities vector $\bm{v}$ of this floating-base system may therefore be written as \begin{equation} \bm{q} = \begin{bmatrix} {}_I\bm{r}_{IB} \\ \bm{\psi}_{IB} \\ \bm{q}_j \end{bmatrix} \in \mathbb{R}^3 \times \overline{\mathbb{R}}{}^3 \times \mathbb{R}^{n_j}, \quad \bm{v} = \begin{bmatrix} \bm{\nu}_B \\ \bm{\dot{q}}_j \end{bmatrix} \in \mathbb{R}^{n_v}, \end{equation} where the twist $\bm{\nu}_B = \left [ {}_I\bm{v}_{B} \quad {}_B\bm{\omega}_{IB} \right ]^\top \in \mathbb{R}^6$ encodes the linear and angular velocities of the base $B$ w.r.t. the inertial frame expressed in the $I$ and $B$ frames, and $n_v = 6 + n_j$. For fixed-base manipulators, the generalized vectors of coordinates and velocities can be simplified to $\bm{q} = \bm{q}_j \in \mathbb{R}^{n_j}$ and $\bm{v} = \bm{\dot{q}}_j \in \mathbb{R}^{n_j}$, due to the absence of a free-floating base. \subsection{Problem Formulation} We tackle the motion planning problem using trajectory optimization; more specifically, using a \textit{direct transcription} approach. The original problem is \emph{continuous} in time, so we start by converting it into a numerical optimization problem that is \emph{discrete} in time. For that, we divide the trajectory into $N$ equally spaced segments, $t_I = t_1 < \dots < t_M = t_F$, where $t_I$ and $t_F$ are the start and final instants, respectively. This division results in $M = N + 1$ discrete \textit{mesh points}, for each of which we explicitly discretize the states of the system, as well as the control inputs. Let $x_k \equiv x(t_k)$ and $u_k \equiv u(t_k)$ be the values of the state and control variables at the $k$-th mesh point. We treat $x_k \triangleq \{ \bm{q}_k, \bm{v}_k \}$ and $u_k \triangleq \{ \bm{\tau}_k, \bm{\lambda}_k \}$ as a set of \gls{NLP} variables, and formulate the trajectory optimization problem as \begin{equation} \mathrm{find} \enspace \bm{\xi} \quad \mathrm{s.t.} \enspace x_{k+1} = f(x_k, u_k), \enspace x_k \in \mathcal{X}, \enspace u_k \in \mathcal{U}, \label{equation:nlp} \end{equation} where $\bm{\xi}$ is the vector of decision variables, $x_{k+1} = f(x_k, u_k)$ is the state transition function incorporating the nonlinear system dynamics, and $\mathcal{X}$ and $\mathcal{U}$ are sets of feasible states and control inputs enforced by a set of equality and inequality constraints. The decision variables vector $\bm{\xi}$ results from aggregating the generalized coordinates, generalized velocities, joint torques, and contact forces at every\footnote{The control inputs at the final state need not be discretized.} mesh point, i.e., \begin{align} \bm{\xi} \triangleq \{ \bm{q}_1, \bm{v}_1, \bm{\tau}_1, \bm{\lambda}_1, \cdots, \bm{q}_{N}, \bm{v}_{N}, \bm{\tau}_{N}, \bm{\lambda}_{N}, \bm{q}_M, \bm{v}_M \}. \end{align} Similarly to Winkler \textit{et al.} \cite{winkler2018gait} and differently to Erez and Todorov \cite{erez2012trajectory}, we transcribe the problem by only making use of hard constraints; and satisfaction of those constraints is a necessary requirement for the computed motions to be physically feasible and to complete the task successfully. This design decision is motivated by the fact that considering a cost function requires expert knowledge to carefully tune the weighting parameters that control the trade-off between different objective terms. Optimizing an objective function also requires additional iterations and computation time. Nonetheless, for the sake of completion, one of the experiments we present later in this paper does include and discuss the minimization of a cost function. For tasks where the robot makes or breaks contacts with the environment, we assume contact locations and contact timings are known \textit{a priori}. This assumption allows us to enforce zero contact forces for mesh points where the robot is not in contact with the environment, and therefore our formulation does not require any actual complementarity constraints. On the other hand, such assumption depends on pre-determined contact sequences specified either by a human or by a contact planner (such as \cite{winkler2018gait,tonneau2019sl1m,stouraitis2020online}). \subsection{Problem Constraints} \subsubsection{Bounds on the decision variables} We constrain the joint positions, velocities, and torques to be within their corresponding lower and upper bounds. \subsubsection{Initial and final joint velocities} We enforce the initial and final velocities of every joint to be zero: $\bm{v}_1 = \bm{v}_M = \bm{0}$. \subsubsection{End-effector pose} We enforce end-effector poses with $f^\mathrm{fk}(\bm{q}_k, i) = \bm{p}_i$, where $f^\mathrm{fk}(\cdot)$ is the forward kinematics function, $i$ refers to the $i$-th end-effector of the robot, and $\bm{p}_i \in SE(3)$ is the desired pose. \subsubsection{Contact forces} For mesh points where the robot is \emph{not} in contact with the environment, we enforce the contact forces at the respective contact points to be zero: $\bm{\lambda}_k = \bm{0}$. \subsubsection{Friction constraints} We model friction at the contacts with linearized friction cones, in the same way as \cite{caron2015leveraging}. \subsubsection{System dynamics} We enforce nonlinear whole-body dynamics, $\dot{x} = f(x, u)$, with \emph{defect} constraints. The approach used to define these constraints is the main subject of this paper, and the next section explains this in detail. \section{System Dynamics} \label{sec:system_dynamics} The equations of motion for a floating-base robot that interacts with its environment can be written as \begin{equation} \bm{M}(\bm{q})\bm{\dot{v}} + \bm{h}(\bm{q}, \bm{v}) = \bm{S}^\top \bm{\tau} + \bm{J}_s^\top(\bm{q}) \bm{\lambda}, \label{equation:equations_of_motion_floating_base} \end{equation} where $\bm{M}(\bm{q}) \in \mathbb{R}^{n_v \times n_v}$ is the mass matrix, and $\bm{h}(\bm{q}, \bm{v}) \in \mathbb{R}^{n_v}$ is the vector of Coriolis, centrifugal, and gravity terms. On the right-hand side of the equation, $\bm{\tau} \in \mathbb{R}^{n_\tau}$ is the vector of joint torques commanded to the system, and the selection matrix $\bm{S} = [\bm{0}_{n_\tau \times (n_v - n_\tau)} \quad \mathbb{I}_{n_\tau \times n_\tau}]$ selects which \gls{DoF} are actuated. We consider that all limb joints are actuated, thus $n_\tau = n_j$. The vector $\bm{\lambda} \in \mathbb{R}^{n_s}$ denotes the forces and torques experienced at the contact points, with $n_s$ being the total dimensionality of all contact wrenches. The support Jacobian $\bm{J}_s \in \mathbb{R}^{n_s \times n_v}$ maps the contact wrenches $\bm{\lambda}$ to joint-space torques, and it is obtained by stacking the Jacobians which relate generalized velocities to limb end-effector motion as $\bm{J}_s = [\bm{J}_{C_1}^\top \quad \cdots \quad \bm{J}_{C_{n_c}}^\top]^\top$, with $n_c$ being the number of limbs in contact. For fixed-base robots that are not subject to contact forces, we can simplify the equations of motion to $\bm{M}(\bm{q})\bm{\dot{v}} + \bm{h}(\bm{q}, \bm{v}) = \bm{\tau}$. In order to enforce the equations of motion of nonlinear systems, we define a set of equality constraints within our framework, the so-called \emph{defect constraints}. Usually, these constraints are defined using a forward dynamics algorithm, but in this paper we argue that using inverse dynamics can be more computationally advantageous. The standard problem of forward dynamics computes the joint accelerations resultant from commanding torques and applying forces to the robot at a given state, i.e., \begin{equation} \bm{\dot{v}}_{k}^{\ast} = f^\mathrm{fd}(\bm{q}_{k}, \bm{v}_{k}, \bm{\tau}_{k}, \bm{\lambda}_{k}), \label{equation:forward_dynamics} \end{equation} where $f^\mathrm{fd}(\cdot)$ is the function that solves forward dynamics. The asterisk ${(\cdot)}^{\ast}$ denotes intermediately computed values, whereas terms without an asterisk are \gls{NLP} variables. Using the semi-implicit Euler method as the integration scheme and $h = (t_F - t_I) / N$ as the integration time step, we can compute the state of the robot after $h$ seconds. First, we integrate $\bm{\dot{v}}_{k}^{\ast}$ to compute the next generalized velocities $\bm{v}_{k+1}^{\ast} = \bm{v}_{k} + h \, \bm{\dot{v}}_{k}^{\ast}.$ Then, we can compute the time derivative of the generalized coordinates, $\bm{\dot{q}}_{k+1}^{\ast}$, from those velocities, $\bm{v}_{k+1}^{\ast}$. In turn, we integrate that time derivative to compute the next generalized coordinates, $\bm{q}_{k+1}^{\ast} = \bm{q}_{k} + h \, \bm{\dot{q}}_{k+1}^{\ast}$. After these calculations, we end up with two different values for the state of the system at mesh point $k+1$: one from the discretized \gls{NLP} variables, and another computed as a result of the controls applied to the system at mesh point $k$. To enforce dynamical consistency, we define the defect constraints as \begin{equation} \bm{q}_{k+1}^{\ast} - \bm{q}_{k+1} = \bm{0} \quad \text{and} \quad \bm{v}_{k+1}^{\ast} - \bm{v}_{k+1} = \bm{0}. \label{equation:defects_1} \end{equation} However, there is an alternative way to enforce dynamical consistency: with inverse dynamics. In contrast to \eqref{equation:forward_dynamics}, inverse dynamics computes the joint torques and forces required to meet desired joint accelerations at a given state, i.e., \begin{equation} \bm{\tau}_{k}^{\ast} = f^\mathrm{id}(\bm{q}_{k}, \bm{v}_{k}, \bm{\dot{v}}_{k}^{\ast}, \bm{\lambda}_{k}), \label{equation:inverse_dynamics} \end{equation} where $f^\mathrm{id}(\cdot)$ is the function that solves the inverse dynamics problem, and the desired joint accelerations can be calculated implicitly with $\bm{\dot{v}}_{k}^{\ast} = (\bm{v}_{k+1} - \bm{v}_{k}) / h$. Similarly to the forward dynamics case, we compute $\bm{\dot{q}}_{k+1}^{\ast}$ from $\bm{v}_{k+1}$, and integrate it to compute the next generalized coordinates $\bm{q}_{k+1}^{\ast}$. And finally, we define the dynamics defect constraints as \begin{equation} \bm{q}_{k+1}^{\ast} - \bm{q}_{k+1} = \bm{0} \quad \text{and} \quad \bm{\tau}_{k}^{\ast} - \bm{\tau}_{k} = \bm{0}. \label{equation:defects_2} \end{equation} Notice that the main difference between equations \eqref{equation:defects_1} and \eqref{equation:defects_2} is that forward dynamics enforces consistency of the generalized velocities whereas inverse dynamics enforces consistency of joint torques commanded to the system. The main subject of this paper revolves around the two formulations explained above to enforce the nonlinear system dynamics: \emph{forward dynamics} vs. \emph{inverse dynamics}. We developed our framework with both options in mind, and we are able to easily toggle between one approach and the other, which was particularly useful for our experiments. \section{Experiments and Results} This section is organized into four subsections: \begin{itemize} \item [A.] Compares the computation time and number of solver iterations required to find locally-optimal solutions; \item [B.] Evaluates the robustness of each approach as problem discretization gets more coarse (larger time steps); \item [C.] Analyzes the performance of each formulation for the minimization of a cost function; and finally, \item [D.] Shows hardware validation of the planned motions. \end{itemize} All evaluations were carried out in a single-threaded process on an Intel i7-6700K CPU with clock frequency fixed at \SI{4.0}{\giga\hertz}, and \SI{32}{\giga\byte} \SI{2133}{\mega\hertz} memory. The framework we propose has been implemented in Julia~\cite{bezanson2017julia}, using the rigid-body dynamics library \gls{RBD.jl}~\cite{rigidbodydynamicsjl}, and the optimization library Knitro~\cite{byrd2006knitro}. To solve the formulated \gls{NLP} problems, we used the interior-point method of Waltz \textit{et al.} \cite{waltz2006interior}. \subsection{Evaluation of Convergence} In order to evaluate and compare forward dynamics against inverse dynamics in the context of direct transcription, we used our framework to specify tasks in the form of numerical optimization problems for different types of robots: a manipulator, a quadruped, and a humanoid. Those robots were selected as they allows us to evaluate the formulations for distinct features: fixed- and floating-base systems, single-point and surface contacts, and low and high dimensionality. For each task on each robot, we solved the optimization problem twice: first defining the defect constraints with forward dynamics, and then with inverse dynamics. The \emph{only} changing factor was the toggling between forward and inverse dynamics for the definition of the defect constraints; every other aspect of the formulation was kept unchanged. The performance of general \gls{NLP} solvers is greatly affected by the linear solver used for solving the linear systems of equations of the problem. For this reason, we tested different state-of-the-art linear solvers exhaustively. For interior-point methods, another important factor that affects performance is the update strategy of the barrier parameter. Therefore, for all of our evaluations, we tested the different strategies available within the Knitro~\cite{byrd2006knitro} library exhaustively. \begin{figure}[t] \captionsetup{font=small} \begin{subfigure}[t]{0.333\linewidth} \includegraphics[width=0.98\linewidth,center]{task_kuka} % \caption{Manipulator}\label{figure:robot_kuka} \end{subfigure}\hfill% \begin{subfigure}[t]{0.333\linewidth} \includegraphics[width=0.98\linewidth,center]{task_anymal} % \caption{Quadruped}\label{figure:robot_anymal} \end{subfigure}\hfill% \begin{subfigure}[t]{0.333\linewidth} \includegraphics[width=0.98\linewidth,center]{task_talos} % \caption{Humanoid}\label{figure:robot_talos} \end{subfigure} \caption{ % % Left to right: KUKA iiwa tracing a circular path, ANYmal jumping in-place, and TALOS jumping forward. }\label{figure:robot_tasks} \vspace{-12pt} \end{figure} In the remainder of this subsection, we present the task specifications for each robot and indicate all the parameters for reproducibility. Then, we present the results we obtained for each task, which evaluated the solver's performance in terms of computation time and number of iterations taken by the solver until a locally-optimal solution was found. \subsubsection{Manipulator} We evaluated the different formulations using a fixed-base robot arm with seven \gls{DoF} (shown in \autoref{figure:robot_kuka}). We specified the end-effector to trace a circular path given by $[0.5, 0.2 \cos \theta, 0.8 + 0.2 \sin \theta] \forall \theta \in [0,2\pi]$. The total duration was set to \SI{2.0}{\second} and the trajectory was discretized at \SI{150}{\hertz}, resulting in a total of \num{301} mesh points. \subsubsection{Quadruped} The quadruped robot we used is shown in \autoref{figure:robot_anymal}. This system is more complex than the manipulator due to its floating-base, more \gls{DoF} (three motors per leg), and because it needs to handle contact forces. We defined a jumping task by enforcing the contact forces to be zero for a short period of time. The trajectory was discretized at \SI{100}{\hertz}, the total duration of the motion was \SI{2.0}{\second}, and the interval specified for the flight-phase was $[1.0,1.2]$ \si{\second}. We did not constrain feet positions during the flight-phase, which allowed the solver to converge to a solution where the feet swing most naturally according to the system dynamics. \subsubsection{Humanoid} Finally, we considered the humanoid robot shown in \autoref{figure:robot_talos}. This robot is more complex than the quadruped because it has 27 \gls{DoF}\footnote{% The real robot has more \gls{DoF}: grippers, neck, and one more \gls{DoF} at the torso. For simplicity, we assumed those joints were fixed to zero. } (seven per arm, six per leg, and one at the torso), and its feet cannot be simplified to single-point contacts. We also defined a jumping task for this robot. The motion duration was \SI{1.2}{\second}, discretized at \SI{125}{\hertz}, and the interval for the flight-phase was $[0.5,0.8]$ \si{\second}. For all the tasks, the initial guess was a fixed standing configuration and zero velocities, torques, and contact forces. The results of the experiments on these robots are shown in \autoref{table:results}, where smaller numbers indicate better performance. The rows of the table are grouped according to robot, dynamics, and linear solver. Each row shows the time taken to solve the optimization problem for each barrier update strategy, as well as the total number of iterations (within parenthesis). The last column shows the time spent on each iteration, averaged over all of the update strategies. \begin{table}[t] \captionsetup{font=small} \centering \caption[Computation time and number of iterations for each robot's task.]{ Computation time\footnotemark (in seconds) and number of iterations (within parenthesis) for each robot. % % The best computation time for each dynamics and each robot is highlighted in bold. }\label{table:results} \begin{adjustbox}{width=1\linewidth} \begin{tabular}{@{\hskip 0pt}c@{\hskip 8pt}ccr@{\hskip 0pt}rr@{\hskip 0pt}rr@{\hskip 0pt}rc@{\hskip 0pt}} \toprule & & Linear & \multicolumn{6}{c}{Barrier strategy (\texttt{bar\_murule})} & Average time \\ & & Solver & \multicolumn{2}{c}{\texttt{adaptiv}} & \multicolumn{2}{c}{\texttt{dampmpc}} & \multicolumn{2}{c}{\texttt{quality}} & per iteration (\si{\second}) \\ \midrule[\heavyrulewidth] \multirow{6.5}{*}{\begin{turn}{90}KUKA iiwa\end{turn}} & \multirow{3}{*}{\begin{turn}{90}Fwd D\end{turn}} & MA27 & \textbf{0.40} & (5) & 0.49 & (6) & 0.43 & (5) & 0.08 $\pm$ 0.002 \\ & & MA57 & 0.41 & (5) & 0.48 & (6) & 0.42 & (5) & 0.08 $\pm$ 0.001 \\ & & MA97 & 0.46 & (5) & 0.56 & (6) & 0.50 & (5) & 0.09 $\pm$ 0.002 \\ \cdashlinelr{2-10} & \multirow{3}{*}{\begin{turn}{90}Inv D\end{turn}} & MA27 & \textbf{0.20} & (4) & 0.26 & (5) & 0.23 & (4) & 0.05 $\pm$ 0.002 \\ & & MA57 & 0.22 & (4) & 0.28 & (5) & 0.24 & (4) & 0.05 $\pm$ 0.001 \\ & & MA97 & 0.27 & (4) & 0.33 & (5) & 0.29 & (4) & 0.07 $\pm$ 0.002 \\ \midrule[\heavyrulewidth] \multirow{6.5}{*}{\begin{turn}{90}ANYmal B\end{turn}} & \multirow{3}{*}{\begin{turn}{90}Fwd D\end{turn}} & MA27 & 2.26 & (7) & 2.80 & (9) & 2.34 & (7) & 0.31 $\pm$ 0.021 \\ & & MA57 & 2.80 & (10) & 2.49 & (9) & 32.13 & (99) & 0.29 $\pm$ 0.020 \\ & & MA97 & \textbf{2.21} & (7) & 2.76 & (9) & 2.26 & (7) & 0.31 $\pm$ 0.009 \\ \cdashlinelr{2-10} & \multirow{3}{*}{\begin{turn}{90}Inv D\end{turn}} & MA27 & 2.99 & (13) & 2.60 & (11) & 2.18 & (9) & 0.23 $\pm$ 0.005 \\ & & MA57 & 2.90 & (13) & 2.54 & (11) & \textbf{2.10} & (9) & 0.22 $\pm$ 0.004 \\ & & MA97 & 3.21 & (13) & 2.81 & (11) & 2.37 & (9) & 0.25 $\pm$ 0.007 \\ \midrule[\heavyrulewidth] \multirow{6.5}{*}{\begin{turn}{90}TALOS\end{turn}} & \multirow{3}{*}{\begin{turn}{90}Fwd D\end{turn}} & MA27 & --- & & --- & & 14.82 & (15) & 0.94 $\pm$ 0.115 \\ & & MA57 & --- & & 13.47 & (19) & 44.23 & (66) & 0.68 $\pm$ 0.020 \\ & & MA97 & 13.42 & (18) & \textbf{11.48} & (15) & 12.92 & (16) & 0.76 $\pm$ 0.026 \\ \cdashlinelr{2-10} & \multirow{3}{*}{\begin{turn}{90}Inv D\end{turn}} & MA27 & 8.38 & (15) & 8.02 & (13) & 38.59 & (70) & 0.57 $\pm$ 0.035 \\ & & MA57 & 7.36 & (15) & \textbf{ 6.59} & (13) & 36.88 & (73) & 0.50 $\pm$ 0.014 \\ & & MA97 & 7.43 & (15) & 6.61 & (13) & 41.84 & (82) & 0.50 $\pm$ 0.012 \\ \bottomrule \end{tabular} \end{adjustbox} \vspace{-12pt} \end{table} \footnotetext{% This table (and future tables) show the minimum time value observed over \num{10} trials. Reporting the minimum time is more reliable than the median or the mean, since all measured noise is positive, as explained in \cite{chen2016robust}. } In general, we can see that the computation time depends mostly on the complexity of the system, regardless of linear solver or barrier update strategy; i.e., solving the manipulator task was faster than solving the quadruped task, which in turn was faster than the humanoid task. More importantly, for each robot and given the same choice of linear solver and update strategy, the computation time of inverse dynamics was better than forward dynamics. We can also see that the number of iterations required to solve the problem did not change significantly (apart from a few exceptions). This indicates that the difficulty of the problem itself did not change with the different dynamics defects; it just took longer to solve using forward dynamics---as supported by the information in the last column of the table. \subsection{Robustness to Coarser Problem Discretizations} In the next experiment, we compare the ability of each formulation to handle trajectories discretized using fewer mesh points. We defined the same quadruped jumping task repeatedly, but transcribed it with different resolutions. First, we divided the trajectory into equally spaced segments with a time step of $h=0.01$; we solved the optimization problem and took the resulting trajectory as our baseline. Then, we incrementally changed $h$, making the problem more coarse each time, and compared the obtained trajectories against the baseline. The problems were initialized with a nominal configuration repeated for each point, and zero velocities, torques and contact forces. The results of this experiment are shown in \autoref{figure:rms_error} and \autoref{table:stress_test}. The plots in \autoref{figure:rms_error} show that the solutions deviate more from the baseline as the number of mesh points used to discretize the problem decreases (in the $x$-axis, from right to left). But more importantly, the plots reveal that the rate at which deviation occurs is significantly different depending on the formulation. We can see that the \gls{RMSE} of the formulation using inverse dynamics is significantly lower than that of the forward. \begin{table}[t] \captionsetup{font=small} \centering \caption{Computation time and number of iterations required by different problem discretizations, for the quadruped jump.} \label{table:stress_test} \begin{tabular}{ccccccc} \toprule \multirow{2}{*}{Frequency} & & \multicolumn{2}{c}{Forward Dyn.} & & \multicolumn{2}{c}{Inverse Dyn.} \\ & & Time (\si{\second}) & Iter. & & Time (\si{\second}) & Iter. \\ \midrule % % \SI{100}{\hertz} & & 3.289 & 10 & & 3.295 & 13 \\ \SI{90}{\hertz} & & 3.916 & 14 & & 2.774 & 13 \\ \SI{80}{\hertz} & & 5.227 & 21 & & 1.821 & 9 \\ \SI{70}{\hertz} & & 4.062 & 19 & & 1.344 & 8 \\ \SI{60}{\hertz} & & 1.518 & 9 & & 1.193 & 8 \\ \SI{50}{\hertz} & & 2.226 & 16 & & 0.983 & 8 \\ \SI{40}{\hertz} & & 1.099 & 9 & & 0.785 & 8 \\ \SI{30}{\hertz} & & 0.731 & 8 & & 0.534 & 7 \\ \SI{20}{\hertz} & & 0.433 & 7 & & 0.354 & 7 \\ % \bottomrule \end{tabular} % \end{table} \begin{figure}[t] \captionsetup{font=small} \centering \includegraphics[width=\linewidth]{rmse_of_trajectories} \caption{ Root-mean-square error (RMSE) of joint positions, velocities, torques, and contact forces of each formulation for different discretizations, using a baseline of \SI{120}{\hertz}. }\label{figure:rms_error} \vspace{-16pt} \end{figure} \autoref{table:stress_test} shows the computation time (in seconds) and the number of iterations required to solve the quadruped task using different discretizations. We can see that the time required to solve the problem using inverse dynamics follows a clear pattern: it decreases as the problem gets more coarse; and the same goes for the number of iterations. In contrast, a pattern does not seem to exist for forward dynamics. The results shown in \autoref{figure:rms_error} and \autoref{table:stress_test} provide strong evidence that defining the defect constraints with inverse dynamics is the approach more robust to different problem discretizations, both in terms of deviation from realistic solutions and in terms of computation performance. \begin{figure*}[t] \captionsetup{font=small} \begin{subfigure}[t]{0.2\linewidth} \includegraphics[width=0.98\linewidth,center]{snapshot_anymal_01} \caption{Initial configuration} \end{subfigure}\hfill% \begin{subfigure}[t]{0.2\linewidth} \includegraphics[width=0.98\linewidth,center]{snapshot_anymal_02} \caption{Take-off} \end{subfigure}\hfill% \begin{subfigure}[t]{0.2\linewidth} \includegraphics[width=0.98\linewidth,center]{snapshot_anymal_03} \caption{Full-flight phase} \end{subfigure}\hfill% \begin{subfigure}[t]{0.2\linewidth} \includegraphics[width=0.98\linewidth,center]{snapshot_anymal_04} \caption{Landing} \end{subfigure}\hfill% \begin{subfigure}[t]{0.2\linewidth} \includegraphics[width=0.98\linewidth,center]{snapshot_anymal_05} \caption{Final configuration} \end{subfigure} \caption{ Snapshots of ANYmal~\cite{hutter2017anymal} performing a \SI{0.5}{\meter}-long jump. The length of the black tape on the ground is \SI{0.5}{\meter}. }\label{figure:snapshots_anymal} \vspace{-8pt} \end{figure*} \subsection{Optimization with an Objective Function} Thus far we have analyzed the trajectory optimization performance for feasibility problems. However, in optimization, it is common to define a cost function to be minimized (or a value function to be maximized). In this next experiment, we evaluate the performance of our formulation when a cost function is considered. We minimize the actuator torques and ground-reaction contact forces with $\min_{\bm{\xi}} \quad \sum_{k=1}^{M-1} \frac{\bm{\tau}_k^\top \bm{\tau}_k + \bm{\lambda}_k^\top \bm{\lambda}_k}{M-1}$. We tested this cost function on the quadruped jump task, with the MA57 linear solver and \texttt{adaptive} barrier parameter update strategy. Both formulations converged to very similar solutions: the \gls{RMSE} between the two trajectories was \num{0.038}. The final objective value was \num{3.567801e+04} and \num{3.567804e+04} for forward and inverse dynamics, respectively. Despite converging to similar solutions, the formulation employing inverse dynamics finished in \SI{6.208}{\second}, showing better performance than the formulation using forward dynamics which took \SI{14.570}{\second}. The time in seconds corresponds to the minimum value measured over a total of 10 samples. \autoref{figure:minimization} shows the evolution of the cost and feasibility error throughout the optimization. The star-shaped marker denotes the point at which the local minimum of the problem was found. In the left plot, we can see that inverse dynamics reached values close to the optimal cost much earlier than forward dynamics. In the right plot, we can see that inverse dynamics required less iterations than forward dynamics to cross the faint-green line, which marks the point at which the error becomes acceptable to be considered feasible. Inverse dynamics converged in \num{26} iterations, and forward dynamics converged in \num{43} iterations. Inadvertently, one advantage of the forward formulation was that its final feasibility error was smaller than that of inverse dynamics. \begin{figure}[t] \captionsetup{font=small} \centering \includegraphics[width=\linewidth]{minimization} \caption{ Evolution of the cost and the feasibility error during convergence. The faint-green line at $y=10^{-3}$ denotes the tolerance under which we consider a problem to be feasible. }\label{figure:minimization} \vspace{-12pt} \end{figure} \subsection{Hardware Validation} We conducted real-world experiments with ANYmal~\cite{hutter2017anymal} and TALOS~\cite{stasse2017talos} to validate the trajectories computed with our framework. The motion planning is performed offline and then the trajectories are sent to the controller for playback. To execute the whole-body motions, we commanded each joint with feedforward torque and feedback on joint position and velocity. For the quadruped, we updated the references for each joint's position, velocity, and torque at \SI{400}{\hertz}. The decentralized motor controller at every joint closes the loop compensating for friction effects. On the humanoid, we updated the references at \SI{2}{\kilo\hertz}, and a centralized controller compensates for the motor dynamics and friction. \autoref{figure:cover} and \autoref{figure:snapshots_anymal} contain snapshots of the jumps realized with the humanoid and with the quadruped, respectively. These experiments can be seen in our supplementary video: \texttt{\url{https://youtu.be/pV4s7hzUgjc}}. Jumping motion is challenging to execute in real hardware because it includes a severely underactuated phase when the robot is fully off the ground. Nonetheless, our controller is able to execute our planned trajectories reliably, attesting the dynamical consistency of our formulation. \section{Discussion} \label{sec:discussion} The results of this work indicate that direct transcription implementations relying on forward dynamics to define the defect constraints can be reformulated with inverse dynamics to see an increase in performance, for both feasibility or minimization problems, and without sacrificing the feasibility of the solutions to the optimization problem. An additional reason to prefer inverse dynamics is robustness to coarser discretizations, both in terms of computation efficiency and faithfulness of solutions with respect to finer discretizations. When minimizing a cost function, the locally-optimal solutions computed with either formulation are essentially the same. However, when an objective function is not considered, the formulations may diverge to different solutions. Experimentally, we have observed that the solutions computed with inverse dynamics are easier to perform in real hardware. The reasons behind this divergence are not yet clear to us, and this is something we plan to investigate in future work. Erez and Todorov \cite{erez2012trajectory} observed a striking feature in their results: an emergent coordination between legs and opposite arms during a running gait. In this work, for the humanoid jumping task, we also observed such emerging behavior: the resulting motions swing the arms upwards to build-up energy before the take-off instant. Both in \cite{erez2012trajectory} and our work, these features originated without any explicit modeling---reaffirming the power of dynamic trajectory optimization. In recent work \cite{ferrolho2020optimizing}, we took into account uncertainty and robustness to disturbances using direct transcription. Considering uncertainty usually incurs additional computational cost due to more complex problem formulations. With the findings from this paper, we plan to redefine the dynamics defect constraints in that work with inverse dynamics, improving the performance of our robustness framework and making it more competitive. \bibliographystyle{IEEEtran}
{'timestamp': '2021-03-12T02:27:46', 'yymm': '2010', 'arxiv_id': '2010.05359', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05359'}
arxiv
\section{Introduction} Google Landmark Retrieval and Recognition competitions have been running for the third consecutive year. In previous years, winning solutions used a combination of global and local features, such as last year's first place winners in recognition \cite{2019recognition1st} and retrieval \cite{2019retrieval1st} tracks. Interestingly, the advances in state-of-the-art image classification models over the past year, especially EfficientNet \cite{efficientnet}, together with their open source ImageNet pretrained weights, have pushed the performance of global feature only models on this task so high that the additional benefit of local feature models could be marginal or negligible. This is evidenced by the fact that none of top three solutions in Retrieval 2020 \cite{Retrieval1st,Retrieval2nd,Retrieval3rd} nor the first place solution in Recognition 2020 \cite{2020recog1st} used local features. Our solution, too, consists of only global feature models. It is an ensemble of 7 metric learning models. The architecture of choice is Sub-center ArcFace \cite{subcenter}. To alleviate the extreme class imbalance in the GLDv2 dataset \cite{GLDv2}, we propose dynamic margins for ArcFace loss, a family of continuous functions of class size, which gives major performance boost over constant margins. We designed a progressive finetuning schedule to deal with the huge dataset in limited time. Lastly, we applied postprocessing strategies taking advantage of both feature similarity search and ArcFace head's output. We attempted to use local feature models like DELG \cite{Delg}, but they did not boost the ensemble's performance. In section 2, we explain the dynamic margins in more details. Training schedule and setup are discussed in section 3. We then describe our test set predicting strategy in section 4. Finally, the ensemble and scores are presented in section 5. \section{Model architecture: Sub-center ArcFace with dynamic margins} ArcFace \cite{arcface} has been the state-of-the-art metric learning methods. In this competition, we used Sub-center ArcFace \cite{subcenter}, a recent improvement over ArcFace, designed to better handle noisy data. Sub-center ArcFace may be particularly suitable for GLDv2 dataset besides the fact that it is noisy. The idea is that each class may have more than one class centers. For example, a certain landmark's photos may have a few clusters (e.g. taken from different angles). Sub-center ArcFace's model weights include multiple class centers' representations, which can increase classification accuracy and improve global feature's quality. We chose number of sub-centers $K=3$. Another feature of the GLDv2 dataset is that it's extremely imbalanced with very longs tails. Inspired by AdaptiveFace \cite{adaptiveface}, we aim to assign different margin levels for different class sizes. For models to converge better in the presence of heavy imbalance, smaller classes need to have bigger margins as they are harder to learn. Instead of manually setting different margin levels based on class size, we introduce dynamic margins, a family of continuous functions mapping class size to margin level: $$f(n) = a\cdot n^{-\lambda}+b$$ where $a,b,\lambda$ are parameters. $\lambda>0$ determines the shape of the margin function. The closer $\lambda$ is to 0, the similar it is to a linear function. $a$ and $b$ determines the upper of lower bounds of each margin function. See Figure \ref{fig:model}. \begin{figure} \includegraphics[width=0.9\linewidth]{dynamic_margins.png} \caption{\textbf{Constant margin and three dynamic margins as function of class size} } \label{fig:model} \end{figure} We experimented with $\lambda=1, \frac14, \frac18$ using a baseline EfficientNet-B0 model with image size 256. We tuned the optimal lower and upper bounds of each function separately. The model score of each dynamic function are listed in Table \ref{tab:margin}, compared with constant margin at its optimal level 0.25. The best dynamic function is $n^{-1/4}$ with lower and upper bounds 0.05 and 0.5 respectively. It has over 0.025 gain in validation GAP score over constant margin baseline. We used this best dynamic function to train all our models in the final ensemble. \begin{table*}[h] \begin{center} \begin{tabular}{cccc} \toprule margin function & lower and upper bounds & validation accuracy & validation GAP \\ \midrule constant margin& 0.25 & 0.4762 & 0.84176 \\ 1/n & 0.2 -- 0.55 & 0.4805 & 0.85475 \\ $n^{-1/8}$& 0 -- 0.4 & 0.4814 & 0.86471 \\ $n^{-1/4}$& 0.05 -- 0.5 & \textbf{0.4822} & \textbf{0.86710} \\ \bottomrule \end{tabular} \caption{Validation scores of three dynamic margin functions of baseline EfficientNet B0 model with 256 image size, compared with the constant margin counterpart. The constant margin level 0.25 and the upper and lower bounds of each dynamic margin functions are tuned optimal values. }\label{tab:margin} \end{center} \end{table*} \section{Training schedule and setup} In the competition dataset, cGLDv2 (cleaned GLDv2), there are 1.6 million images and 81k classes. All landmark test images belong to these classes. In the original GLDv2 dataset\cite{GLDv2}, there are 4.1 million images and 203k classes, among which 3.2 million images belong to the 81k cGLDv2 classes. We noticed that (1) training with the 3.2 million data gives better results than only the 1.6 million competition cGLDv2 data, (2) pretraining on all 4.1 million data then finetuning on 3.2 million data gives even better results. Therefore, we designed the following progressive finetuning strategy similar to the winning solution in Google Landmark Retrieval 2020 \cite{Retrieval1st}: \begin{itemize} \item Stage 1 (pretrain): 10 epochs with small image size (256) on the full 4.1 million images \item Stage 2 (finetune): 15-20 epochs with medium image size (512 to 768 depending on model) on 3.2 million images \item Stage 3 (finetune): 1-10 epoch with large image size (672 to 1024) on 3.2 million images \end{itemize} We used the following augmentations during training: horizontal flip, image compression, shift, scale, rotate and cutout\cite{cutout}. We find heavier augmentations hurt model performance. All images are resized into square shape without cropping. Training data is split into stratified 5-fold. Each model is trained on 4 folds and validated on only 1/15 of the other fold in order to save time. We used different folds to train different single models to increase model diversity. GAP metric is used for validation scores, same as the leaderboard. But validation scores are much higher than leaderboard scores, due to the absence of non-landmark images in our validation set. All our single model's validation GAP scores are over 0.967. \section{Test set predicting strategy} \subsection{Baseline approach} The ArcFace model can output a 512-dimensional global feature for any input image. For each image in the query set (i.e. test set), calculate its global feature cosine similarity between all the gallery set (i.e. private train set) images. Use the top 1 nearest neighbor's class and the corresponding cosine similarity as the prediction and confidence score for this query image. Our best single model scored \textbf{0.5859/0.6040} (private/public) using this baseline approach. \subsection{Postprocessing step 1} Instead of using top 1 nearest neighbor only, we can improve it by combining the same-class images in top 5 nearest neighbors and their cosine similarities. We found the best combining function to be 8th power, i.e. applying the 8th power function to each individual scores before summing. A high power ensures that high values in cosine similarity dominate lower values, making it harder for top 1 predictions to be overturned. It is illustrated in Fig \ref{fig:PP}. In this example, 1st and 4th nearest neighbors are the same class while the 2nd and 3rd nearest neighbors are the same class. After combining, the predicted class is still class 1. But the score changed, which has an effect on the relative position of this test image in GAP metric calculation. \begin{figure*}[] \centering \includegraphics[width=1\textwidth]{PP.png} \caption{Postprocessing illustration.} \label{fig:PP} \end{figure*} Best single model's score improved to \textbf{0.5932/0.6104} (private/public) after postprocessing step 1. \subsection{Postprocessing step 2} We can further improve it by incorporating ArcFace head's predicted scores. They represent the test image's cosine similarity to each class center, which contain information the model learned from the whole public train set. The best function to incorporate ArcFace head's score is found to be 12th power. Postprocessing step 2 is also illustrated in Fig \ref{fig:PP}. In this example, class 2's ArcFace head score is higher than class 1, boosting class 2 to have the highest overall score. Best single model's score increased to \textbf{0.6014/0.6244} (private/public) with both postprocessing steps. \section{Ensemble} We trained 7 models for the ensembles: EfficientNets-B7, B6, B5, B4, B3\cite{efficientnet}, ResNeSt-101\cite{resnest}, ReXNet2.0\cite{rexnet}. In ensemble 1, each model is pretrained for 10 epochs on full GLDv2 data at small image size (256), then finetuned on the 81313 subset of GLDv2 data at medium image size (512 to 768) for 13-21 epochs, then finetuned again on the same data at large image size (672 to 1024) for 1 epoch. See Table \ref{tab:score1} for detailed model configuration and scores. In order to have diversity between the two submissions, we finetuned the models for more epochs in ensemble 2. In some models, the finetune image size also changed. Moreover, a second Efficient-B5 and B6 models (the two best single models) are added to ensemble 2, making it a 9-model ensemble. Detailed model configuration and scores are listed in Table \ref{tab:score2}. For global feature neighbor search, we concatenated each model's 512-dimensional feature before computing the cosine similarities between gallery and query images; for ArcFace head, we take simple average of each model's output. Ensemble 1 has higher public LB score (0.6604), but ensemble 2 has higher private LB score (0.6344). Both submissions are good enough for third place on private leaderboard. \begin{table*}[ht] \begin{center} \small \setlength\tabcolsep{1.5pt} \begin{tabular}{p{2.7cm}p{2.3cm}p{1.5cm}cc} \toprule Model &Image Size& Epochs &Private LB &Public LB\\ \hline EfficientNet-B7 &256, 512, 672 &10, 13, 1 &0.5678 & 0.5838\\ EfficientNet-B6 &256, 512, 768 &10, 17, 1 &0.5807 & 0.6030\\ EfficientNet-B5 &256, 576, 768 &10, 16, 1 &0.5829 & 0.6037\\ EfficientNet-B4 &256, 704, 768 &10, 16, 1 &0.5768 & 0.5905\\ EfficientNet-B3 &256, 544, 1024 &10, 18, 1 &0.5687 & 0.5857\\ ResNeSt101 &256, 576, 768 &10, 16, 1 &0.5711 & 0.5953\\ ReXNet2.0 &256, 768, 1024 &10, 21, 1 &0.5757 & 0.5998\\ \hline Ensemble &&&0.6109& 0.6368\\ Ensemble with PP &&&\textbf{0.6289}& 0.6604\\ \bottomrule \end{tabular} \caption{\textbf{Ensemble 1's model configuration and scores.} The three numbers in Image Size and Epochs columns are the image size and number of epochs in each of the three training stages. Single model's scores are without postprocessing (PP).}\label{tab:score1} \end{center} \end{table*} \begin{table*}[ht] \begin{center} \small \setlength\tabcolsep{1.5pt} \begin{tabular}{p{2.7cm}p{2.3cm}p{1.5cm}cc} \toprule Model & Image Size& Epochs &Private LB &Public LB\\ \hline EfficientNet-B7 &256, 512, 672 &10, 13, 5 \\ EfficientNet-B6 &256, 512 &10, 36 &0.5842 &0.6028\\ EfficientNet-B6 &256, 512, 768 &10, 28, 5 \\ EfficientNet-B5 &256, 576, 768 &10, 16, 1 &0.5829 &0.6037\\ EfficientNet-B5 &256, 576, 768 &10, 33, 4 \\ EfficientNet-B4 &256, 704, 768 &10, 16, 5 &0.5748 &0.5944\\ EfficientNet-B3 &256, 544, 768 &10, 29, 10 \\ ResNeSt101& 256, 576, 768 &10, 16, 6 \\ ReXNet2.0 &256, 768 &10, 38 \\ \hline Ensemble &&& 0.6134 & 0.6318\\ Ensemble with PP &&&\textbf{0.6344}& 0.6581\\ \bottomrule \end{tabular} \caption{\textbf{Ensemble 2's model configuration and scores.} The numbers in Image Size and Epochs columns are the image size and number of epochs in each of the two or three training stages. Empty single model score means we did not submit those epochs individually. There are two more single models in ensemble 2 than in ensemble 1.}\label{tab:score2} \end{center} \end{table*} \bibliographystyle{plain}
{'timestamp': '2020-10-13T02:25:51', 'yymm': '2010', 'arxiv_id': '2010.05350', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05350'}
arxiv
\section{Introduction} Sign language translation (SLT), as an essential sign language interpretation task, aims to provide text-based natural language translation for continuously signing videos. Since sign languages are distinct linguistic systems~\cite{pfau2018syntax} which differ from natural languages, signed sentence and their translation into natural languages do not syntactically align. For instance, sign languages have different word ordering rules from their natural language counterparts. Because of such discrepancies between a sign language and its natural language translation, SLT methods are often required to jointly learn embedding space of sign sentence videos and natural languages as well as mappings between them, leading to a difficult sequential learning problem. Existing SLT approaches can be categorized into \emph{two-staged} and \emph{bootstrapping} approaches depending on whether they require additional annotations for video and text alignments or not. Two-staged models require extra annotations, namely \emph{gloss}, to describe sign videos with word labels in their occurring order. These models first learn to recognize gestures using gloss annotations and then rearrange the recognition results into natural language sentences. Gloss annotations significantly ease the syntactic alignment in these approaches. However, gloss annotations are not easy to acquire since they require expertise in sign languages~\cite{cihan2018neural}. In contrast, bootstrapping models directly learn to translate from video inputs to natural language sentences without gloss annotations. These models extend easily to a wider range of sign language resources, and have recently attracted great research interests. This paper also investigates bootstrapping methods and aims to minimize the translation accuracy gap between these two approaches by learning more expressive sign features. Sign gestures are the minimal units that preserve semantics in sign language videos. However, because of motion blurs, fine-grained gestural details, and the transitions between different sign gestures, inferring boundaries between sign gestures is difficult. Thus, current approaches~\cite{cihan2018neural,ko2019neural} extract sign features in a frame-wise fashion. By doing so, only spatial appearance features are captured while neglecting the temporal dependencies between sign gestures. However, temporal information is helpful in distinguishing different signs when similar body poses appear, and therefore we expect that this information to be useful in SLT models. In this paper, we propose a Temporal Semantic Pyramid Network (TSPNet) to learn features from video segments instead of single frames. Particularly, we aim to learn sign video representations that encode both spatial appearance and temporal dynamics. However, obtaining accurate gesture segments from a continuous sign video is difficult, while noisy segments bring substantial ambiguity for feature learning. Here, we observe two important factors impacting the semantics of sign segments. First, sign video semantics are coherent, implying that segments that are temporally close share consistent semantics locally. Second, the semantics of sign gestures are context-dependent. Namely, non-local information is helpful to disambiguate the semantics of local gestures. Motivated by these, we divide each video into segments of different granularities. Our proposed TSPNet then exploits the semantic consistency among them to further enhance sign representations. To be specific, after organizing multiple video segments of different granularities in a hierarchy, our TSPNet enforces local semantic consistency by aggregating features of segments in each \emph{semantic neighborhood} using an inter-scale attention. When tackling local ambiguity caused by imprecise segmentation, we develop an intra-scale attention to re-weight the local gesture features along the whole video sequence. By learning features from sign segments in a hierarchical approach, our TSPNet captures temporal information in sign gestures thus producing more discriminative sign video features. As a result of stronger feature semantics, we ease the difficulty in constructing mappings between sign videos and natural language sentences, thus improving the translation results. Our model significantly improves the translation quality on the largest public sign language translation dataset RWTH-PHOENIX-WEATHER-2014T, increasing the BLEU score from 9.58~\cite{cihan2018neural} to 13.41 and ROUGE score from 31.80~\cite{cihan2018neural} to 34.96, greatly relaxing the constraint on expensive gloss annotations for sign language translation models. \section{Related Work} \textbf{Sign Word Recognition.}~~Most sign language works focus on word-level sign language recognition (WSLR), aiming to recognize a single gesture from an input video~\cite{ding2009modelling,cooper2012sign,joze2018ms,min2019flickernet,min2020efficient,li2020word,li2020transferring,li2020sth}. Although many efforts have been devoted to WSLR, few works investigate the connections between WSLR and SLT, thus hindering the usage of WSLR models in practice. Earlier WSLR works~\cite{martinez2002purdue,ding2009modelling,cooper2012sign,Pigou_2017_ICCV} conduct studies on constrained subsets of vocabulary, resulting in less generalizable features. The recent research outcomes~\cite{li2020transferring} show that large-scale WLSR datasets~\cite{joze2018ms,li2020word} facilitate the generalization ability of sign feature learning. Motivated by this, we make the first attempt to apply the knowledge of WLSR models to the SLT task by reusing WLSR backbones to extract video features. Interestingly, our experiments indicate that an American Sign Language (ASL) WLSR backbone network is even effective for unseen sign languages, such as~German Sign Language (GSL). \textbf{Sign Language Translation.}~~A major challenge in sign language translation is the alignment between sign gestures and words of a natural language. One solution is to manually provide gloss annotations for each gesture in a video as aforementioned. However, glosses often require sign language expertise to annotate. Thus, they are expensive to label and not always available. Cihan~\textit{et al.}~\cite{cihan2018neural} propose a sign2text (S2T) model to predict translations directly from sign videos without glosses, which is referred to as a bootstrapping approach. % In particular, their models learn video features in a frame-wise manner. Since sign gestures span over multiple continuous frames, their approach overlooks the temporal dependencies in sign gestures. Different from their work, we propose to learn video features from segments, and model both spatial appearance and temporal dynamics of sign gestures simultaneously. Our feature learning method exploits local and non-local temporal structure in a hierarchical way to learn discriminative sign video representations while counteracting the effect of inaccurate sign gesture segmentation. \textbf{Neural Machine Translation (NMT).}~~The NMT task aims to translate one natural language to another. Most NMT models follow an encoder-decoder paradigm. Earlier works use RNN to model temporal semantics~\cite{kalchbrenner2013recurrent, sutskever2014sequence, cho2014learning}. Later, attention mechanisms are adopted to deal with long-term dependencies~\cite{bahdanau2014neural,luong2015effective}. Instead of RNNs, recent Transformer models~\cite{vaswani2017attention,devlin2018bert} fully rely on attention and feed-forward layers for sequence modeling. They obtain a large improvement in both translation quality and efficiency. In our work, we develop a novel encoder architecture in order to fully exploit the local and non-local semantics in sign videos, while reusing Transformer decoder to produce translations in natural language. \section{Temporal Semantic Pyramid Network} Our TSPNet employs an encoder-decoder architecture. The encoder learns discriminative sign video representations by exploiting the semantic hierarchical structure among video segments. The output of the encoder is fed to a Transformer decoder to acquire the translation. In this section, we first describe our proposed multi-scale segment representation for sign videos. Then we introduce the proposed hierarchical feature learning method. To focus on our main contributions, we omit the detailed decoder architecture and refer readers to~\cite{vaswani2017attention} for reference. \subsection{Multi-scale Segment Representation}\label{sec:multiscale} Previous SLT approaches~\cite{cihan2018neural,ko2019neural} learn video features in a frame-wise manner. Since a sign gesture usually lasts for around half a second ($\sim$12 frames)~\cite{buehler2009learning}, these features from static images neglect the temporal semantics of gestures. Different from their approaches, we develop a segment representation for sign videos, and aim to learn both spatial and temporal semantics of sign gestures. However, as aforementioned it is difficult to obtain accurate sign gesture boundaries. To alleviate the influence of imprecise sign video segmentation, we exploit the semantic consistency among segments of different granularities in a hierarchy. Specifically, we employ a sliding window approach to create video segments with multiple window widths. \textbf{Windowing Segments.}~~Given a video of $N$ frames $\mathbf{x}=\{x_0,x_1,...,x_{N-1}\}$ with $x_i$ a video frame, a \emph{video segment} $\mathbf{x}_{m,\,n}$ is a subsequence of $\mathbf{x}$, denoted as $\{x_m,x_{m+1},...,x_{m+n-1}\}$. For a window width $w\in \mathbb{N}$ and a stride $s\in \mathbb{N}$, we define \emph{windowing segments} of $\mathbf{x}$ with width $w$ and stride $s$ as $\Phi(\mathbf{x},w,s)=\{\mathbf{x}_{ks,\,w}\mid 0\leq k <\lfloor\frac{N}{w}\rfloor\}$. Windowing segments evenly divide an input video into overlapping clips. However, since sign gestures in a video vary in length, it is hard to choose an appropriate window width: smaller segments tend to capture finer-grained gestures but provide weaker contextual semantics, while larger ones are inferior to capture short gesture semantics but provide stronger context knowledge. To make the most out of the segment representation, we introduce \emph{multi-scale segment representation} and complement the semantics of short and long segments with each other. Specifically, a multi-scale segment representation of video $\mathbf{x}$ is a set of windowing segments $\{\Phi(\mathbf{x},w_i,s_i)\mid 0\leq i<M\}$, where $M$, $w_i$, and $s_i$ denote the number of scales, a window width and a stride. In the following, we refer to the scales with short and long segments as small and large scales, respectively. Given the multi-scale segment representation of a video, we employ a 3D convolution network I3D~\cite{carreira2016human} to extract video features for each segment. In order to adapt our backbone network to sign language gestures, we further finetune I3D on two WSLR datasets~\cite{joze2018ms,li2020word}. \subsection{Hierarchical Video Feature Learning for Sign Language Translation}\label{sec:hier} Inaccurate sign video segmentation leads to substantial ambiguity in gesture semantics. As a result, straightforward combinations of multi-scale segments, such as pooling or concatenation, do not necessarily improve the overall translation results. To deal with the issue, we start from two key observations on the semantic structure of sign language videos, \textit{i.e.}~\emph{local consistency} and \emph{context dependency}. First, gestures in sign language videos continuously evolve. This implies that video semantics change coherently. Therefore, segments that are temporally close are expected to share consistent semantics. Second, similar sign gestures translate to different words according to the context~\cite{pfau2018syntax,padden2016interaction}, and non-local video information is important for resolving semantic ambiguity in the individual gestures especially when the video segmentation is noisy. Driven by these observations, we develop a hierarchical feature learning method that utilizes local temporal structure to enforce semantic consistency and non-local video context to reduce semantic ambiguity. % Figure \ref{fig:architecture} illustrates an overview of our TSPNet. For a given sign video, we first generate its multi-scale segment representation and extract features from our I3D network $\mathcal{G}_{\mathrm{I3D}}(\cdot)$. We also develop a \emph{Shared Positional Embedding} layer (Section~\ref{sec:spe}) to inform the positions of segments in a sequence. Next, we propose to learn semantically consistent representations by aggregating features in each local neighborhood (Section~\ref{sec:lsc}). Lastly, TSPNet collects all the aggregated features and uses them to provide non-local video context to resolve the ambiguity of local gestures (Section~\ref{sec:nls}). As an alternative, we also introduce a joint learning layer to consolidate the feature learning by utilizing local and non-local information simultaneously (Section~\ref{sec:joint}). For notational convenience, we denote the windowing segments at $i$-th scale $\Phi(\mathbf{x},w_i,s_i)$ as $\Phi_i$, and its $k$-th segment $\mathbf{x}_{ks_i,w_i}$ as $\phi_{i,k}$. We use $\phi_{i,k}^{f}=\mathcal{G}_{\mathrm{I3D}}(\phi_{i,k})\in\mathbb{R}^{D}$ to represent the feature of the segment $\phi_{i,k}$ from the backbone, with $D$ the feature dimension. \subsubsection{Shared Positional Encoding}\label{sec:spe} Similar to words in spoken languages, the position of a sign gesture in the whole video sequence is important for interpretation. Inspired by recent works on sequence modeling~\cite{vaswani2017attention}, we inject the position information to video segments by representing position indices in an embedding space. Specifically, we learn a function $\mathcal{G}_{\mathrm{spe}}(\cdot)$ that maps each position index into an embedding with the same length of the segment feature. Such \emph{positional embeddings} are then added to the segment features at the corresponding position in each scale, resulting in {position-informed segment representation} $\widehat{\phi}_{i,k}^{f}=\phi_{i,k}^{f}+\mathcal{G}_{\mathrm{spe}}(k)$ We pad each video by repeating the last frame to ensure the number of segments in each scale is equal. As a result, we have the same number of position indices in each scale. This allows us to share the weights of $\mathcal{G}_{\mathrm{spe}}(\cdot)$ across all the scales. By sharing weights of $\mathcal{G}_{\mathrm{spe}}(\cdot)$, we reduce the number of model parameters, especially when the number of segments is large, thus benefiting the training efficiency and alleviating overfitting when data is limited. The output of the shared positional embedding layer is the position-informed video representation in $M$ scales, \textit{i.e.}~$\{\widehat{\Phi}^{f}_0,\widehat{\Phi}^{f}_1,...,\widehat{\Phi}^{f}_{M-1}\}$, where each scale has $L$ segment features $\widehat{\Phi}^{f}_i=\{\widehat{\phi}^{f}_{i,0},\widehat{\phi}^{f}_{i,1},...,\widehat{\phi}^{f}_{i,L-1}\}$. \subsubsection{Enforcing Local Semantic Consistency}\label{sec:lsc} Taking advantage of the multi-scale segment representation, we tackle the issue of imperfect video segmentation by complementing smaller segments with larger but semantically relevant ones. This is achieved by an \emph{inter-scale attention-based aggregation} of segments within \emph{surrounding neighborhoods}. A surrounding neighborhood consists of features of one \emph{pivot segment} (see Figure~\ref{fig:attn}) from the smallest scale $\widehat{\Phi}_0^f$, and features of multiple \emph{neighbor segments} from larger scales. Specifically, for each pivot segment, we construct its surrounding neighborhood by including segments from larger scales if their frames superset those of the pivot segment. \textbf{Surrounding Neighborhood.}~~Given position-informed video representation $\{\widehat{\Phi}^{f}_0,\widehat{\Phi}^{f}_1,...,\widehat{\Phi}^{f}_{M-1}\}$, with window widths arranged in an ascending order $w_0<w_1<...<w_{M-1}$, we name the feature of a pivot segment, $\widehat{\phi}^{f}\in\widehat{\Phi}_0^{f}$, as a \emph{pivot feature}. We define the \emph{surrounding neighborhood} of a pivot feature $\widehat{\phi}^{f}$ as a set $\mathcal{N}_{\widehat{\phi}^{f}} = {\widehat{\phi}^{f}}\cup\{\widehat{\psi}^{f}\mid \widehat{\psi}^{f}\in\bigcup_{i=1}^{M-1} \widehat{\Phi}_i^{f},\,{\phi\subset \psi}\}$, with $\widehat{\phi}^{f}$, $\widehat{\psi}^{f}$ the position-informed representation of segments $\phi$ and $\psi$, respectively. Surrounding neighborhood imposes a containment relation between a pivot and its neighbors. As a result, we ensure gestures appearing in the pivot segment are also included in the neighbors. In this way, we use neighbors to provide more contextual clues for the pivot, and encourage the model to learn an aggregated feature that best represents the local temporal region. \begin{figure}[t] \centering \includegraphics[width=0.95\linewidth]{figs/illustration.pdf} \caption{A surrounding neighborhood consists of features of a pivot segment and neighboring segments from multiple scales. Here we show 4 segments with the highest inter-scale attention scores. From the 26-th to 37-th frame, the GSL sign is the word \textbf{süden} (south).} \label{fig:attn} \vspace{-2mm} \end{figure} \textbf{Inter-scale Attention Aggregation.}~~Given position-informed video features $\{\widehat{\Phi}_0^{f},\widehat{\Phi}_1^{f},...,\widehat{\Phi}_{M-1}^{f}\}$, our hierarchical feature learning method first enforces local semantic consistency to compensate for the effect of inaccurate video segmentation. As Figure~\ref{fig:attn} shows, longer segments in the neighborhood capture more transitional gestures while shorter segments focus on fine-grained movements, both of which are helpful to recognize sign gestures in the local region. Therefore, for each pivot feature $\widehat{\Phi}_0^{f}$, we retrieve its surrounding neighbors and aggregate them using an \emph{inter-scale attention}. Specifically, since segments of different scales capture different semantic aspects of the gesture, they may not reside in the same embedding space. In this regard, we first apply a linear mapping $\mathbf{W}_g\in\mathbb{R}^{D^{\prime}\times D}$ to their features and map them into a shared space in $\mathbb{R}^{D^\prime}$. We then perform scaled dot-product attention to aggregate neighbor features into the pivot feature $\widehat{\phi}_{0,k}^f\in\widehat{\Phi}_{0}^{f}$, \begin{gather} \mathcal{Z}_k = [\mathbf{W}_g z_0, \mathbf{W}_g{z_1},...,\mathbf{W}_gz_{P-1}]^T, \;\text{where }\,z_{j}\in \mathcal{N}_{\widehat{{\phi}}^{f}_{0,k}},\,P=\|\mathcal{N}_{\widehat{\phi}^{f}_{0,k}}\| \\ c_k = \mathcal{G}_{\mathrm{attn}}(\mathbf{W}_g\widehat{\phi}^{f}_{0,k},\mathcal{Z}_k,\mathcal{Z}_k), \end{gather} where $\mathcal{G}_{\mathrm{attn}}(\cdot)$ is the scaled dot-product attention $\mathcal{G}_{\mathrm{attn}}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \mathrm{softmax}(\mathbf{Q}\mathbf{K}^T/\sqrt{d})\mathbf{V}$. $\mathcal{G}_{\mathrm{attn}}(\cdot)$ measures the correlation between $\mathbf{Q}$, $\mathbf{K}$ and uses it to re-weight $\mathbf{V}$; with $d$ the dimension of vectors in $\mathbf{K}$. The scaling factor $\sqrt d$ handles the effect of growing magnitude of dot-product with larger $d$~\cite{vaswani2017attention}. In order to learn more expressive features, we add two linear layers $\mathbf{W}_{1}\in\mathbb{R}^{D\times D^{\prime}},\mathbf{W}_{2}\in\mathbb{R}^{D\times D}$ with a $\mathrm{GELU}$ activation~\cite{hendrycks2016gaussian} in between as follows, \begin{equation}\label{eq:ffn} h_k = \mathbf{W}_{2}\cdot\mathrm{GELU}(\mathbf{W}_{1}c_k + b_{1}) + b_{2}, \end{equation} where $b_{1}$ and $b_{2}\in \mathbb{R}^{D}$ are biases of the corresponding fully-connected layers. Each $h_k$ encodes the aggregated semantics of segments across all the scales, thus providing a locally consistent representation of the sign gestures in the temporal region. \subsubsection{Non-local Semantic Disambiguation}\label{sec:nls} The interpretation of individual sign language gestures depends on the sentence-level context. First, the sign gesture of a word is usually a composition of two or even more ``meta-signs''. For example, the word ``driver'' requires to perform signs of ``car'' and ``person'' in order~\cite{pfau2018syntax}. The sign of ``person'' may translate to ``teacher'' or ``student'' depending on the accompanying word. Therefore, semantics for these signs are clarified only in the presence of context information. Second, there exist quite a few similar sign gestures~\cite{li2020word}. For instance, signs of ``wish'' and ``hungry'' are very similar and are hardly distinguishable without the context. Due to the imprecise gesture segments, these ambiguities become even more severe. It is thereby important for an SLT model to consider non-local sentence information in order to resolve the semantic ambiguity. Hence, we propose to model non-local video context by an intra-scale attention over the sequence of enriched pivot features. \textbf{Intra-scale Attention Aggregation.}~~After we aggregate multi-scale features into pivots, we design an intra-scale attention which takes $\mathbf{h}=[h_0,h_1,...,h_{L-1}]^T$, $h_k\in\mathbb{R}^{D}$ as input, in order to enhance features across all the local regions. This is achieved by a self-attention operation on the aggregated local features,~\textit{i.e.}~$\mathbf{e} = \mathcal{G}_{\mathrm{attn}}(\mathbf{W}_{e}\mathbf{h},\mathbf{W}_{e}\mathbf{h},\mathbf{W}_{e}\mathbf{h})$, where $\mathbf{W}_{e}\in\mathbb{R}^{D^{\prime\prime}\times D}$ and $D^{\prime\prime}$ denotes the dimension of the hidden embedding space. Similar to the inter-scale attention, the self-attention layer is followed by two fully-connected layers for feature transformation, and then we acquire the output, namely $\mathbf{o}\in\mathbb{R}^{D}$. We feed the output into a Transformer decoder for translation. \subsubsection{Joint Learning of Local and Non-local Video Semantics}\label{sec:joint} \vspace{-0.5em} In the previous sections, the intra-scale attention follows sequentially the inter-scale attention. Therefore, the model does not have knowledge of non-local video context when enforcing local semantic consistency. This is not ideal when the non-local context is helpful for recognizing local sign gestures and easing the noisy segmentation issue. As an alternative, we propose to jointly learn local and non-local video semantics so that the two information sources interact thoroughly. In this way, non-local information helps to better recognize local gestures. In the meanwhile, enhanced local gesture semantics contribute to resolve ambiguity in turn. For this purpose, we include all the pivot segments into each surrounding neighborhood, leading to \emph{extended surrounding neighborhood}. \textbf{Extended Surrounding Neighborhood.}~~For segment representation $\{\widehat{\Phi}^{f}_0,\widehat{\Phi}^{f}_1,...,\widehat{\Phi}^{f}_{M-1}\}$ of an input video, whose window widths are arranged in an ascending order $w_0<w_1<...<w_{M-1}$. An \emph{extended surrounding neighborhood} of a pivot feature $\widehat{\phi}^{f}$ is a set $\mathcal{N}_{\widehat{\phi}^{f}}^{*} = \mathcal{N}_{\widehat{\phi}^f}\cup \widehat{\Phi}_0^f$. As an extended surrounding neighborhood includes semantically relevant multi-scale segments and all the pivot segments, we aggregate to learn both local and non-local sign video features, as follows, \begin{gather} \mathcal{Z}^{*}_k = [\mathbf{W}_c z_0^{*}, \mathbf{W}_cz_1^{*},...,\mathbf{W}_cz_{Q-1}^{*}]^T\;\text{where}~\,z_{j>0}^{*}\in \mathcal{N}^{*}_{\widehat{\phi}^f_{0,k}},\, Q=\|\mathcal{N}^{*}_{\widehat{\phi}^f_{0,k}}\|, \\ c^{*}_k = \mathcal{G}_{\mathrm{attn}}(\mathcal{Z}_k^{*},\mathcal{Z}_k^{*},\mathcal{Z}_k^{*}). \vspace{-1em} \end{gather} In this way, we bring forward the non-local video context and encourage models to jointly learn to recognize sign gestures locally and mitigate the semantic ambiguity due to the inaccurate video segmentation. We eventually pass $\mathbf{c}^{*}=[c^*_0,c^*_1,...,c^*_{L-1}]^T$ to two fully-connected layers to acquire the encoder output, which later passes into the Transformer decoder for generating the translation. \section{Experiments} \vspace{-0.5em} \label{experiments} \subsection{Experiment Setup and Implementation Details} \vspace{-0.5em} \textbf{Dataset.}~~We evaluate TSPNet on RWTH-PHOENIX-Weather 2014T (RPWT) dataset~\cite{cihan2018neural}. It is the \emph{only} publicly available standard SLT dataset that is used for large-scale training and inference. We follow the official RPWT data partition protocol, where $7096$, $519$, $642$ videos are used for training, validation and testing sets, respectively. These samples are performed by nine different signers in German Sign Language (GSL) and the translations in German are also provided. RPWT dataset contains a diverse vocabulary of around $3$k German words. This distinguishes SLT from most vision-and-language tasks that usually have a limited vocabulary and simple sentence structure~\cite{antol2015vqa,anderson2018bottom}. \textbf{Metrics.}~~We adopt BLEU~\cite{papineni2002bleu} and ROUGE-L~\cite{lin2004automatic} scores, two commonly used machine translation metrics, for evaluation. BLEU-$n$ measures the precision of translation \emph{up to} $n$-grams. For instance, BLEU-$4$ summarizes precision scores of 1, 2, 3 and 4-grams. We use ROUGE-L that measures the F1 score based on the longest common sub-sequences between predictions and ground-truth translations. In general, both metrics are expected to be significantly lower than $100$, as there are multiple valid translations of the same meaning in natural language. This phenomenon, however, is not well quantified by existing translation metrics. \textbf{Implementation and Optimization.}~~We implement the proposed TSPNet using \textsc{Fairseq}~\cite{ott2019fairseq} framework in \textsc{PyTorch}~\cite{NEURIPS2019_9015}. Since a sign gesture on average lasts around half a second ($\sim$12 frames)~\cite{buehler2009learning}, we determine the minimal segment width to be 8 and enlarge it by $\sqrt{2}$ to another two scales, \textit{i.e.}, 12 and 16 frame segments. In each scale, we apply a stride of 2 frames to reduce the feature sequence lengths while keeping the most semantic information. In order to extract video features, we start with a pretrained I3D networks on Kinetics~\cite{carreira2017quo}, and then finetune it on two WSLR datasets~\cite{joze2018ms,li2020word} in ASL to adapt to sign gesture videos. To represent texts in the feature space, we adopt \textsc{SentencePiece}~\cite{kudo2018sentencepiece} German subword embedding~\cite{heinzerling2018bpemb}, which are based on character units to handle low-frequency words. We optimize TSPNet using Adam optimizer~\cite{kingma2014adam} with a cross-entropy loss as in~\cite{vaswani2017attention,sennrich2015improving}. We set an initial learning rate to $10^{-4}$ and a weight decay to $10^{-4}$. We train our networks for $200$ epochs, which is sufficient for all the models to converge. \vspace{-0.5em} \subsection{Comparisons with the State-of-the-art} \vspace{-0.5em} \input{tables/main_results} \textbf{Competing Methods.}~~We compare our TSPNet with two bootstrapping SLT methods. (i) \emph{Conv2d-RNN}~\cite{cihan2018neural} achieves the \emph{state-of-the-art} performance on RPWT dataset. It extracts features using AlexNet~\cite{krizhevsky2012imagenet} and employs GRU-based~\cite{chung2014empirical} encoder-decoder architecture for sequence modeling. It also exploits multiple attention variants on top of recurrent units~\cite{bahdanau2014neural,luong2015effective}. We also conduct comparisons with those attention based variants. (ii)~\emph{TSPNet-Single}: in this baseline, we feed segments from only a single scale into our TSPNet. With merely single-scale feature used, it only applies intra-scale attention aggregation, which is equivalent to vanilla self-attention. As a result, this baseline degenerates to a Transformer model. \textbf{Quantitative Comparison.}~~We report translation results of our TSPNet and the competing models in Table~\ref{tab:perfs}. The row of TSPNet-Sequential refers to the setting in Section~\ref{sec:lsc} and Section~\ref{sec:nls}, where we apply inter- and intra-scale attentions sequentially. TSPNet-Joint refers to the setting in Section~\ref{sec:joint}, where we enhance local and non-local video semantics by jointly modeling them. As indicated in Table~\ref{tab:perfs}, both settings outperform the state-of-the-art SLT model, Conv2d-RNN, by a large margin, with relative improvements on BLEU-4 score by $39.80\%$ ($9.58 \rightarrow13.41$) and on ROUGE-L by $9.94\%$ ($31.80 \rightarrow34.96$). Benefiting from our proposed sign segment video representation, our features encode not only spatial appearance information but also the temporal information of sign gestures, and thus is more discriminative. Compared to TSPNet-Single, the multi-scale settings improve SLT performance on all metrics. This shows the effectiveness of our hierarchical feature learning. In addition, TSPNet-Joint achieves superior performance to TSPNet-Sequential. This reflects that including non-local video context is beneficial to resolve local ambiguity caused by imprecise gesture segments. Compared with previous bootstrapping approaches, TSPNet significantly narrows the performance gap between bootstrapping approaches and two-staged ones. Computationally, it costs around two hours to train a TSPNet-Joint model on a single NVIDIA V100 GPU, excluding the time for the one-off offline visual feature extraction. \textbf{Qualitative Comparison.}~~Table~\ref{tbl:trans-exp} shows two example translations produced by TSPNet and the state-of-the-art model, Conv2d-RNN. In the first example, TSPNet produces a very accurate translation while Conv2d-RNN fails to interpret the original meanings. In the second example, the translation from our model retains the meaning of the sign by using the synonym of the word ``rain'', (\textit{i.e.}, ``shower''), while Conv2d-RNN does not capture the correct intent. However, this difference is not fully reflected on the adopted metrics. More results are provided in the supplementary material. \input{tables/translation_example} \input{tables/scales} \vspace{-0.5em} \subsection{Model Analysis and Discussions} \vspace{-0.5em} In this section, we investigate the effects of different components and design choices of TSPNet-Joint, our best model, on the translation performance. \textbf{Multi-scale Segment Representation.}~~We first study the impacts of feature in different scales. As seen in Table~\ref{tab:mullv}, the performance of our model increases as we progressively incorporate multi-scale features. This demonstrates that learning sign representations from hierarchical features mitigates the inaccurate video segment issue. When only single-scale features are exploited, our TSPNet-Joint model degenerates to the Transformer model. We notice that the inclusion of segments with a width $16$ improves the model most. This is also consistent with the finding that the $16$-frame segments offer the most expressive features in a single-scale model, as indicated in Table~\ref{tab:perfs}. However, by incorporating segments of larger widths (\textit{e.g.}, $24$ frames), we observe a slight performance drop. This is because $24$ frame segments (around 1 second) usually contain more than one sign gesture, where local semantic consistency may not hold. \textbf{Hierarchical Feature Learning.}~~To investigate the effectiveness of our hierarchical feature learning method, we compare our method with three aggregation methods that do not fully consider semantic relevance among segments. (1) \emph{position-wise pooling}: different from Section~\ref{sec:lsc}, we fuse features at the same temporal position across scales. Specifically, we first encode features on each scale using a separate encoder, and then apply a position-wise max-pooling operation over multi-scale segment features. (2) \emph{position-wise FC}: we first concatenate position-wise features and then employ two fully-connected layers for aggregating features. (3) \emph{nonrestrictive attention}: unlike Section~\ref{sec:nls}, this method allows each pivot to attend to all the segments on different scales to verify the importance of enforcing local consistency. As Table~\ref{tab:mullv} shows, non-structural methods fail to utilize the multi-scale segments. On the contrary, all three settings result in worse translation quality TSPNet-Single (16). This signifies the role of semantic structures when combining multi-scale segment features. \textbf{Other Design Choices.}~~(i) Without finetuning the I3D networks on the WLSR datasets, the best BLEU-4 score drops to $11.23$. This shows our backbone features are generalizable to even unseen sign languages (\textit{e.g.},~GSL). (ii) When not sharing weights but learning a separate position embedding layer for each scale, we observe a slight drop of $0.08$ in BLEU-4 compared to TSPNet-Joint. When we share positioning embedding layer weights, we not only reduce the model parameters but also further avoid overfitting. (iii) As indicated by TSPNet-Single (8), (12) results, simply utilizing a Transformer encoder does not achieve better performance than~\cite{cihan2018neural}. This implies that the performance gain mainly comes from the proposed hierarchical feature learning method. For the concern of training efficiency, recurrent operations are rather time-consuming (up to two orders of magnitude more training time in our case). Thus, we opt to avoid using recurrent units in our model. Additionally, TSPNet-Single (16) achieves better results than \cite{cihan2018neural}. This shows even with a proper uniform segmentation, our segment representation is effective in capturing temporal semantics of signs. \textbf{Limitations and Discussions.}~~Although the proposed hierarchical feature learning method proves effective in modeling sign language videos, we notice several limitations of our model. For example, low-frequency words such as city names are very challenging to translate. In addition, facial expressions typically reflect the extent of signs, e.g. shower \emph{versus} rain storm, which are not explicitly modeled in our approach. We further note that the work~\cite{Camgoz_2020_CVPR} achieves 20.17 BLEU-4 score when reusing the visual backbone networks from~\cite{koller2019weakly}, which is reliant on the gloss annotations. In this regard, our proposed method greatly eases the requirements of expensive annotations, thus having the potential to learn sign language translation models directly from natural language sources, e.g. subtitled television footage. We therefore plan to resolve the aforementioned issues and further mitigate the performance gap between gloss-free and gloss-reliant approaches as future works. \section{Conclusion} \vspace{-1em} In this paper, we presented a Temporal Semantic Pyramid Network (TSPNet) for video sign language translation. To address the unavailability of sign gesture boundaries, TSPNet exploits semantic relevance of multi-scale video segments for learning sign video features, thus mitigating the issue of inaccurate video segmentation. In particular, TSPNet introduces a novel hierarchical feature learning procedure by taking advantage of inter- and intra-scale attention mechanism to learn features from nosily segmented video clips. As a result, the model learns more expressive sign video features. Experiments demonstrate that our method outperforms previous bootstrapping models by a large margin and significantly relaxes the requirement on expensive gloss annotations in video sign language translation. \section*{Acknowledgement} HL's research is funded in part by the ARC Centre of Excellence for Robotics Vision (CE140100016), ARC-Discovery (DP 190102261) and ARC-LIEF (190100080) grants. CX receives research support from ANU and Data61/CSIRO Ph.D. scholarship. We gratefully acknowledge the GPUs donated by NVIDIA Corporation, and thank all the anonymous reviewers and ACs for their constructive comments. \section*{Broader Impact} As of the year 2020, 466 million people worldwide, one in every ten people, has disabling hearing loss. And by the year of 2050, it is estimated that this number will grow to over 900 million~\cite{whowebsite}. Assisting deaf and hard-of-hearing people to participate fully and feel entirely included in our society is critical and can be facilitated by maximizing their ability to communicate with others in sign languages, thereby minimizing the impact of disability and disadvantage on performance. Communication difficulties experienced by deaf and hard-of-hearing people may lead to unwelcome feelings of isolation, frustration and other mental health issues. Their global cost, including the loss of productivity and deaf service support packages, is US\$ 750 billion per annum in the healthcare expenditure alone~\cite{whowebsite}. The technique developed in this work contributes to the design of automated sign language interpretation systems. Successful applications of such communication technologies would facilitate access and inclusion of all community members. Our work also promotes the public awareness of people living with hearing or other disabilities, who are commonly under-representative in social activities. With more research works on automated sign language interpretation, our ultimate goal is to encourage equitable distribution of health, education, and economic resources in the society. Failure in translation leads to potential miscommunication. However, achieving highly-accurate automated translation systems that are trustworthy even in life-critical emergency and health care situations requires further studies and regulation. In scenarios of this kind, automated sign language translators are recommended to serve as auxiliary communication tools, rather an alternative to human interpreters. Moreover, RPWT dataset was sourced from TV weather forecasting, consequently, is biased towards this genre. Hence, its applicability to real-life use may be limited. Despite this linguistic limitation, RPWT remains the only existing large-scale dataset for sign language translation; this under-resourced area deserves more attention. Both datasets and models ought to be developed. \subsection{Graph Attention Networks.}\label{sec:conn} We remark that the attention operation in the \emph{Coupling layer} is connected with Graph Attention Networks (GAT)~\cite{velivckovic2017graph}. In particular, the multi-scale segment video representation induces a graph structure consisting each segment as a node. With semantic neighborhood, we impose specific assumptions on the semantic connectivity, \textit{i.e.}~edges, between nodes. By introducing these inductive biases, we guide the model to exploit local and global semantics in an efficient and complementary way. In contrast, besides the distinct implementation of attention mechanism, our work differs from~\cite{velivckovic2017graph} in that we emphasize on the construction of hierarchical segment representation, which aims to capture sign gestures across frames. On top of this, we propose to utilize semantic relevance to provide effective structural learning priors, while in most graph learning methods these structural information is directly available as part of the input, \textit{e.g.}~citing relation in Cora citation networks~\cite{mccallum2000automating}. \section{Submission of papers to NeurIPS 2020} \medskip \small
{'timestamp': '2020-10-13T02:29:01', 'yymm': '2010', 'arxiv_id': '2010.05468', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05468'}
arxiv
\section{Introduction} \label{intro} Social media, which has achieved growing popularity in recent decades, provide the opportunity for people to share their ideas with an enormous number of users around the world. As a micro-blogging platform, Twitter allows its users to write short text messages regarding various issues ranging from politics, economy, and healthcare to routine tasks of people's daily lives. One such issue, the COVID-19 pandemic, has had a profound impact on people's social lives since the beginning of 2020. Determining and tracking health issues such as COVID-19 on Twitter would help governments and healthcare companies better handle the impact of those diseases on societies. Concretely, assembling tweets on this topic and analyzing them may result in invaluable information for those companies. From the healthcare perspective, crawling tweets related to COVID-19 as a pandemic issue might help in finding a remedy for it. As manual processing of such information is prohibitively expensive, automatic or semi-automatic methods are thus needed; however, assembling and distilling such data is a challenging task. Previous works have tackled this problem by streaming and grouping tweets into various categories by using supervised \cite{dehkharghani2014sentimental} or unsupervised \cite{cataldi2010emerging} methods. Unsupervised methods, however, could gain greater popularity. These methods collect streaming tweets in a time interval and assign them to clusters based on their topics. Clustering has been already used for topic detection in the literature. In stream data clustering, a two-phase task is accomplished. In the first phase, data are captured from a data stream; and in the second phase, clusters are created and (in this paper) re-organized to constitute denser clusters. The ultimate goal is to increase the intra-cluster similarities as well as to decrease the inter-cluster similarities. To tackle the aforementioned problem, we propose a novel, communicative, multi-agent, parallelizable text clustering approach for tweet clustering, experimented on the COVID-19 and the FA CUP datasets, which is described with greater details in Section \ref{proposedMethod}. The key aspect of this work is its multi-agent and communicative structure. The difference between this work and the existing ones is in the second phase (as mentioned above). In the communication step of the proposed approach, existing clusters may export data to, and/or import data from other clusters. At the same time, the proposed approach is also capable of distinguishing outlier data and excluding them from their current clusters. All these tasks can be (and have been) accomplished in a parallel setting. The contributions of the proposed approach can be summarized as follows. \begin{itemize} \item ComStreamClust updates clusters by detecting outliers and distributing them among other clusters, in a streaming, parallel, and multi-agent setting. This setting is being used for the first time in the literature on topic detection problems. \item The proposed approach could achieve promising results when applied to the FA CUP dataset. We applied our approach also to this dataset for the sake of fair comparison. Obtained results were as good as or superior to the existing approaches such as LDA, SFPM, and BNgram. \item ComStreamClust benefits from a state-of-the-art sentence embedding model, the LaBSE, for measuring the semantic similarity between tweets. \item A comprehensive experimental evaluation of the proposed approach on two datasets with different parameter values, such as the number of topics per time-slot, and the number of keywords per topic have been conducted. \end{itemize} \section{Related Work} \label{RW} Ibrahim et. al. \cite{ibrahim2018tools} divide the topic detection techniques into five groups: clustering, frequent pattern mining, Exemplar-based, matrix factorization, and probabilistic models. The current research falls into the clustering-based models. Stream clustering is a type of clustering, in which, data are continuously fed to a clustering system. Given this sequence of data, the goal is to group them in clusters, the elements of which are similar to each other but different from the elements of other clusters. In \cite{petkos2014two}, the authors propose a two-level clustering method based on document-pivot algorithm to detect topics in Twitter streaming data. Some previous work relies on word frequency for topic detection and topic categorization on Twitter data. Using the ``aging'' theory for modeling the term life-cycle has experimented in \cite{cataldi2010emerging}. In this work, Cataldi et.al., define a term as emerging, if it was rare in the past but frequent in a specified time-interval. The authors benefit from emerging terms to detect emergent topics. In \cite{dehkharghani2014sentimental} and \cite{dehkharghani2013automatically}, the authors propose approaches that detect topics in Twitter, based on their word frequency, and categorize tweets into sentiment classes. Unlike traditional clustering approaches that rely on a fixed set of input data, stream clustering assumes that input data are in a stream with an unknown number of usually unlabelled data. Along with the fast growth of social media such as Twitter, stream text clustering has gained growing popularity in recent decades. Several researchers have tackled this problem with different approaches. The proposed method in \cite{carnein2017stream} incrementally builds micro-clusters, which are later re-clustered to assemble final clusters. The idea of micro-clusters was earlier used in \cite{hahsler2016clustering}, in which, the first micro-cluster-based online clustering algorithm, so-called DBSCAN was introduced. Hasler and Bolanos in this work, took into account the density of area between the micro-clusters, for the first time in the literature. In another perspective, Fang et. al., \cite{fang2014detecting} categorize topic detection methods in Twitter into two main groups: traditional and new topic detection methods. In the traditional side, some research works \cite{guo2013lda} use an extension of LDA \cite{blei2003latent} for solving the topic detection problems. Some others tackle this problem by constructing a term co-occurrence network of keywords \cite{zhou2011hot} and single-pass clustering along with a new threshold method \cite{papka1998line}. Although traditional methods work well for long texts, they do not portray high performance on short texts such as tweets. Therefore, in new topic detection methods, traditional approaches have been extended to deal with new data types. In \cite{fang2014detecting}, the authors propose a new topic detection framework based on multi-view clustering. The Gradient Boosted Decision Trees is another method for detecting controversial events from Twitter which has been used in \cite{popescu2010detecting}. Computational cost is one of the major challenges in the real-time topic- or event-detection on Twitter. Hasan et. al. \cite{hasan2019real} deal with this issue by proposing an event-detection system called TwitterNews+ which utilizes inverted indices and an incremental clustering approach, with a low computational cost. Asgari et. al \cite{asgari2020COVID} propose a model based on the universal sentence encoder \cite{cer2018universal} and transformers \cite{vaswani2017attention} to detect main topics on Twitter regarding the COVID-19 pandemic. Early detection of bursty topics is one of the most challenging problems in this era. TopicSkech \cite{xie2016topicsketch} deals with this problem on Twitter. Similarly, PoliTwi \cite{rill2014politwi}, also has been proposed for early detection of emerging political events. There are several other approaches to topic detection on the text which use different methods such as Formal Concept Analysis \cite{cigarran2016step}, clustering based on n-grams, and named entity boosting \cite{tembhurnikar2015topic}, and combination of singular value decomposition and K-means clustering methods \cite{nur2015combination}. More information and related work on topic detection on Twitter can be found in \cite{atefeh2015survey,mottaghinia2020review}. Despite a good deal of research work proposed for topic detection on Twitter, none of them is communicative, multi-agent, and parallelizable at the same time. The proposed approach can improve its clusters by providing the communication ability for its clusters. \section{Proposed approach} \label{proposedMethod} Twitter streaming data is a sequence of data, in which, data-points appear during the time. The problem tackled in this paper can be formally defined as follows: Each data-point is assumed as a quadruple $(id, t, ts, s)$, such that \emph{id} is a unique value as the identification number; \emph{t} is the text with at most 280 characters; \emph{ts} is the timestamp of the tweet including its arrival date and time; \emph{s} is the subject of the tweet which is not known in advance. Once the subject \emph{s} is determined, the tweet can be assigned to one of the existing clusters. Having a set of topic clusters, the task is to assign a newly arrived tweet to one of the clusters. After this assignment, the attribute \emph{s} of the tweet will be initialized, which can be updated later. ComStreamClust consists of three main steps: (1) Data streaming, in which, data points, i.e. tweets, are fetched from Twitter streaming data, (2) Data assignment, where the newly arrived tweet is assigned to an existing or a new cluster, and (3) Data exchange, which is a communicative step to exchange data among clusters to build denser clusters. The initialization phase is not assumed as the main step because it is accomplished once at the beginning of the whole process. Different steps of the proposed approach are described in greater detail in their respective subsections. The proposed approach is illustrated in figure \ref{flowchart} as a flowchart. The reference implementation of the proposed approach is also released under the MIT license\footnote{The Python and Elixir imlemantation of the proposed approach is publicly available at \url{https://github.com/AliNajafi1998/ComStream}}. \begin{figure*}[t] \centering \caption{The proposed approach as a flowchart.} \includegraphics[width=12cm]{ComStream.jpg} \captionsetup{justification=centering} \label{flowchart} \end{figure*} \subsection{Initialization} \label{Initialization} The initialization phase receives and handles the first \emph{k} tweets; we set \emph{k} to \emph{10}. The first \emph{k} tweets are randomly assigned to one of the initial agents. This phase will be finished when all initial agents are filled. The initial number of agents, identified by the \emph{init-agents} parameter, and the initial capacity of these agents indicated by \emph{init-agent-cap} are respectively set to 5 and 2 for both datasets ($5*2=10$). In other words, the first ten tweets would be randomly assigned to five agents. \subsection{Data streaming} \label{datastream} In this step, data are fetched from a data stream, e.g. Twitter. Such data sources have unique characteristics, in contrast to batch data sources, access to the dataset is limited by time--the whole data do not exist in advance. In other words, the system receives one data point at a time. In this paper, two streaming data sources are used for topic detection: the COVID-19 dataset and the FA CUP dataset. These datasets have been explained in section \ref{dataset}. The streaming step fetches tweets from the data stream, and after passing a tweet through a preprocessing channel, assigns it to one of the agents (clusters). \subsubsection{Data preprocessing} \label{preprocessing} Because of the short length of tweets, Twitter users usually prefer to use informal language. Due to this informality, tweets should be first preprocessed to be prepared for further processing. In this phase, several subtasks are applied to the newly-arrived tweet before passing it to the next step (Data assignment). \begin{itemize} \item URL removal: In this subtask, hyperlinks to various webpages are removed, as they generally do not contribute to the topic. \item Hashtag tokenization: Hashtags are words or phrases starting with a '\#' character. Hashtags may contribute to the tweet's topic as they carry contextual information. A hashtag semantically links a tweet to all other tweets including it. As a hashtag usually consists of several words, in this subtask, it is separated into its constituting words. \item Mention removal: Twitter users might be mentioned in a tweet with an '@' character followed by their username. These names are also removed from tweets as they usually do not contain useful information for topic detection. \item Tweet cleaning: As explained above, Informal language is often preferred in Twitter, which tends to include digits or special characters such as ``[]()/!?.''. Such characters are also removed in this subtask. \item Tweet tokenization: Finally, the cleaned tweets are tokenized using the whitespace character. Bigrams and trigrams including a hyphen between words are left unchanged as they usually convey a non-compositional phrase, e.g., ``brother-in-law'', or ``chronicle-independent''. Moreover, all capital words are lowered. \end{itemize} \subsection{Data assignment} \label{dataassignment} In this step, the coordinator receives a tweet and assigns it to one of the existing clusters that is semantically the most similar to it. The coordinator is a component for monitoring the system and collaborating with agents (clusters). The similarity between a tweet and a cluster is measured by the similarity of topics covered by them. This similarity is being measured according to a state of the art sentence embedding model. More specifically, we first compute the sentence embedding vector of a given tweet based on the Language Agnostic Bert Sentence Embedding (LaBSE) model \cite{feng2020language}, which generates similar embeddings for bilingual or monolingual sentence pairs that are semantically similar. We then measure the cosine similarity of this vector with centroids of the existing clusters--the average sentence embedding vector of each cluster--to find the most similar cluster to the given tweet. The LaBSE \footnote{{https://tfhub.dev/google/LaBSE/1}} is a recently proposed multilingual sentence encoding model based on BERT \cite{devlin2018bert}, and its architecture is based on Bidirectional Dual-Encoder \cite{guo-etal-2018-effective} with Additive Margin Softmax \cite{ijcai2019-746}. It has been trained on 17 billion monolingual sentences and 6 billion bilingual sentence pairs. It is the state of the art model for measuring the semantic similarity between two documents/sentences, and can measure the semantic similarity of two sentences/documents even if they do not share any word. Moreover, this model takes the whole message conveyed by a tweet, instead of taking the constituting words of a tweet in isolation. Note that if the semantic distance of the newly arrived tweet from the most similar cluster to it is greater than a given threshold parameter, namely, \emph{assign radius}, a new cluster including only the new tweet will be generated. The cosine similarity measure in equation \ref{cosine} is used to compute the semantic similarity of two tweets, which are represented by two \emph{n}-dimensional vectors. $\vec {tw}$ and $\vec {cl}$ respectively represent the tweet and cluster vectors. \label{cosine} $cos(\vec {tw},\vec {cl}) = \frac{\vec {tw} \cdot \vec {cl}}{{|\vec {tw}||\vec {cl}|}}$ $ = \frac{\vec {tw}}{|\vec {tw}|} \cdot \frac{\vec {cl}}{|\vec {cl}|}$ $= \frac{\sum_{i \in tw \cap cl} {tw}_i {cl}_i}{\sqrt{\sum_{i = 1}^{|tw|}} {tw}_{i}^2 \sqrt{\sum_{i = 1}^{|cl|} {cl}_{i}^2}}$ To prevent overflow in agents, we use a sliding window method. This window, indicated by a parameter named \emph{slid-win-init}, is set to twenty-four hours, and 1 minute, respectively in the COVID-19 and the FA CUP datasets' evaluations. This parameter differs from the \emph{timeslot} parameter which indicates a time interval, after which, the output of the system is stored and evaluated. In other words, topics and their keywords are separately extracted for each day in the COVID-19 and each minute in the FA CUP datasets. After each timeslot, a constant number of topics and a constant number of keywords per topic are stored. These constant numbers are represented by two parameters: \emph{no-topics} and \emph{no-keywords}. The \emph{no-topics} parameter varies in different experiments, whereas the \emph{no-keywords} is set to 5 and 9, respectively in the COVID-19 and the FA CUP datasets. \subsection{Data exchange} \label{dataexchange} After assigning the tweets to existing clusters in the data assignment step, a multi-agent communication-based data exchange occurs periodically among agents under the supervision of the coordinator. This period is a parameter in our approach, named \emph{comm-int}. In this step, the coordinator redistributes outlier tweets among clusters to achieve higher cluster density. Concretely, in each timeslot, the agents determine their outlier tweets and return them back to the coordinator. A tweet is assumed an outlier in a cluster if its cosine similarity from the cluster centroid is lower than a given threshold. This threshold, named \emph{outlier-threshold} is another parameter, which is set to $0.78$ and $0.73$ respectively in the COVID-19 and the FA CUP datasets. Then, the coordinator redistributes these outliers among existing clusters (agents), again based on the cosine similarity. The intuition behind this communication is that due to the automatic update in cluster centroids, which is caused by the newly-added tweets, some tweets inside clusters gradually become an outlier. In other words, the topic carried by an outlier gradually gets away from the overall topic of the cluster including it. At the end of each communication phase, the weight of each agent is reduced by a parameter named \emph{agent-fading-rate}. After this update, if the weight of any agent is lower than a threshold, \emph{del-agent-weight}, it will be faded. This weight is incremented by each data point's arrival to an agent, but not decremented by each outlier's removal from that agent. As mentioned already, the proposed methodology includes several parameters, which have been initialized by the try-and-test method. The complete list of parameters, as well as their values separately for two datasets, are listed in Table \ref{table_parameters}. The proposed approach has two versions: ComStreamClust1 and ComStreamClust2. The difference between these two versions is in parameters assign-radius and outlier-threshold. The value of assign-radius and outlier-threshold are 0.25 and 0.27 in ComStreamClust1 and 0.27 and 0.29 in ComStreamClust2 respectively. \begin{table*}[t] \caption{The parameters used in the proposed methodology. cc, dp, ts, and kw respectively stand for cluster-center, data-point, time-slot and keyword. Values inside parantheses have been used in two versions of the proposed approach.} \centering \begin{tabular}{l l l l} \hline \bf Parameter name &\bf COVID-19&\bf FA CUP&\bf explanation \\ [0.5ex] \hline init-agents& 5 & 2 & initial number of agents\\ init-agent-cap& 5 & 2 & initial \# of dps per agents\\ timeslot & 24h& 1m & time-interval to store the output\\ comm-int & 1.5h& 1m & time-interval to repeat comm. phase\\ slid-win-int & 24h& 1m & time-interval for naming a dp is as old\\ assign-radius& 0.2 & (0.25,0.27) & max distance for assigning a dp to an agent\\ outlier-threshold& 0.22 & (0.27,0.29) & min dist. from cc for a dp to be an outlier\\ no-topics & 2-20& 2-20 &\# of topics stored in each ts\\ no-keywords& 5 & 9 &\# of kws per topic stored in each ts\\ agent-fading-rate& 0.5 & 0 &percentile of agents faded in comm. phase\\ del-agent-weight-threshold& 0.4 & 0 &weight threshold for deleting agents\\ \hline \end{tabular} \label{table_parameters} \end{table*} \section{Experimental Evaluation} \label{expeval} In this section, we evaluate the proposed approach on two datasets, the COVID-19 and the FA CUP. Evaluation metrics, ground-truth, datasets, and obtained results have been explained with details in the following subsections. {\bf Evaluation metrics:} We use topic recall, keyword recall, and keyword precision for evaluation. F-score is also used for keyword evaluation as the harmonic mean of precision and recall. These metrics are calculated according to equations \ref{prec} through \ref{fscore}. Keyword precision is the ratio of correctly extracted keywords of a topic over the total number of extracted keywords for that topic. Topic recall is the ratio of correctly extracted topics over the total number of topics. Keyword recall is the ratio of correctly extracted keywords of a topic over the total number of keywords of that topic. The correct topics and their keywords have been collected in a ground-truth set. Note that we did not use topic precision, because there exist hot topics in the datasets which might not be in the ground-truth set. For example, daily events such as the death of someone's cat might be extracted as a hot topic, where it is not relevant to any topic in the ground-truth. \begin{equation} \label{prec} \displaystyle P_{kw} = \frac{\textit{ \# of estimated kws for $T_i$}}{\textit{\# of kws for $T_i$ in ground-truth}} \end{equation} \begin{equation} \label{recall} \displaystyle R_{tp} = \frac{\textit{\# of correctly extracted topics}}{\textit{\# of topics in ground-truth}}\\ \end{equation} \begin{equation} \label{recallkw} \displaystyle R_{kw} = \frac{\textit{\# of correctly extracted kws for $T_i$}}{\textit{\# of kws for $T_i$ in ground-truth}} \end{equation} \begin{equation} \label{fscore} \displaystyle Fscore_{P,R} = \frac{2*P*R}{P+R} \end{equation} \textbf{Ground-truth:} The ground-truth data are available for the FA CUP dataset, which have been explained with details in \cite{aiello2013sensing}. However, to the best knowledge of the authors, there is no ground-truth publicly available for the COVID-19 dataset. To generate a ground-truth for this dataset, we manually extracted the hot topics and their associated keywords from online media and search engines, separately for each day from March 29 to April 30. We have made these ground-truth data publicly available \footnote{\url{https://www.kaggle.com/thelonecoder/labelled-1000k-covid19-dataset}}. \begin{figure*}[t] \includegraphics[width=\textwidth]{N_Tweet_COV.jpg} \captionsetup{justification=centering} \centering \caption{Daily distribution of COVID-19 tweets in a 31-day interval.} \label{NTweetCOV} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=\textwidth ]{N_Tweet_FACUP.jpg} \captionsetup{justification=centering} \caption{Daily distribution of the FA CUP tweets in a 13 timeslots including special events.} \label{NTweetFACUP} \end{figure*} \subsection{Dataset} \label{dataset} As already mentioned, two datasets have been used in this paper. The Football Association Challenge Cup, FA CUP, was compiled during a football game between Chelsea and Liverpool, on May 05, 2012, from 16:00:00 to 18:30:00. The data have been crawled using key hashtags such as the event name and the name of teams and key players. The set of hot topics in this dataset is comprised of 13 special times including the start and the end of the match, the goal times, penalizing the players, and so on. This dataset includes about 113 thousand English tweets already labeled in \cite{aiello2013sensing}. The COVID-19 dataset is a collection of tweets compiled from Twitter from March 29 to April 30, 2020. This dataset has been assembled by crawling tweets including the hashtag \#COVID19. The total number of tweets in this dataset is about 9 million but we randomly chose 1 million tweets and manually identified thirty topics in them as our groundtruth. We have made this subset publicly available for other researchers' use \footnote{\url{https://www.kaggle.com/thelonecoder/labelled-1000k-covid19-dataset}} The number of tweets in each timeslot for both datasets has been illustrated as a histogram in Figures \ref{NTweetCOV} and \ref{NTweetFACUP}. Both datasets have been automatically collected by using hashtags, therefore irrelevant (outlier) tweets might exist in them which would lead to challenges in topic detection. This issue was the reason for neglecting topic precision as an evaluation metric. \subsection{Results} The evaluation metrics include topic and keyword recall, keyword precision, and F-score (for keyword evaluation). We used micro-averaging for computing the final value of evaluation metrics both for the topic and keyword evaluation. We conducted several experiments, the results of which are portrayed in Figure \ref{TopicNo}. These results have been obtained when {topic-number-per-timeslot} is 2 to 20 (for both datasets) and {keyword-number-per-topic} is 5 for the covid-19 and 9 for the FA CUP datasets. The exact values of topic recalls have been also provided in Table \ref{table_results}. It can be concluded from this table and figure that a higher number of topics would result in a higher topic recall, especially in the COVID-19 dataset. The intuition behind the harsh slope of the line (from 0 to 3) in the COVID-19, is that the number of hot topics per timeslot ranges from 0 to 3, and therefore increasing the number of estimated hot topics would increase topic recall until 3, but after 3, due to the lower number of topics per timeslot in the ground-truth, the line rises with a lower slope. However, increasing this number does not affect other metrics (Keyword precision and recall) much, because having more topics would require estimating more topic keywords, whereas our estimation would not be always correct. \begin{table* \caption{Obtained results for both datasets by the proposed approach.} \begin{tabular}{ l l l l l l l l l l} \hline 2&4&6&8&10&12&14&16&18&20\\ \hline &&&&COVID-19&&&&&\\ {0.361}&{0.500}&{0.611}&0.667&0.667&0.722&{0.833}&{0.861}&{0.861}&{0.917}\\ \hline &&&&FA CUP&&&&&\\ 0.692&0.840&0.923&1&1&1&1&1&1&1\\ \hline \end{tabular} \label{table_results} \end{table*} \begin{figure*}[t] \includegraphics[width=\textwidth]{TopicNo.png} \captionsetup{justification=centering} \caption{TRec, KWRec and KWPrec for different number of topics per timeslot in the FA CUP (left) and COVID-19 (right) dataset.} \label{TopicNo} \end{figure*} Finally, we provide the t-distributed stochastic neighbor embedding (tSNE) diagrams for both datasets in a specific timeslot in Figure \ref{TSNE}. Each agent in this diagram represents a cluster including similar data-points, i.e., tweets sharing a topic. \begin{figure*}[t] \centering \includegraphics[width=\textwidth]{TSNE.png} \captionsetup{justification=centering} \caption{The t-distributed stochastic neighbor embedding (tSNE) diagrams for a specific timeslot in the FA CUP (a) and the COVID-19 (b) datasets.} \label{TSNE} \end{figure*} \subsection{Discussion and comparison} \label{discussin} We obtained different topic recall values for different values for topic-number-per-timeslot, which have been provided in Table \ref{table_comparison}. This table also compares the obtained values with other approaches applied to the FA CUP dataset for topic detection. The main reason for applying the proposed approach on the FA CUP dataset is fair comparison because the same set of data-points are used in the FACUP by different researchers; However, in the case of COVID-19, a different dataset has been used in each research work. Moreover, people usually do not make their dataset publicly available. As mentioned already, the difference between two versions of ComStreamClust is in two parameters, assign-radius and outlier-threshold. ComStreamClust1 with lower values for these parameters starts not very good but obtains the best result fast. On the other hand, ComStreamClust2 with higher values for these parameters starts good but its improvement speed is lower. The intuition behind this issue is that the lower radius causes higher number of agents, and higher number of agents would make them more specific. But when the radius is higher, lower number of agents with more generality would be generated. Several erroneous cases were causing lower topic recall in both datasets, such as the overshadowing phenomenon. In the FA CUP, for instance, a goal was achieved by Drogba in the 24th minute which is a hot topic in timeslot 24. There is another hot topic in the 25th minute that discusses passing the ball to Drogba before achieving the goal. The latter topic was overshadowed by the first one, i.e., the latter was lost in minute 25 among tweets issued in minute 24. \begin{table*}[t] \caption{The obtained results of the proposed approach and its comparison with other methods when applying on the FA CUP dataset with different topic numbers. TR stands for Topic Recall. The maximum value in each column is in bold.} \centering \begin{tabular}{l l l l l l l l l l l} \hline Method&TR@2&TR@4&TR@6&TR@8&TR@10&TR@12&TR@14&TR@16&TR@18&TR@20\\ \hline &&&&&FA CUP&&&&\\ Gfeat-P&0.000&0.308&0.308&0.375&0.375&0.375&0.375&0.375&0.375&0.375\\ LDA&0.692&0.692&0.840&0.840&0.923&0.923&0.840&0.840&0.840&0.750\\ BNgram&0.769&{\bf 0.923}&{\bf 0.923}&0.923&0.923&0.923&0.923&0.923&0.923&0.923\\ SFPM&0.615&0.840&0.840&{\bf 1}&{\bf 1}&{\bf 1}&{\bf 1}&{\bf 1}&{\bf 1}&{\bf 1}\\ Doc-P&0.769&0.840&{\bf 0.923}&0.923&{\bf 1}&{\bf 1}&{\bf 1}&{\bf 1}&{\bf 1}&{\bf 1}\\ ComStreamClust1&{0.692}&{ 0.840}&{\bf 0.923}&{\bf1}&{\bf1}&{\bf1}&{\bf 1}&{\bf 1}&{\bf 1}&{\bf 1}\\ ComStreamClust2&{\bf 0.840}&{\bf 0.923}&{\bf 0.923}&0.923&0.923&{0.923}&{\bf 1}&{\bf 1}&{\bf 1}&{\bf 1}\\ \hline \end{tabular} \label{table_comparison} \end{table*} {\bf Keyword analysis:} We tested the proposed approach with different values for the parameter, \emph{no-keywords} (per topic), and concluded that 5 and 9 keywords per topic respectively in the FACUP and COVID-19 datasets achieve the best results. A lower number of keywords would result in lower topic-recall due to detecting fewer topics, but higher topic precision. A greater number of keywords, on the other hand, would detect more topics causing higher topic recall and lower topic precision. At the end of all time-slots in each dataset, some keywords have been labeled as most frequent, which have been illustrated as boxplots in Figures \ref{boxkwfacup} and \ref{boxkwCOVID19}. \begin{figure*}[t] \centering \includegraphics[height=3in]{boxplot_FACUP.jpg} \captionsetup{justification=centering} \caption{The Boxplot of keywords in the COVID-19 dataset.} \label{boxkwfacup} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=5.5in]{boxplot_COVID.jpg} \captionsetup{justification=centering} \caption{The Boxplot of keywords in the COVID-19 dataset.} \label{boxkwCOVID19} \end{figure*} As can be seen in COVID-19's boxplot, the most frequent words are ``stay'', ``pandemic'', ``home'' and ``people'', which may imply that due to the COVID-19 pandemic, people suggest each other to ``stay at home''. We observed in this dataset that the majority of tweets include the hashtag \#StayAtHome. Note that obvious frequent keywords such as ``COVID19'', ``coronavirus'', ``corona'', and ``virus'' have been treated as stopwords, as they appear in almost all tweets. We chose a few sample tweets from each dataset, which include a hot topic in its timeslot. Table \ref{table_samples} lists these sample tweets. \begin{table*}[t] \caption{Sample tweets including hot topics for each dataset.} \centering \begin{tabular}{l l l} \hline Text&Date-Time&keywords\\ \hline COVID-19&&\\ \hline \#BREAKING The \#UK \#PrimeMinister @BorisJohnson has been&19:25:28&icu hospital\\ moved to \#ICU "\#BorisJohnson moved to intensive care after being &2020-04-06&Boris johnson\\admitted to hospital with \#coronavirus symptoms" \#COVID19 \\https://t.co/mq4gDedDGx\\ \\ It’s \#EarthDay2020. It’s ironic that the \#COVID19 crisis has made us think&03:18:01&earth change\\ more about how vulnerable we are on this fragile earth. Maybe now our&2020-04-22&climate\\ governments will rethink their intransigence on climate change action.\\ \hline FA CUP&&\\ \hline 44' Daniel Agger made a hard tackle to Mikel. And shown yellow card&17:01:34&mikel daniel\\ by the referee. \#FACup&May 05 2012&agger yellow card\\ \\ \o/ Yay Chelsea! RT @itvfootball: Congrats to \#CFC on beating \#LFC 2-1&18:09:52&cup chelsea\\ and winning the 2012 \#FACupFinal&May 05 2012&champions\\ \hline \end{tabular} \label{table_samples} \end{table*} {\bf Multi-agent setup:} The proposed approach is capable of being parallelized. In order to prove this claim, we implemented it in the elixir language \footnote{\url{https://elixir-lang.org/docs.html}} using a multi-processor system, after running the implemented system in python on a single-processor system. The cpu Specifications for this system is 4x i7 6700 HQ @3.8GHz and its RAM is 16 GB. We conducted this experiment to see if the proposed approach can be executed in a multi-agent system and also how much time can be saved in a parallel setting compared to the sequential case. More specifically, we used a multi-agent system including eight processors, each of which handles one cluster. If the number of clusters is more than eight (which is the case in some time intervals), the parallel system would transform to an eight-processor pipeline --the ninth and other clusters will be concurrently processed. The time intervals spent for the sequential and parallel cases are respectively 5 minutes and 14 seconds and 4 minutes and 40 seconds. Note that sequential processing in python takes the advantage of the optimal implementation of libraries such as numpy which drastically decreases the execution time, whereas elixir lacks such optimality. Every process in this language has to be executed in parallel; no sequential execution is allowed in it. In conclusion, due to the facts discussed above, the improvement in the execution time is not substantial. This improvement could be higher with higher-speed processors. \begin{table*}[t] \caption{Sample tweets turned to normal data-points from outlier.} \centering \begin{tabular}{l l l} \hline Tweet&Tweet assumed as outlier&Tweet assumed as normal\\ \hline COVID-19&&\\ \hline british prime minister boris &['boris', 'johnson', 'stay', 'pandemic', 'trump',&['boris', 'johnson', 'care', 'intensive', 'stay', \\ johnson moved intensive care&'news', 'care', 'social', 'lockdown', 'health']& 'moved', 'prime', 'minister', 'icu', 'recovery']\\ \hline FACUP&&\\ great save by cech from a low &['the', 'arsenal', 'you', 'goal', 'cfc',&['cup', 'fa', 'final', 'wembley', 'cfc', \\ suarez shot. fa cup final&'still', 'please', 'minutes', 'have', 'chelsea']& 'sl', 'chelsea', 'cech', 'suarez', 'save']\\ \hline \end{tabular} \label{table_outliernormal} \end{table*} {\bf Data-point tracking:} For deeper analysis, we tracked some data-points during their life-cycle in our methodology. Some data-points might be assumed as an outlier in a cluster but after reassignment to another cluster, they turn to be a normal data-point. Two sample tweets have been tracked in Table \ref{table_outliernormal}. In this table, the COVID-19 tweet was first categorized in a general-concept cluster, but when it was identified as an outlier in that cluster, the coordinator re-assigned it to a more specific cluster; Therefore, a normal data-point could be kept among clustered data. In the FACUP tweet, the situation is also similar. Saving the shot of Suarez by Cech was supposed to be an outlier in a general tweet and then labeled as a normal data-point in a more specific one. The strengths of the proposed approach include its dynamic, communicative and parllelizable nature and keeping the detected topics (clusters) as pure as possible. ComStreamClust attempts to keep clusters fresh, by discarding older tweets, and updating the clusters by adding newer ones, and also detecting and deleting the outliers. Note that a tweet might gradually turn into an outlier, due to the updates that happen to the cluster including it. The weaknesses of this approach might be its need for parameter tuning, i.e., it requires adapting each parameter for the given dataset. \section{Conclusion and future work} This paper proposes a new topic detection approach using stream clustering on Twitter data. The proposed approach, named ``ComStreamClust'', is unique in that it benefits from a communication phase, in which, clusters communicate with each other in a multi-agent and parallelizable setting. ComStreamClust has been applied on two datasets, the COVID-19 and the FA CUP. When applied on the FA CUP dataset, it was shown that the proposed methodology provides superior or in some cases, equal perdormance compared to other methodologies. The current analysis on the COVID-19 dataset approves the assumption that social media can help governments and health centers cure this pandemic in a more efficient and rapid manner. For example, almost all Twitter users have used \#StayAtHome in their tweets, which in turn would remind people that staying at home is the most efficient treatment for the COVID-19 pandemic. Our future works include exploiting images inside tweets to accomplish a multinodal topic detection on Twitter. \bibliographystyle{spbasic}
{'timestamp': '2021-04-28T02:25:35', 'yymm': '2010', 'arxiv_id': '2010.05349', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05349'}
arxiv
\section{Introduction} In recent years, there has been increasing interest in studying the time series of functions observed at high frequency. In these time series, the data frequency is high enough to model itself as a curve time series and gives rise to the analysis of functional time series \citep[see, e.g.,][]{HK12, KR17}. Examples of functional time series include intraday stock price curves with each functional observation defined as a pricing function of time points within a day \citep[e.g., see][]{HKR14, LRS20}, and intraday volatility curves with each functional observation defined as a volatility function of time points within a day \citep[e.g., see][]{SYK19}. Most of the existing literature focuses on statistical inference, modeling, and forecasting of a univariate functional time series. We study co-movement by observing samples of bivariate stationary curve time series. A natural question is which time series causes the other? In other words, which functional variable is the leading variable and which functional variable is the lagging variable. To address this problem, we use a measure of causality in scalar-valued univariate time series analysis, known as Granger causality: Based on a suggestion by \cite{Wiener56}, \cite{Granger69} proposed a Granger causality measure that relies on the \textit{additional} predictive ability of the second variable. Granger causality has since been extended and applied to a range of research fields. \cite{Granger80} considered testing for causality, while \cite{Granger88} drew a connection between causation (with a lag between cause and effect) and co-integration. \cite{HJ94} tested linear and non-linear Granger causality in the stock price-volume relation, while \cite{DP06} introduced a nonparametric test for Granger non-causality. In neuroscience and neuroimaging, \cite{SBB15} applied Granger causality to study neural activity using electrophysiological and fMRI data. The Granger causality measure has been modified to generalized measures of correlation (GMC) and Granger causality generalized measures of correlation (GcGMC) by \cite{ZSZ12}. \cite{Vinod17} applied the GMC criterion to analyze the development of economic markets in a study of 198 countries. Further, \cite{Vinod19} developed a package in R \citep{Team20} called ``generalCorr" to implement the GMC. \cite{AH18} used the GMC criterion to analyze causal relations between the VIX, S\&P 500, and the realized volatility of the S\&P 500 sampled at five-minute intervals. \cite{CLC+17} extended the GMC criterion to propose a model-free feature screening approach, namely sure explained variability and independence screening. In this paper, we aim to extend GcGMC from bivariate scalar-valued time series to bivariate function-valued time series. The outline of this paper is as follows. In Section~\ref{sec:1_2}, we present a background for GMC and GcGMC. In Section~\ref{sec:2}, we present a nonparametric function-on-function regression model to estimate conditional mean in function-valued GcGMC. Through a series of simulation studies in Section~\ref{sec:3}, we examine the finite-sample performance of our estimate. In Section~\ref{sec:4}, we present three data analyses for our motivating data examples in climatology and finance, respectively. Conclusions are given in Section~\ref{sec:5}. \section{Granger causality generalized measures of correlation}\label{sec:1_2} Before introducing GcGMC, we revisit GMC and auto generalized measures of correlation (AGMC). The GMC can be derived from a well-known \textit{variance decomposition} formula, \begin{equation} \text{Var}(X) = \text{Var}[\text{E}(X|Y)] + \text{E}[\text{Var}(X|Y)],\label{eq:1} \end{equation} where $X$ and $Y$ are second-order stationary processes with finite variances, and $\text{Var}[\text{E}(X|Y)]$ denotes the variance of the conditional mean of $X$ given $Y$. Equation~\eqref{eq:1} states that the unconditional variance of a random variable $X$ can be expressed as the variance of conditional mean plus the expectation of conditional variance. By dividing~\eqref{eq:1} by Var$(X)$, we obtain \begin{align*} 1 &= \frac{\text{Var}[\text{E}(X|Y)]}{\text{Var}(X)} + \frac{\text{E}[\text{Var}(X|Y)]}{\text{Var}(X)}, \\ \frac{\text{Var}[\text{E}(X|Y)]}{\text{Var}(X)} &= 1 - \frac{\text{E}[\text{Var}(X|Y)]}{\text{Var}(X)}, \end{align*} where $\text{GMC}(X|Y) = \frac{\text{Var}[\text{E}(X|Y)]}{\text{Var}(X)}$ can be interpreted as explained variance of $X$ by $Y$. Similarly, we can define GMC$(Y|X)$ as \begin{equation*} \text{GMC}(Y|X) = \frac{\text{Var}[\text{E}(Y|X)]}{\text{Var}(Y)} = 1 - \frac{\text{E}[\text{Var}(Y|X)]}{\text{Var}(Y)}. \end{equation*} When one models the relationship between random variables $X$ and $Y$ by a linear model $Y = g(X)+\varepsilon$, then GMC$(Y|X)$ is identical to a functional version of $R^2$ when $g(X)$ corresponds to $\text{E}(Y|X)$. However, the GMC is a more generalized correlation measure than the $R^2$, as it can measure possible nonlinear association. When $Y$ is a lagged variable of $X$, and they are bivariate stationary time series, we can measure their serial auto-correlation by AGMC. It is defined as \begin{equation*} \text{AGMC}_k(X_t) = \text{GMC}(X_t|X_{t-k}), \end{equation*} where $k>0$ denotes a lag variable. When $(X_t, Y_t)_{t=1,\dots,n}$ are a pair of bivariate scalar time series, we can also measure cross-correlation by AGMC defined as \begin{equation*} \text{AGMC}_k(Y_t|X_t) = \text{GMC}(Y_t|X_{t-k}). \end{equation*} By taking into account the cross-correlation and auto-correlation, \cite{ZSZ12} proposed a Granger causality general measure of correlation (GcGMC). It is defined as \begin{align*} \text{GcGMC}(X_t|\mathcal{F}_{t-1}) &= 1 - \frac{\text{E}[\{X_t - \text{E}(X_t|X_{t-1}, X_{t-2},\dots, Y_{t-1}, Y_{t-2},\dots)\}^2]}{\text{E}(\text{Var}(X_t|X_{t-1}, X_{t-2},\dots))} \\ &= 1 - \frac{\text{E}[\{X_t - \text{E}(X_t|X_{t-1}, X_{t-2},\dots, Y_{t-1}, Y_{t-2},\dots)\}^2]}{\text{E}[\{X_t - \text{E}(X_t|X_{t-1}, X_{t-2},\dots)\}^2]} \\ \text{GcGMC}(Y_t|\mathcal{F}_{t-1}) &= 1 - \frac{\text{E}[\{Y_t - \text{E}(Y_t|Y_{t-1}, Y_{t-2},\dots, X_{t-1}, X_{t-2},\dots)\}^2]}{\text{E}(\text{Var}(Y_t|Y_{t-1}, Y_{t-2},\dots))} \\ &= 1 - \frac{\text{E}[\{Y_t - \text{E}(Y_t|Y_{t-1}, Y_{t-2},\dots, X_{t-1}, X_{t-2},\dots)\}^2]}{\text{E}[\{Y_t - \text{E}(Y_t|Y_{t-1}, Y_{t-2},\dots)\}^2]}, \end{align*} where $\mathcal{F}_{t-1} = \sigma(X_{t-1}, X_{t-2}, \dots, Y_{t-1}, Y_{t-2},\dots)$ denotes all available series up to time point $t-1$ for a function $\sigma$. Suppose that $\{\mathcal{X}(u), \mathcal{Y}(v)\}$ are second-order stationary curve time series, where $u\in [a, b]$ and $v\in [c, d]$ denote two function supports. Those function support ranges can be different. The GcGMC can be expressed as \begin{align} \text{GcGMC}(\mathcal{X}_t(u)|\mathcal{G}_{t-1}) &= 1 - \frac{\text{E}[\{\mathcal{X}_t(u) - \text{E}(\mathcal{X}_t(u)|\mathcal{X}_{t-1}(u), \mathcal{X}_{t-2}(u),\dots, \mathcal{Y}_{t-1}(v), \mathcal{Y}_{t-2}(v),\dots)\}^2]}{\text{E}[\{\mathcal{X}_t(u) - \text{E}(\mathcal{X}_t(u)|\mathcal{X}_{t-1}(u),\mathcal{X}_{t-2}(u),\dots)\}^2]} \label{eq:7}\\ \text{GcGMC}(\mathcal{Y}_t(v)|\mathcal{G}_{t-1}) &= 1 - \frac{\text{E}[\{\mathcal{Y}_t(v) - \text{E}(\mathcal{Y}_t(v)|\mathcal{Y}_{t-1}(v), \mathcal{Y}_{t-2}(v), \dots, \mathcal{X}_{t-1}(u), \mathcal{X}_{t-2}(u),\dots)\}^2]}{\text{E}[\{\mathcal{Y}_t(v) - \text{E}(\mathcal{Y}_t(v)|\mathcal{Y}_{t-1}(v),\mathcal{Y}_{t-2}(v),\dots)\}^2]},\label{eq:8} \end{align} where $\mathcal{G}_{t-1} = \sigma[\mathcal{X}_{t-1}(u), \mathcal{X}_{t-2}(u),\dots,\mathcal{Y}_{t-1}(v),\mathcal{Y}_{t-2}(v),\dots]$ denotes all available series up to time point $t-1$ for a function $\sigma$. \section{Function-on-function regression}\label{sec:2} \subsection{Functional time series} Functional time series consist of random functions observed at regular time intervals. Functional time series can be classified into two categories depending on if the continuum is also a time variable. On the one hand, functional time series can arise from measurements obtained by separating an almost continuous time record into consecutive intervals \citep[e.g., days or years, see][]{HK12}. We refer to such data structure as sliced functional time series, examples of which include intraday stock price curves \citep{KRS17} and intraday particulate matter \citep{Shang17}. On the other hand, when the continuum is not a time variable, functional time series can also arise when observations over a period are considered as finite-dimensional realizations of an underlying continuous function \citep[e.g., yearly age-specific mortality rates, see][]{LRS20}. \subsection{Nonparametric function-on-function regression} Let $\bm{\mathcal{Y}}=(\mathcal{Y}_1, \mathcal{Y}_2,\dots, \mathcal{Y}_n)^{\top}$ be a vector of functional responses and $\bm{\mathcal{X}}=(\mathcal{X}_1, \mathcal{X}_2, \dots, \mathcal{X}_n)^{\top}$ be a vector of functional predictors. Through samples of ($\bm{\mathcal{X}}, \bm{\mathcal{Y}}$), we investigate the causality between bivariate functional time series. We assume ($\bm{\mathcal{X}}, \bm{\mathcal{Y}}$) are second-order stationary. We consider a function-on-function regression with homoskedastic errors. Given observations $(\mathcal{X}_t, \mathcal{Y}_t)_{t=1,2,\dots,n}$, the regression model can be expressed as \begin{equation*} \mathcal{Y}_t = m(\mathcal{X}_t)+\varepsilon_t, \end{equation*} where $m(\cdot)$ is a smooth function from square-integrable function space to square-integrable function space, and $\varepsilon_t$ denotes error function. When $\mathcal{X}_t=\mathcal{Y}_{t-1}$, we can also model first-order autocorrelation of series $\mathcal{Y}$ by a nonparametric function-on-function regression. Similarly, when $\mathcal{Y}_t = \mathcal{X}_{t+1}$, we can also model first-order autocorrelation of series $\mathcal{X}$ by the nonparametric function-on-function regression. While functional linear regression can measure a linear association between functional predictor and response, it is more usual to consider a possible nonlinear association between two functional variables. There is an increasing amount of literature on the development of nonparametric functional estimators, such as the functional Nadaraya-Watson (NW) estimator \citep{FV06}. For estimating the conditional mean, the functional NW estimator can be defined as \begin{equation} \widehat{m}_h(\mathcal{X}, \bm{\mathcal{Y}}) = \sum^n_{t=1}\frac{K_h[d(\mathcal{X}_t, \mathcal{X})]}{\sum^n_{t=1}K_h[d(\mathcal{X}_t, \mathcal{X})]}\mathcal{Y}_t, \label{eq:9}\\ \end{equation} where $K(\cdot)$ denotes a kernel function that integrates to one. It is often chosen as a unimodal probability density function that can be either symmetric or non-symmetric around zero and has a finite variance. Here, we choose the quadratic kernel function. It is often assumed that functions have a continuous derivative on the function support range for measuring the distance between two curves. We compute a semi-metric $d(\cdot, \cdot)$ based on a second-order derivative, given by \begin{equation*} d_2^{\text{deriv}}(\mathcal{X}_t, \mathcal{X}) = \sqrt{\int_a^b \Big[\mathcal{X}_t^{(2)}(u) - \mathcal{X}^{(2)}(u)\Big]^2du}, \end{equation*} where $\mathcal{X}^{(2)}(u)$ is the second-order derivative of $\mathcal{X}(u)$. The bandwidth parameter $h$ controls the trade-off between squared bias and variance in the mean squared error given by $\text{E}[m(\mathcal{X}) - \widehat{m}(\mathcal{X})]^2$, where $\widehat{m}(\mathcal{X})$ is an estimator of the true but unknown regression function $m(\mathcal{X})$. Here, we choose $h$ by generalized cross validation. Without knowing it as a priori, the first-order temporal dependence is often adequate and convenient to model a time series \citep[see also][]{Granger88, TBE14}. When the functional response variable is one-lag-ahead of the functional predictor variable, we can use the functional NW estimator in~\eqref{eq:9} to capture the autocorrelation. It can be expressed as: \begin{equation} \widehat{m}_b(\mathcal{X}) = \sum^{n-1}_{t=1}\frac{K_b[d(\mathcal{X}_t, \mathcal{X})]}{\sum^{n-1}_{t=1}K_b[d(\mathcal{X}_t, \mathcal{X})]}\mathcal{X}_{t+1}. \label{eq:10b} \end{equation} With the estimated bandwidth parameter $b$ and functional NW estimator in~\eqref{eq:10b}, we can obtain a one-step-ahead prediction of $\mathcal{X}_{n+1}$ given by \begin{equation*} \widehat{\mathcal{X}}_{n+1} = \widehat{m}_b(\mathcal{X}_n) = \sum^{n-1}_{t=1}\frac{K_h[d(\mathcal{X}_t, \mathcal{X}_n)]}{\sum^{n-1}_{t=1}K_h[d(\mathcal{X}_t, \mathcal{X}_n)]}\mathcal{X}_{t+1}. \end{equation*} By plugging estimated $\widehat{\mathcal{X}}_{n+1}$ into~\eqref{eq:9}, we obtain a one-step-ahead prediction of $\mathcal{Y}_{n+1}$ given by \begin{equation*} \widehat{\mathcal{Y}}_{n+1} = \widehat{m}_h(\widehat{\mathcal{X}}_{n+1}, \bm{\mathcal{Y}}) = \sum^n_{t=1}\frac{K_h[d(\mathcal{X}_t, \widehat{\mathcal{X}}_{n+1})]}{\sum^n_{t=1}K_h[d(\mathcal{X}_t, \widehat{\mathcal{X}}_{n+1})]}\mathcal{Y}_t. \end{equation*} With the forecast and holdout functions, we can compute the one-step-ahead prediction error $\mathcal{E}_{n+1}(\mathcal{Y}) = \mathcal{Y}_{n+1} - \widehat{\mathcal{Y}}_{n+1}$. \subsection{GcGMC for curve time series} The GcGMC defined in~\eqref{eq:7} and~\eqref{eq:8} can be viewed as a prediction problem. We divide our data set into a training sample consisting of a portion of the data and a testing sample consisting of the remaining data. For the $t$\textsuperscript{th} observation in the testing sample, the ratio of mean square prediction error can be expressed as: \begin{align} \text{GcGMC}(\mathcal{X}) &= 1- \frac{\text{E}\{[\mathcal{X}_{t}(u) - \text{E}(\mathcal{X}_{t}(u)|\mathcal{X}_{t-1}(u),\mathcal{X}_{t-2}(u),\dots,\mathcal{Y}_{t-1}(v),\mathcal{Y}_{t-2}(v),\dots)]^2\}}{\text{E}\{[\mathcal{X}_{t}(u) - \text{E}(\mathcal{X}_{t}(u)|\mathcal{X}_{t-1}(u),\mathcal{X}_{t-2}(u),\dots)]^2\}} \label{eq:10}\\ \text{GcGMC}(\mathcal{Y}) &= 1 - \frac{\text{E}\{[\mathcal{Y}_{t}(v) - \text{E}(\mathcal{Y}_{t}(v)|\mathcal{Y}_{t-1}(v),\mathcal{Y}_{t-2}(v),\dots,\mathcal{X}_{t-1}(u),\mathcal{X}_{t-2}(u),\dots)]^2\}}{\text{E}\{[\mathcal{Y}_{t}(v) - \text{E}(\mathcal{Y}_{t}(v)|\mathcal{Y}_{t-1}(v),\mathcal{Y}_{t-2}(v),\dots)]^2\}}, \label{eq:11} \end{align} where $\text{E}(\cdot)$ denotes conditional expectation. The GcGMC$(\mathcal{X})$ and GcGMC$(\mathcal{Y})$ provide an overall measure of the GcGMC$(\mathcal{X}_t(u)|\mathcal{G}_{t-1})$ and GcGMC$(\mathcal{Y}_t(v)|\mathcal{G}_{t-1})$ in~\eqref{eq:7} and~\eqref{eq:8}. The numerator and denominator in~\eqref{eq:10} and~\eqref{eq:11} measure sum squared prediction errors. If $\mathcal{Y}$ Granger-causes $\mathcal{X}$, the inclusion of $\mathcal{Y}$ information can help to reduce the sum squared prediction errors in $\mathcal{X}$ \citep[see also][]{GT87}. Thus, it results in a positive-valued GcGMC. Similarly, if $\mathcal{X}$ Granger-causes $\mathcal{Y}$, the addition of $\mathcal{X}$ information can help to reduce the sum squared prediction errors in $\mathcal{Y}$. \section{Simulation studies}\label{sec:3} A Monte-Carlo experiment under different sample sizes is conducted to present the usefulness of the proposed GcGMC. In the Monte Carlo experiment, we consider the following bivariate functional time series: \begin{equation} \mathcal{Y}_t(u) = 0.6 \mathcal{Y}_{t-1}(u) + \int_{v=0}^1 \mathcal{X}_t(v) \beta(u,v) dv + \varepsilon_t(u), \qquad u \in [0,1],\label{eq:sim} \end{equation} where $\varepsilon_t(u)$ denotes an independently and identically distributed (iid) error function with mean zero and finite second-order moment, $\mathcal{Y}_t(u)$ denotes a functional response variable and $\beta(u,v) = \sqrt{u v}$, and $\mathcal{X}_t(v)$ denotes a functional predictor variable that is generated from the functional autoregressive of order 1 process as follows: \begin{equation*} \mathcal{X}_t(v) = \int_0^1 \psi(v,s) \mathcal{X}_{t-1}(s) ds + B_t(v), \end{equation*} where $B_t(v)$ is a realization of a iid standard Brownian motion and $\psi(v,s) = 0.34 \exp^{\frac{1}{2} \left( v^2+s^2 \right)}$. Equation~\eqref{eq:sim} is a functional extension of the plant equation in the engineering literature \citep[see, e.g.,][Equation (2)]{Granger88}. An example of the generated bivariate functional time series is presented in Figure \ref{fig:sim_plots}. \begin{figure}[!htbp] \centering {\includegraphics[width=8.2cm]{sim_Y.pdf}} \quad {\includegraphics[width=8.2cm]{sim_X.pdf}} \caption{\small Functional time series plots of the generated functional response $\mathcal{Y}_1(u)$, \dots, $\mathcal{Y}_n(u)$, and functional predictor $\mathcal{X}_1(v)$, \dots, $\mathcal{X}_n(v)$.}\label{fig:sim_plots} \end{figure} Throughout the experiments, $n = [250, 500, 1000]$ functions are generated at $p$ equally spaced points in the interval $u, v \in [0,1]$. For each sample size, the generated data are divided into the training and test samples with sizes $0.8\times n$ and $0.2 \times n$, respectively. Using the first $0.8 \times n$ of the data, we obtained one-step-ahead forecasts of $\mathcal{X}_t(v)$ and $\mathcal{Y}_t(u)$ at time $t = 0.8\times n + 1$. Having increased the training sample by one, we then obtain-one step-ahead forecasts of $\mathcal{X}_t(v)$ and $\mathcal{Y}_t(u)$ at time $t = 0.8\times n + 2$. This process is repeated until the training sample covers the entire data. For each sample size, we repeat this procedure 100 times and for each time, we compute the GcGMC values of the predictor and response variables. If GcGMC($\mathcal{Y}$) $>$ GcGMC($\mathcal{X}$), we conclude $\mathcal{Y}$ is more predictable than $\mathcal{X}$. Further, if GcGMC($\mathcal{Y})>0$ and GcGMC($\mathcal{X})<0$, we conclude that $\mathcal{X}$ Granger-causes $\mathcal{Y}$, and thus $\mathcal{X}$ is more adequate to be the predictor. In Table~\ref{tab:simulation}, we report the number of times, where GcGMC($\mathcal{Y}$) $>$ GcGMC($\mathcal{X}$) and GcGMC($\mathcal{Y})>0$, GcGMC($\mathcal{X})<0$. As sample size $n$ increases from 250 to 1000, the probability of making a correct decision increases. \begin{table}[!htbp] \centering \caption{\small Out of 100 replications, we compute the number of times where $\mathcal{Y}$ is more predictable than $\mathcal{X}$ when GcGMC($\mathcal{Y}$) $>$ GcGMC($\mathcal{X}$) and $\mathcal{X}$ Granger-causes $\mathcal{Y}$ when GcGMC($\mathcal{Y})>0$ and GcGMC($\mathcal{X})<0$.}\label{tab:simulation} \tabcolsep 0.36in \begin{small} \begin{tabular}{@{}lcccccc@{}} \toprule & \multicolumn{3}{c}{GcGMC($\mathcal{Y}$) $>$ GcGMC($\mathcal{X}$)} & \multicolumn{3}{c}{GcGMC($\mathcal{Y})>0$, GcGMC($\mathcal{X})<0$} \\ $p\backslash n$ & 250 & 500 & 1000 & 250 & 500 & 1000 \\ \midrule 50 & 88 & 94 & 99 & 57 & 84 & 92 \\ 100 & 90 & 99 & 100 & 62 & 82 & 96 \\ 200 & 91 & 97 & 99 & 74 & 81 & 90 \\ 400 & 96 & 99 & 99 & 71 & 85 & 92 \\ \bottomrule \end{tabular} \end{small} \end{table} \section{Data analyses}\label{sec:4} \subsection{Sea surface temperature and sea-level atmospheric pressure}\label{sec:31} The Oceanic Ni\~{n}o index (ONI) is one of the primary indices used to monitor the El Ni\~{n}o Southern Oscillation. The National Oceanic and Atmospheric Administration (\url{https://www.noaa.gov}) agency considers El Ni\~{n}o conditions to be present when the ONI is +0.5 or higher, indicating the east-central tropical Pacific is significantly warmer than usual. La Ni\~{n}a conditions exist when the ONI is -0.5 or lower, indicating the region is cooler than usual. The ONI is computed by averaging 3-month sea surface temperature anomalies in an area of the east-central equatorial Pacific ocean, called the Ni\~{n}o 3.4 region (5S to 5N; 170W to 120W). The 3-month running average of sea surface temperature is often compared to a 30-year average as an indicator of the climate becoming warmer or cooler. The Southern Oscillation Index (SOI) is a measure of the strength of the Walker circulation. It is a critical atmospheric index for controlling the strength of El Ni\~{n}o and La Ni\~{n}a events. The SOI measures the difference in sea-level atmospheric pressure between Tahiti and Darwin, Australia. By standardizing sea-level atmospheric pressures in Tahiti and Darwin, the SOI is obtained by a ratio between the difference of the two standardized sea-level atmospheric pressures and their normalized standard deviation. We consider the bivariate curve time series for the monthly sea surface temperature and sea-level atmospheric pressure from January 1951 to December 2018. The data sets can be obtained from \url{https://www.cpc.ncep.noaa.gov/data/indices/soi} and \url{https://www.cpc.ncep.noaa.gov/products/analysis_monitoring/ensostuff/detrend.nino34.ascii.txt}. In Figure~\ref{fig:1}, we plot the two functional time series. \begin{figure}[!htbp] \centering \includegraphics[width = 8.2cm]{SST_fts} \quad \includegraphics[width = 8.2cm]{SOI_fts} \caption{\small Functional time series plots of the sea surface temperature anomaly and southern oscillation index (a standardized measure of sea-level atmospheric pressure) observed from January 1951 to December 2018. Each curve represents data in a year.}\label{fig:1} \end{figure} We implement a functional nonparametric regression to predict the sea-level atmospheric pressure and sea surface temperature. We split our entire sample into an initial training sample consisting of years from 1951 to 1983 and a testing sample composed of years from 1984 to 2018. Using the years from 1951 to 1983, we obtain one-step-ahead forecasts of the sea-level atmospheric pressure and sea surface temperature in 1984. Then, we increase the training sample by one year and obtain one-step-ahead forecasts of the sea-level atmospheric pressure and sea surface temperature in 1985, respectively. We obtain our forecasts through this expanding window approach until the training sample covers the entire data sample. Let $\mathcal{X}$ be the sea-level atmospheric pressure, and $\mathcal{Y}$ be the sea surface temperature. With the 35 years of forecasts and their corresponding forecast errors, we compute the GcGMC values of~\eqref{eq:10} and~\eqref{eq:11}, namely GcGMC$(\mathcal{X}) = 0.0093$ and GcGMC$(\mathcal{Y}) = -0.2441$. Given $\text{GcGMC}(\mathcal{X}) > \text{GcGMC}(\mathcal{Y})$, we conclude $\mathcal{X}$ is more predictable than $\mathcal{Y}$. Because the GcGMC of the sea-level atmospheric pressure is greater than 0, the inclusion of the sea surface temperature can help to reduce the sum squared prediction errors in the prediction of the sea-level atmospheric pressure. Because the GcGMC of the sea surface temperature is less than 0, the inclusion of the sea-level atmospheric pressure cannot help to reduce the sum squared prediction errors in the prediction of the sea surface temperature. Therefore, we conclude that the sea surface temperature Granger-causes the sea-level atmospheric pressure. \subsection{Dow-Jones Industrial Average and its constituent stocks}\label{sec:32} The Dow-Jones Industrial Average (DJIA) is a stock market index that shows how 30 large publicly owned companies based in the United States have traded during a standard New York Stock Exchange trading session. We consider daily cross-sectional returns from 2/January/2018 to 31/December/2018. The data were obtained from the Thompson Reuters DataScope Tick History. We have a sample of log-price observations, denoted by $q_t^j(u_i)$ for each day $t=1,\dots,n$. We define the $j$\textsuperscript{th} log return on day $t$ as \begin{equation*} r^j_t(u_i) = q_t^j(u_{i+1}) - q_t^j(u_i), \qquad i=1,\dots,95, \end{equation*} that is, $r^j_t(u_i)$ is the log return for $j$\textsuperscript{th} company at the middle of time interval $i$ at day $t$ \citep[e.g., see][]{KRS17, SYK19, LRS20}. In a given day, there are 96 5-minute price observations from 9:30 to 17:20 Eastern time, resulting in 95 values of the log returns. In Table~\ref{tab:DJIA_stocks}, we list 30 constituent stocks of the DJIA. There are five stocks, namely Cisco, Dow Chemical, Intel, Microsoft, and Walgreen, that have missing observations, and are thus removed from our analysis for consistency. \begin{table}[!htbp] \centering \tabcolsep 0.03in \caption{\small Stock name and tick symbol of 30 constituent of the Dow-Jones index}\label{tab:DJIA_stocks} \begin{small} \begin{tabular}{@{}llllll@{}} \toprule Stock & Tick symbol & Stock & Tick symbol & Stock & Tick symbol \\ \midrule Apple Inc & AAPL.OQ & IBM & IBM & PFE & Pfizer \\ AXP & American Express & INTC.OQ & Intel & PG & Procter \& Gamble \\ BA & Boeing & JNJ & Johnson \& Johnson & TRV & Travelers Companies Inc \\ CAT & Caterpillar & JPM & JPMorgan Chase & UNH & United Health \\ CSCO.OQ & Cisco & KO & Coca-Cola & UTX & United Technologies \\ CVX & Chevron & MCD & McDonald's & V & Visa \\ DIS & Disney & MMM & 3M & VZ & Verizon \\ DOW & Dow Chemical & MRK & Merck & WBA.OQ & Walgreen \\ GS & Goldman Sachs & MSFT.OQ & Microsoft & WMT & Wal-Mart \\ HD & Home Depot & NKE & Nike & XOM & Exxon Mobil \\ \bottomrule \end{tabular} \end{small} \end{table} We implement a functional nonparametric regression to predict the DJIA, and each of the 25 stocks. We split our entire sample into an initial training sample consisting of days from 2/January/2018 to 7/August/2018 (151 days in total) and a testing sample composed of days 8/August/2018 to 31/December/2018 (100 days in total). Using days from 2/January/2018 to 7/August/2018, we obtain one-step-ahead forecasts of the DJIA and each of its constituent stocks on day 8/August/2018. Then, we increase the training sample by one day and obtain one-step-ahead forecasts of the DJIA and each of its constituent stock in day 9/August/2008, respectively. Through this expanding-window approach, we obtain our forecasts until the training sample covers the entire data sample. With 100 days of forecasts and their corresponding forecast errors, we compute the GcGMC values when either a stock or DJIA is a response variable in the nonparametric function-on-function regression in Table~\ref{tab:GcGMC_DJIA}. Let $\mathcal{X}$ be the log-return of DJIA and $\mathcal{Y}$ be the log-return of a stock. For several stocks highlighted in blue in the table, we observe that the GcGMC of the DJIA is less than 0, and the GcGMC of the stock is greater than 0. Thus, the DJIA's inclusion can help reduce the sum squared prediction errors in the stock's prediction. These stocks highlighted in blue are lagging behind the DJIA for the period we considered. When the two GcGMC values have the same sign, we can no longer make a specific statement about leading and lagging. Instead, we can only highlight those stocks that are less predictive than the DJIA in red as GcGMC$(\mathcal{X})$ $>$ GcGMC$(\mathcal{Y})$; similarly, those stocks that are more predictive than the DJIA in white. For those stocks that are lagging behind the DJIA, a possible practical implication is to predict the direction of their log returns based on the most recent log return of the DJIA. \begin{table}[!htbp] \tabcolsep 0.045in \centering \caption{\small GcGMC values when either the log return of a stock or DJIA is the response variable in the nonparametric function-on-function regression.}\label{tab:GcGMC_DJIA} \begin{small} \begin{tabular}{@{}lrlrlrlrlr@{}} \toprule Variable & GcGMC & Variable & GcGMC & Variable & GcGMC & Variable & GcGMC & Variable & GcGMC \\ \midrule AAPL.OQ & \cellcolor{blue!25}{0.0031} & AXP & \cellcolor{blue!25}{0.0058} & JNJ & \cellcolor{blue!25}{0.0039} & KO & \cellcolor{blue!25}{0.0006} & MRK & \cellcolor{blue!25}{0.0032} \\ DJIA & \cellcolor{blue!25}{-0.0185} & DJIA & \cellcolor{blue!25}{-0.0063} & DJIA & \cellcolor{blue!25}{-0.0064} & DJIA & \cellcolor{blue!25}{-0.0055} & DJIA & \cellcolor{blue!25}{-0.0201} \\ \\ NKE & \cellcolor{blue!25}{0.0015} & PFE & \cellcolor{blue!25}{0.0013} & UNH & \cellcolor{blue!25}{0.0019} & UTX & \cellcolor{blue!25}{0.0031} & WMT & \cellcolor{blue!25}{0.0007} \\ DJIA & \cellcolor{blue!25}{-0.0133} & DJIA & \cellcolor{blue!25}{-0.0140} & DJIA & \cellcolor{blue!25}{-0.0087} & DJIA & \cellcolor{blue!25}{-0.0127} & DJIA & \cellcolor{blue!25}{-0.0061} \\ \\ TRV & \cellcolor{red!25}{-0.6959} & BA & -0.0022 & CAT & -0.0040 & CVX & -0.0014 & DIS & -0.0001 \\ DJIA & \cellcolor{red!25}{-0.0107} & DJIA & -0.0125 & DJIA & -0.0091 & DJIA & -0.0062 & DJIA & -0.0046 \\ \\ GS & -0.0034 & HD & -0.0031 & IBM & 0.0047 & JPM & -0.0046 & MCD & -0.0003 \\ DJIA & -0.0121 & DJIA & -0.0073 & DJIA & 0.0141 & DJIA & -0.0052 & DJIA & -0.0107 \\ \\ MMM & -0.0015 & PG & -0.0071 & V & -0.0011 & VZ & -0.0051 & XOM & -0.0004 \\ DJIA & -0.0102 & DJIA & -0.0079 & DJIA & -0.0024 & DJIA & -0.0132 & DJIA & -0.0074 \\ \bottomrule \end{tabular} \end{small} \end{table} \subsection{S\&P 500 index and WTI oil price} The S\&P 500 index is a stock market price representing the performance of around 500 of the largest U.S. companies. When observing the S\&P 500 index, we also observe oil prices from West Texas Intermediate (WTI). We aim to investigate if the oil price is a leading or lagging variable of the S\&P 500. We collected monthly S\&P 500 indexes and WTI prices from January/1984 to December/2019 (432 months in total). For each month in a given year $t$, we compute the normalized prices of the S\&P 500 and WTI by taking into account the consumer price index in the United States (CPI). The normalized prices can be expressed as \begin{align*} q_t^{\text{WTI}}(u_i) &= \frac{\text{WTI}_{\text{observed}, t}(u_i)}{\text{CPI}_{\text{observed}, t}(u_i)}\times 100, \\ q_t^{\text{S\&P 500}}(u_i) &= \frac{\text{S\&P 500}_{\text{observed}, t}(u_i)}{\text{CPI}_{\text{observed}, t}(u_i)}\times 100, \end{align*} where $i$ denotes any given month. The log returns of the normalized WTI and S\&P 500 at month $i$ in year $t$ can be expressed as \begin{align*} r_t^{\text{WTI}}(u_i) &= \ln \left[\frac{q_t^{\text{WTI}}(u_{i+1})}{q_t^{\text{WTI}}(u_i)}\right], \\ r_t^{\text{S\&P 500}}(u_i) &= \ln \left[\frac{q_t^{\text{S\&P 500}}(u_{i+1})}{q_t^{\text{S\&P 500}}(u_i)}\right], \qquad i=1,\dots,11. \end{align*} In Figure~\ref{fig:sp_wti}, we display two functional time series plots of the log returns of the S\&P 500 and WTI. Using a stationarity test of \cite{HKR14}, we checked and verified that both series are stationary with $p$-values of 0.998 and 0.931, respectively. \begin{figure}[!htbp] \centering {\includegraphics[width=8.2cm]{sp500}} \quad {\includegraphics[width=8.2cm]{wti}} \caption{\small Functional time series plots of the log returns of the normalized prices of the S\&P 500 and WTI by incorporating the consumer price index in the United States.}\label{fig:sp_wti} \end{figure} We implement a nonparametric function-on-function regression to predict the log returns of S\&P 500 and WTI. The entire data set was split into an initial training sample consisting of monthly log returns from January/1984 to December/2003 (20 curves in total) and a testing sample composed of months from January/2004 to December/2019 (16 curves in total). Using the initial training sample, we obtain one-step-ahead curve forecasts of the log returns of the WTI and S\&P 500 in 2004. Then, we increase the number of curves in the training sample by one year and obtain one-step-ahead forecasts of the WTI and S\&P 500 in 2005. Through an expanding-window approach, we obtain our forecasts until the training sample covers the entire data sample. Let $\mathcal{X}$ be the S\&P 500 log returns and $\mathcal{Y}$ be the WTI log returns. With 16 curves in the testing sample, we compute the corresponding one-step-ahead forecast errors, from which we compute the GcGMC when the S\&P 500 or WTI is the response variable, namely GcGMC$(\mathcal{X}) = -0.0232$ and GcGMC$(\mathcal{Y}) = 0.1255$. We observe that the GcGMC of the WTI is greater than 0, and the GcGMC of the S\&P 500 is less than 0, so the inclusion of the S\&P 500 can help reduce the sum squared prediction errors in the prediction of the WTI. Thus, the S\&P 500 index is a leading variable of the WTI price. A possible practical implication is to predict the direction of the WTI price based on the most recent S\&P 500 index. \section{Conclusion}\label{sec:5} We extend the Granger causality generalized measures of correlation from bivariate scalar to curve time series. With this measure, we can investigate which curve time series Granger-causes the other one; in turn, it helps to determine suitable predictor and response variables. Granger causality can be viewed from a prediction viewpoint. The measure can be computed by a nonparametric function-on-function regression that captures the possible nonlinear pattern between the predictor and response. Illustrated by a climatology data set, we find that the sea surface temperature Granger-causes the sea-level atmospheric pressure. From the Dow-Jones index data set, we find those constituent stocks that are lagged behind the Dow-Jones index. From the S\&P 500 and WTI oil data sets, we find that the S\&P 500 index Granger causes the WTI price. There are two limitations associated with our Granger causality generalized measures of correlation. This measure depends on the length of training and testing samples. Sometimes, an outlying observation in the testing sample can affect the estimation accuracy of our proposed measure. Second, we compute a one-step-ahead forecast and its errors as a way of assessing predictive ability. While this sets up the foundation for our measure, it is sometimes more useful to consider other longer-term forecast horizons. There are several ways in which the current work may be further extended, and we briefly outline three. First, we could extend Granger causality tests studied in \cite{Geweke84} to function-valued variables, and possibly assess the strength of this relationship \citep[see, e.g.,][]{TBE14}. Second, since there is a strong connection between Granger causality and co-integration \citep[see, e.g.,][]{Granger86, Granger88}, one may study the concept of co-integration in non-stationary functional time series. Finally, the causality arisen from the Granger causality generalised measures of correlation may depend on a specific forecast horizon. We may extend the current work by forecasting $h>1$ step ahead, which may help to incorporate seasonality in a functional time series forecasting \citep[see, e.g.,][]{CMZ19}. \bibliographystyle{agsm}
{'timestamp': '2020-10-21T02:06:11', 'yymm': '2010', 'arxiv_id': '2010.05320', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05320'}
arxiv
\section{Introduction} Neural Machine Translation (NMT) in the biomedical domain presents challenges in addition to general domain translation. Text often contains specialist vocabulary and follows specific stylistic conventions. For this task fine-tuning generic pre-trained models on smaller amounts of biomedical-specific data can lead to strong performance, as we found in our 2019 biomedical submission \citep{saunders-etal-2019-ucam}. For our WMT 2020 submission we start with strong single models from that 2019 submission and fine-tune them exclusively on the small Medline abstracts training sets \citep{bawden-etal-2019-findings}. This allows fast training on very relevant training data, since the test set is also made up of Medline abstracts. However, fine-tuning on relevant but small corpora has pitfalls. The small number of training examples exacerbates the effect of any noisy or poorly aligned sentence pairs. We treat this as a form of exposure bias, in that model overconfidence in training data results in poor translation hypotheses at test time. Our contributions in this system paper are: \begin{itemize} \item A discussion of exposure bias in the form of imperfect training data, focusing on the biomedical domain. \item An exploration of straightforward ways to mitigate exposure bias via data preparation and training objective. \item A discussion of our 2020 Biomedical task results for single models fine-tuned on small, domain-specific data sets. \end{itemize} \subsection{Exposure bias in the biomedical domain} \begin{table*}[ht] \centering \small \begin{tabular}{|p{2.4cm}|p{12.6cm}|}\hline English source & [Associations of work-related strain with subjective sleep quality and individual daytime sleepiness].\\ Human translation & [Zusammenhang von arbeitsbezogenen psychischen Beanspruchungsfolgen mit subjektiver Schlafqualität und individueller Tagesschläfrigkeit.] \\ \hline MLE & Zusammenfassung. \\ MRT & [Assoziationen arbeitsbedingter Belastung mit subjektiver Schlafqualität und individueller Tagesschläfrigkeit]. \\ \hline English source & [Effectiveness of Upper Body Compression Garments Under Competitive Conditions: A Randomised Crossover Study with Elite Canoeists with an Additional Case Study]. \\ Human translation & [Effektivität von Oberkörperkompressionsbekleidung unter Wettkampfbedingungen: eine randomisierte Crossover-Studie an Elite-Kanusportlern mit einer zusätzlichen Einzelfallanalyse.]\\ \hline MLE & Eine randomisierte Crossover-Studie mit Elite-Kanuten mit einer Additional Case Study wurde durchgeführt. \\ MRT & Eine randomisierte Crossover-Studie mit Elite-Kanüsten mit einer Additional Case Study hat zur Wirksamkeit von Oberkörperkompressionsbekleidung unter kompetitiven Bedingungen geführt. \\ \hline \end{tabular} \caption{Two sentence from the English-German 2020 test set with hypothesis translations from various models, demonstrating the effects of exposure bias from training on imperfectly aligned training sentences. The first MLE example output is completely unrelated to the source sentence, but the second MLE translation is more misleading.}\label{tab:exposurebias} \end{table*} Exposure bias for an autoregressive sequence decoder refers to a discrepancy between decoder conditioning during training and inference \citep{bengio2015scheduled, ranzanto16sequencelevel}. During training the decoder generates a hypothesis for the $t^{th}$ output token $\hat{y_t}$ conditioned on $y_{1:t-1}$, the gold target sequence prefix. During inference, the gold target $y$ is unavailable, and $\hat{y_t}$ is conditioned instead on the hypothesis prefix $\hat{y}_{1:t-1}$. Previous work has interpreted the risk of exposure bias primarily in terms of the model over-relying on correct gold target translations, resulting in error propagation when mistakes are made during inference. We take a different view, focusing on mistakes in the training data which harm the model through teacher-forcing exposure and cause it to make related mistakes during inference. We identify a specific feature of the Medline abstract training data which caused noticeable translation errors. The data contains instances in which either the source or target sentence contains the correct translation of the other sentence, but adds information that is not found in translation. For example, the following sentence appears in the English side of en-de Medline abstract training data: \emph{[The effects of Omega-3 fatty acids in clinical medicine]. Effects of Omega-3 fatty acids (n-3 FA) in particular on the development of cardiovascular disease (CVD) are of major interest.} Its corresponding German sentence is \emph{Der Nutzen von Omega-3-Fettsäuren (n-3-FS) in der Medizin, hauptsächlich in der Prävention kardio- und zerebrovaskulärer Erkrankungen, wird aktuell intensiv diskutiert.} (Translated: `The uses of Omega-3 fatty acids in medicine, especially in prevention of cardiovascular and cerebrovascular diseases, are currently heavily discussed.') Some of the English sentence is present in the German translation, but the square-bracketed article title is not. In this example it might be possible to remove only the segment in square brackets, but in other examples there is even less overlap, while source and target sentences may still be related and therefore challenging to filter. For example, the following English and German sentences also correspond with still less overlap: \emph{[Conflict of interest with industry--a survey of nurses in the field of wound care in Germany , Australia and Switzerland]. Background.} \emph{Hintergrund: Pflegende werden zunehmend von der Industrie umworben.} (Translated: `Background: Nurses are being increasingly courted by industry.') These examples are quite frequent in Medline abstract data, especially in the form of titles. It is common to insert the English title of a non-English article into its translation, marked with square brackets \citep{patrias2007citing}. The marked title is not present in the original article. Consequently models trained on English source sentences with titles can behave erratically when given sentences with square-bracketed titles at test time: an exposure bias effect. One possible approach to this problem is aggressively filtering sentences which may be poorly aligned. However, with such a small training set, this risks losing valuable examples of domain-specific source and target language. We hypothesise that such filtering is not the only way to reduce the effects during inference. Instead, we propose an approach in terms of the parameter fine-tuning scheme with Minimum Risk Training (MRT). \citet{wang-sennrich-2020-exposure} have recently shown MRT as effective for combating exposure bias in the context of domain shift -- test sentences which are very different from the training data. We propose that MRT is also more robust against exposure to misaligned training data. The examples in Table \ref{tab:exposurebias} show the different behaviour of MLE and MRT in such cases. In the first example, the MLE hypothesis is unrelated to the source sentence, while the MRT output is relevant. In the second example, the MLE output is more plausible and therefore misleading, as it still misses the first clause which the MRT hypothesis covers. Both MLE and MRT hypotheses are phrased like opening sentences rather than titles, and both feature the untranslated phrase `Additional Case Study': while MRT may be more robust, it is not immune to exposure bias. We note that title translations may not exist in the human reference. In these cases failure to translate the title will not negatively impact BLEU. However, we argue a biomedical translation model should be able to translate such sentences if required. It is also important to note that title translations are not the only case of inexact training pairs, but are simply easily identifiable. \subsection{Document MRT} \begin{figure}[ht] \centering \small \includegraphics[width=\linewidth]{ordered-doc-samples-small-label.png} \caption{Two MRT schemes with an $S=2$ sentence minibatch and $N=3$ samples / sentence. In standard MRT (middle) each sample has a score, e.g. sBLEU. For doc-MRT (right) samples are sorted into minibatch-level `documents', each with a combined score, e.g. document BLEU. Doc-MRT scores are less sensitive to individual samples, increasing robustness.} \label{fig:mrt} \end{figure} Minimum Risk Training (MRT) aims to minimize the expected cost between $N$ sampled target sequences $\bm{y_n^{(s)}}$ and the corresponding gold reference sequence $\bm{y}^{(s)\ast}$ for the $S$ sentence pairs in each minibatch. For translation MRT is usually applied using a sentence-level BLEU (sBLEU) score corresponding to cost function $1 - \text{sBLEU}$, and sentence samples are generated by auto-regressive sampling with temperature $\tau$ during training \citep{shen2016minimum}. Hyperparameter $\alpha$ controls sharpness of the distribution over samples. While MRT permits training from scratch, in practice it is exclusively used to fine-tune models. Doc-MRT is a recently proposed MRT variant which changes sentence cost function to a document cost function, $D(.)$ \citep{saunders-etal-2020-using}. $D$ measures costs between minibatch-level `documents' $Y^*$ and $Y_n$. $Y^*$ is formed of all $S$ reference sentences in the minibatch, and $Y_n$ is one of $N$ sample `documents' each formed of one sample from each sentence pair $( \bm{x}^{(s)}, \bm{y}^{(s)\ast})$. This permits MRT under document-level scores like BLEU, instead of sBLEU. The $n^{th}$ sample for the $s^{th}$ sentence in the minibatch-level document, $\bm{y}_n^{(s)}$, contributes the following term to the overall gradient: $$ \frac{\alpha}{N} \sum_{Y: \bm{y}^{(s)} = \bm{y}^{(s)}_n} D(Y, Y^*) \nabla_\theta \log P(\bm{y}^{(s)}_n|\bm{x}^{(s)};\theta) $$ In other words the gradient of each sample is weighted by the aggregated document-level scores for documents in which the sample appears. Figure \ref{fig:mrt} gives a toy example of doc-MRT scoring samples in context. Document-level metrics aggregate scores across sentence samples, meaning a minibatch with some good samples and some poor samples will not have extreme score variation. Doc-MRT is therefore less sensitive than standard MRT to variation in individual samples. Doc-MRT has been shown to give better performance than standard MRT for small datasets with a risk of over-fitting, as well as improved robustness to small $N$. More discussion of these results and a derivation of the document-level loss function can be found in \citet{saunders-etal-2020-using}. Since we are attempting fine-tuning on small datasets and since $N$ is a limiting factor for MRT on memory-intensive large models, the biomedical task is an appropriate application for doc-MRT. \begin{table*}[ht] \centering \small \begin{tabular}{|l|l|l|l|l|l|}\hline & \textbf{Phase} & \textbf{Datasets} & \textbf{Sentence pairs} & \textbf{Dev datasets} & \textbf{Sentence pairs}\\ \hline \multirow{9}{*}{en-es}& \multirow{5}{*}{Pre-training}& UFAL Medical\footnotemark &639K & \multirow{5}{*}{Khresmoi\footnotemark} & \multirow{5}{*}{1.5K} \\ & &Scielo\footnotemark & 713K && \\ & & Medline titles\footnotemark& 288K&& \\ & & Medline abstracts & 83K && \\ & & Total &1723K / \textbf{1291K}&& \\ \cline{2-6} & Fine-tuning & Medline abstracts & 83K / \textbf{67.5K} & Biomedical19 & 800\\ \hline \multirow{4}{*}{en-de} & \multirow{3}{*}{Pre-training} & UFAL Medical &2958K& Khresmoi& 1.5K\\ && Medline abstracts & 33K &Cochrane\footnotemark &467 \\ & & Total &2991K / \textbf{2156K}& & \\ \cline{2-6} & Fine-tuning & Medline abstracts & 33K / \textbf{28.6K} & Biomedical19 & 800\\ \hline \end{tabular} \caption{Biomedical training and validation data used in the evaluation task. For both language pairs identical data was used in both directions. Bolded numbers are totals after filtering}\label{tab:data} \end{table*} \subsection{Related work} Fine-tuning general models on domain-specific datasets has become common in NMT. Simple transfer learning on new data can adapt a general model to in-domain data \citep{luong2015stanford}. Mixed fine-tuning where some original data is combined with the new data avoids reduced performance on the original data-set \citep{chu2017empirical}. We are only interested in performance on one domain, so use simple transfer learning. For this task, we specifically fine-tune on a relatively small dataset. Adaptation to very small, carefully-chosen domains has been explored for speaker-personalized translation \citep{michel-neubig-2018-extreme} , and to reduce gender bias effects \citep{saunders-byrne-2020-reducing} while maintaining general domain performance. We wish to adapt to a very specific domain without need to maintain good general domain performance, but must avoid overfitting. Related approaches include fine-tuning a separate model for each test sentence \citep{li-etal-2018-one, farajian-etal-2017-multi} or test document \citep{xu2019lexical, kothur-etal-2018-document}. We choose to train a single model for all test sentences in a language pair, but improve the robustness of that model to overfitting and exposure bias using MRT. MRT has been widely applied to NMT in recent years \citep{shen2016minimum, neubig-2016-lexicons, edunov2018classical}. In particular, \citet{wang-sennrich-2020-exposure} recently highlighted the efficacy of MRT for reducing the effects of exposure bias. \section{Experimental setup} \begin{table*}[ht] \centering \small \begin{tabular}{l|l|cc|cc|} \cline{2-6} & &\textbf{de2en} & \textbf{en2de} & \textbf{es2en} & \textbf{en2es}\\ \cline{2-6} \footnotesize{1}& Baseline & 38.8 &30.6 & 48.5 & 46.6 \\ \footnotesize{2}& MLE fine-tuning from 1 &40.9 & 32.5 & 48.5 & 46.0 \\ \footnotesize{3}& Checkpoint averaging 2 (en-de) / 1 (en-es) & 41.1 & 32.2& 48.5 &47.1 \\ \cline{2-6} \footnotesize{4}& MRT from 1 & 40.0 & 31.1 & \textbf{49.0} & 47.4 \\ \footnotesize{5}& MRT from 2 (en-de only) &\textbf{41.3} & 32.9 & - &-\\ \footnotesize{6}& Checkpoint averaging 5 (en-de) / 4 (en-es) & \textbf{41.3} &\textbf{33.0} & 48.9 & \textbf{47.7}\\ \cline{2-6} \end{tabular} \caption{Validation BLEU developing models used in English-German and English-Spanish language pair submissions. Scores for single checkpoints unless indicated. MLE fine-tuning did not improve over the en-es baselines, so we do not use these models to initialise MRT.}\label{tab:ablation-results} \end{table*} \footnotetext[1]{\url{https://ufal.mff.cuni.cz/ufal\_medical\_corpus}} \footnotetext[2]{\citet{dusek2017khresmoi}} \footnotetext[3]{\citet{neves2016scielo}} \footnotetext[4]{\url{https://github.com/biomedical-translation-corpora/medline} \cite{yepes2017findings}} \footnotetext[5]{\url{http://www.himl.eu/test-sets}} \begin{table*}[ht] \centering \small \begin{tabular}{|l|cc|cc|} \hline &\textbf{de2en} & \textbf{en2de} & \textbf{es2en} & \textbf{en2es}\\ \hline MLE from baseline & 41.1 & 32.2& - & - \\ MLE from baseline, no-title & 41.4 & 31.8&- &- \\ MRT from: MLE (en-de) / baseline (en-es) & 41.3 &\textbf{33.0} & 48.9 & \textbf{47.7}\\ MRT no-title from: MLE no-title (en-de) / baseline (en-es) & \textbf{41.9} & 32.6 & \textbf{49.0} & 47.2\\ \hline \end{tabular} \caption{Validation BLEU developing models used in English-German and English-Spanish language pair submissions. Scores for averaged checkpoints. MLE fine-tuning with either dataset did not improve over the en-es baselines.}\label{tab:notitles-results} \end{table*} \begin{table*}[ht] \centering \small \begin{tabular}{|l|cccc|cccc|} \hline & \multicolumn{2}{c}{\textbf{de2en}} & \multicolumn{2}{c}{\textbf{en2de}} & \multicolumn{2}{c}{\textbf{es2en}} & \multicolumn{2}{c|}{\textbf{en2es}}\\ & \textbf{Dev} & \textbf{Test} & \textbf{Dev} & \textbf{Test} & \textbf{Dev} & \textbf{Test} & \textbf{Dev} & \textbf{Test}\\ \hline MLE (all data) (en-de) / Baseline (en-es) & 41.1 & 39.6 & 32.2 & 32.9 & 48.5 & \textbf{46.6} & 47.1 & 45.7\\ MRT (no-title data) & \textbf{41.9} & 39.6 & 32.6 & 32.8 & \textbf{49.0} & 46.4 & 47.2&\textbf{46.7} \\ MRT (all data) & 41.3 & \textbf{39.8} & \textbf{33.0} & \textbf{33.2} & 48.9 & \textbf{46.6} & 47.7& 46.6\\ \hline \end{tabular} \caption{Validation and test BLEU for models used in English-German and English-Spanish language pair submissions. Test results are for "OK sentences" as scored by the organizers.}\label{tab:submission-results} \end{table*} \label{ss:data} \subsection{Data} We report on two language pairs: English-Spanish (en-es) and English-German (en-de). Table \ref{tab:data} lists the data used to train our biomedical domain evaluation systems. For each language pair we use the same training data in both directions, and preprocess all data with Moses tokenization, punctuation normalization and truecasing. We use a 32K-merge joint source-target BPE vocabulary \cite{sennrich2016subword} learned on the pre-training data. All of our submitted approaches involve fine-tuning pre-trained models. We initialise fine-tuning with the strong biomedical domain models that formed our `run 1' submission for the WMT19 biomedical translation task. Details of data preparation and training for these models are discussed in \citet{saunders-etal-2019-ucam}. We fine-tune these models on Medline abstracts data, validating on test sets from the 2019 Biomedical task. For these we concatenate the src-trg and trg-src 2019 test sets for each language pair, and select only the `OK' aligned sentences as annotated by the organizers. Before fine-tuning we carry out detected language filtering on the Medline abstracts fine-tuning data using the Python LangDetect package\footnote{\url{https://pypi.org/project/langdetect/}}. We find LangDetect has a tendency to incorrectly label short sentences or those with rare vocabulary (very common in Medline) as a random language. For each language pair we therefore filter out only sentences where LangDetect identifies the source sentence as belonging to the target language, and vice versa. We then use a series of simple heuristics to further filter the parallel datasets, removing duplicate sentence pairs, those with source/target length ratio of $<$ 1:3.5 or $>$ 3.5:1, and sentences with $>$ 120 tokens. For the more aggressively-filtered `no-title' experiments we additionally remove all lines containing multiple tokens in square brackets, which in medical writing are used to denote the English translation of a non-English article's title \citep{patrias2007citing}. This leaves 27.3K sentence pairs for en-de and 64.8K for en-es: about 96\% of the filtered data in both cases. \subsection{Model hyperparameters and training} We use the Tensor2Tensor implementation of the Transformer model with the \texttt{transformer\_big} setup for all NMT models \cite{tensor2tensor}. We use the same effective batch size of 4k tokens for both MLE and doc-MRT. Because of model size constraints and the need to sample multiple targets for doc-MRT, we achieve the 4k effective batch size by accumulating gradients \citep{saunders2018multi} over every 4 batches of 1k tokens for MLE and every 16 batches of 256 tokens for doc-MRT. For doc-MRT we use sampling temperature $\tau=0.3$, smoothing parameter $\alpha=0.6$ and $N=8$ samples per sentence, which gave the best results for our doc-MRT experiments in \citet{saunders-etal-2020-using}. For each approach we fine-tune on a single GPU, saving checkpoints every 1K updates, until fine-tuning validation set BLEU fails to improve for 3 consecutive checkpoints. Generally this took about 5K updates. We then perform checkpoint averaging \cite{sys-amu-wmt16} over the final 3 checkpoints to obtain the final model. \subsection{Inference} For the 2020 submissions, we additionally split any test lines containing multiple sentences before inference using the Python NLTK package\footnote{\url{https://pypi.org/project/nltk/} sentence splitter}, translate the split sentences separately, then remerged. We found this gave noticeable improvements in quality for the few sentences it applied to. In all cases we decode with beam size 4 using SGNMT \cite{stahlberg2017sgnmt}. Test scores are as provided by the organizers for "OK" sentences using Moses tokenization and the multi-eval tool. Validation scores are for case-insensitive, detokenized text obtained using SacreBLEU\footnote{SacreBLEU signature: \texttt{BLEU+case.lc+numrefs.1\\+smooth.exp+tok.13a+version.1.2.11}} \citep{post2018call}. \subsection{Results} We first assess the impact of small-domain adaptation to the full title-included Medline training set. Results in Table \ref{tab:ablation-results} show that small-domain MLE can lead to over-fitting and reduced performance (en-es) but also significant gains (en-de). Further fine-tuning with doc-MRT improved performance relative to the best MLE model for all translation directions by up to 0.8 BLEU when comparing with or without checkpoint averaging. While checkpoint averaging slightly decreased validation set performance for en2de MLE, we use it in all cases since it reduces sensitivity to randomness in training \citep{popel2018training}. In Table \ref{tab:notitles-results} we explore the impact of fine-tuning only on aggressively filtered `no-title' data. This does noticeably improve performance for de2en, with a very small improvement for es2en. Since the added information in `title' sentences is on the English side, this suggests that target training sentence quality impacts both MLE and MRT performance. However, removing these sentences entirely results in a noticeable performance decrease for the en2de and en2es models, demonstrating that they can be valuable training examples. We submitted three runs to the WMT20 biomedical task for each language pair. For en-de run 1 was the baseline model fine-tuned on MLE with all data, while for en-es we submitted the checkpoint averaged baseline as MLE fine-tuning did not improve dev set performance. Run 2 was the run 1 model fine-tuned with doc-MRT on no-title data. Run 3 was the run 1 model fine-tuned with doc-MRT on all Medline abstract data. Table \ref{tab:submission-results} gives scores for these submitted models. Our best runs achieve the best and second-best results among all systems for en2es and es2en respectively as reported by the organizers. For en-de our test scores are further behind other systems, perhaps indicating that the baseline system could have been stronger before fine-grained adaptation. This is also indicated by the strong improvement of these models under simple MLE. We submitted the MRT model on no-title data instead of the MLE on no-title data because MLE optimization did not improve over the baseline for en-es or en-es, with or without title lines, whereas MRT fine-tuning did. We also wanted to further examine whether MRT was robust enough to benefit from `noisy' data like the title lines, or whether cleaner no-title training data was more useful. In fact both forms of doc-MRT performed similarly on the test data, except in the case of en2de, where `no-title' MRT scored 0.4 BLEU worse -- further confirmation that source sentences with more information than the gold target can benefit MRT. We note that a MRT run was the best run or tied best run in all cases. For the test runs, we additionally experimented with simply removing square bracket tokens from source sentences, since these could act as `triggering' tokens for title sentences. This did seem to improve translations for the sentences it applied to, but is clearly not applicable to all forms of exposure bias, since it requires knowledge of all behaviours that could trigger exposure bias. MRT does not require such knowledge, but still reduces the effects of exposure bias. \section{Conclusions} Our WMT20 Biomedical submission investigates improvements on the English-German and English-Spanish language pairs under a single strong model. In particular, we focus on the behaviour of models trained on sentences with some predictable irregularities. We find that aggressively filtering target sentences can help overall performance, but that aggressively filtering source sentence tends to hurt performance. We also find that Minimum Risk Training can benefit from imperfectly aligned training examples while reducing the effects of exposure bias. \section*{Acknowledgments} This work was supported by EPSRC grants EP/M508007/1 and EP/N509620/1 and has been performed using resources provided by the Cambridge Tier-2 system operated by the University of Cambridge Research Computing Service\footnote{\url{http://www.hpc.cam.ac.uk}} funded by EPSRC Tier-2 capital grant EP/P020259/1. \bibliographystyle{acl_natbib}
{'timestamp': '2020-10-13T02:25:18', 'yymm': '2010', 'arxiv_id': '2010.05333', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05333'}
arxiv
\section{Introduction} Person Re-Identification (ReID) aims to match all the instances of the same person across a system of non-overlapping cameras. This is a challenging task due to extreme view-point changes and occlusions. It has various applications in surveillance systems and it has gained a lot of popularity in the context of computer vision, where new scenarios of this task have been developed recently~\cite{zhou2018vehicle,liu2016large,zhang2019mvb}. Numerous approaches have been proposed using person-related information, such as pose and body parts~\cite{quispe2019improved,kumar2017pose,zheng2019pose,li2017learning,cheng2016person}. However, ReID datasets only provide ID labels. Thus, these methods rely on other datasets proposed for related tasks during the training. This dependency introduces further errors in predictions and motivates the creation of general methods that do not learn from outer information. In this paper, we introduce the Top DropBlock Network (Top-DB-Net) for the ReID problem. Top-DB-Net is designed to further push networks to focus on task-relevant regions and encode low informative regions with discriminative features. Our method is based on three streams consisting of (i) a classic global stream as most of the state-of-the-art methods~\cite{quispe2019improved,kumar2017pose,zheng2019pose,li2017learning,cheng2016person, dai2019batch,luo2019bag}, (ii) a second stream drops\footnote{We use the terms {\it remove} and {\it drop} interchangeably to indicate that a tensor region has been zeroed out.} most activated horizontal stripes of feature tensors to enhance activation in task-discriminative regions and improve encoding of low informative regions, and (iii) a third stream regularizes the second stream avoiding that noise generated by dropping features degrades the final results. As a result of our proposed method, we can observe in Figure~\ref{fig:comp-activation-baseline} that the activation maps~\cite{zagoruyko2016paying} generated by our baseline, focus both on body parts and background, whereas Top-DB-Net focus consistently on the body with stronger activation to discriminative regions. \begin{figure}[!htb] \captionsetup[subfigure]{labelformat=empty} \centering \subfloat{\includegraphics[width=1.4cm, height=3.0cm]{figs/0001_c3s1_000551_00_bdnet_1.jpg}} \hspace*{0.1cm} \subfloat{\includegraphics[width=1.4cm, height=3.0cm]{figs/0001_c3s1_000551_00_bdnet_2.jpg}} \hspace*{0.1cm} \subfloat{\includegraphics[width=1.4cm, height=3.0cm]{figs/0001_c3s1_000551_00_bdnet_3.jpg}} \hspace*{0.1cm} \subfloat{\includegraphics[width=1.4cm, height=3.0cm]{figs/0001_c3s1_000551_00_topbdnet_2.jpg}}\hspace*{0.1cm} \subfloat{\includegraphics[width=1.4cm, height=3.0cm]{figs/0001_c3s1_000551_00_topbdnet_3.jpg}} \\ \subfloat[input image]{\includegraphics[width=1.4cm, height=3.0cm]{figs/0003_c4s6_015641_00_bdnet_1.jpg}} \hspace*{0.1cm} \subfloat[baseline]{\includegraphics[width=1.4cm, height=3.0cm]{figs/0003_c4s6_015641_00_bdnet_2.jpg}} \hspace*{0.1cm} \subfloat[baseline]{\includegraphics[width=1.4cm, height=3.0cm]{figs/0003_c4s6_015641_00_bdnet_3.jpg}} \hspace*{0.1cm} \subfloat[ours]{\includegraphics[width=1.4cm, height=3.0cm]{figs/0003_c4s6_015641_00_topbdnet_2.jpg}} \hspace*{0.1cm} \subfloat[ours]{\includegraphics[width=1.4cm, height=3.0cm]{figs/0003_c4s6_015641_00_topbdnet_3.jpg}} \caption{Comparison of activation maps generated by the proposed method and a baseline~\cite{dai2019batch}. The first column shows the input images, the second and fourth columns present the activation maps that overlap the input images, and the third and fifth columns show a mask generated by thresholding the activation maps.} \label{fig:comp-activation-baseline} \end{figure} Contrasting our Top-DB-Net with BDB Network~\cite{dai2019batch}, there are three differences: (i) instead of dropping random features, our method drops only features with top (the largest) activations, which stimulates the network to maintain performance using only features with inferior discriminative power (the lowest activations), (ii) rather than using the same drop mask for every feature map in the batch, our method creates an independent drop mask for every input based on its top activations, and (iii) dropping top activated features creates noise inside the second stream (Figure~\ref{fig:dropmask-comparison}), thus we introduce a third stream that forces the features before the dropping step to be still discriminative for ReID, which works as a regularizer due to the multi-task principle~\cite{goodfellow2016deep}. We use the same definition for 'batch' as Dai et al\onedot~\cite{dai2019batch}, that is, ``group of images participating in a single loss calculation during training''. The intuition of why our implementation is better can be explained by analyzing Figure~\ref{fig:dropmask-comparison}. For an input image, we can see that the major activations are over the upper body. BDB Network~\cite{dai2019batch} creates a random drop mask that, in this case, removes the lower body during training. This would encourage the network to continue focusing on the upper body. On the other hand, our method controls which regions are being dropped and encourages the network to learn from the lower body. Our results show that this helps during the learning process (Figure~\ref{fig:activation-epoch}) and generates activation maps better spread over the foreground (Figure~\ref{fig:comp-activation-baseline}). \begin{figure}[!htb] \captionsetup[subfigure]{labelformat=empty} \centering \subfloat[Input image]{\includegraphics[width=1.8cm, height=3.2cm]{figs/0680_c6s2_042893_00_person.jpg}} \hspace*{0.2cm} \subfloat[Activation]{\includegraphics[width=1.8cm, height=3.2cm]{figs/0680_c6s2_042893_00_activation.jpg}} \hspace*{0.2cm} \subfloat[BDB drop mask]{\includegraphics[width=1.8cm, height=3.2cm]{figs/0680_c6s2_042893_00_baseline_drop.jpg}} \hspace*{0.2cm} \subfloat[Our drop mask]{\includegraphics[width=1.8cm, height=3.2cm]{figs/0680_c6s2_042893_00_top_drop.jpg}} \caption{Input image, its activation map after epoch 120 and drop masks. BDB creates a random drop mask, while our method creates a mask that drops most activated regions.} \label{fig:dropmask-comparison} \end{figure} The evaluation of our proposed method is conducted through extensive experiments on three widely used datasets for ReID. We consider the BDB Network~\cite{dai2019batch} as a baseline for our work and demonstrate that our Top-DB-Net outperforms it by up to 4.7\% in the CUHK03 dataset~\cite{li2014deepReID}. Moreover, our results show competitive results against state-of-the-art approaches. In Section~\ref{sec:background}, we discuss the evolution of the ReID task and review relevant related work. In Section~\ref{sec:method}, we introduce the Top-DB-Net. In Section~\ref{sec:results}, we describe our experiments and evaluate the results achieved in three challenging datasets. Finally, concluding remarks and directions for future work are presented in Section~\ref{sec:conclusions}. \section{Background} \label{sec:background} The term ReID was first stated by Zajdel et al\onedot~\cite{zajdel2005keeping} as a variation of people tracking problem. However, unlike tracking algorithms, ReID does not depend on the hypotheses of constancy. Thus, it is a more complicated problem due to considerable variations in biometric profile, position, appearance and point of view~\cite{vezzani2013people}. Many initial works in ReID considered it as a classification task. This is mainly because most datasets~\cite{gray2008viewpoint} available at that time had just a few instances of each person. Because of this, various methods based on handcrafted features~\cite{corvee2010person,cheng2011custom,hirzer2012dense,hirzer2012person,leng2015person} were initially proposed. With the popularization of deep learning and ReID, many datasets with larger amounts of instances per person in real-world scenarios have been made available~\cite{zheng2015scalable,li2014deepReID,zhong2017re,zheng2017unlabeled,ristani2016MTMC} and deep networks-based methods had become the standard~\cite{torchreid,zhou2019osnet}. This had two side effects: (i) the most popular datasets already include a predefined training and testing split -- which helps with validation protocols and comparison between methods -- and (ii) ReID turned into a retrieval problem -- thus, measures such as Cumulated Matching Characteristics (CMC) and Mean Average Precision (mAP) are widely used. Various methods proposed for ReID use specific prior related to person's nature, such as pose and body parts~\cite{quispe2019improved,kumar2017pose,zheng2019pose,li2017learning,cheng2016person}. However, labels such as segmented semantic regions and body skeleton that are necessary for these types of methods are not available in current ReID datasets. Thus, they usually leverage datasets proposed for other tasks captured in different domains, which introduces noise during training and makes the learning process more complicated. On the other hand, there are methods~\cite{dai2019batch,li2018harmonious,hou2019interaction,xia2019second} that learn to encode rich information directly from the input images without relying on other types of signals. Our work follows this strategy. Most of the methods in this category use the concept of attention in their pipeline. Thus, their approaches expect networks to learn to focus on discriminative regions and encode those parts. However, assuming that the availability of consistent discriminative regions may introduce errors, since occlusions are a major problem in the context of ReID due to drastic view changes. The discriminative regions that can be used to match two people may not be available in all instances, such that the approaches require to maintain performance without relying on the availability of high discriminability regions or, in other words, being able to encode richer information from less discriminative regions. In this sense, we propose a method that aims to simulate this scenario by dropping top activated (most discriminative) regions and reinforcing the network to perform ReID with only less discriminative regions available. To further improve ReID performance, literature have proposed re-ranking~\cite{zhong2017re,saquib2018pose} and augmentation~\cite{zheng2019joint,zhong2018camstyle} approaches. The former methods can improve ReID results by a huge margin, which makes it unfair to compare pipelines using them against pipelines not using them. Therefore, since various state-of-the-art methods report results with and without re-ranking, our comparison to them is made separately for these two scenarios. \begin{figure*}[!htb] \centering \includegraphics[width=0.9\linewidth]{figs/architecture-eps-converted-to.pdf} \caption{Proposed Top DropBlock Network (Top-DB-Net). It is composed of three streams that are able to focus on reliable parts of the input and encode low informative regions with high discriminative features for enhanced performance. It is trained using triplet loss and cross entropy. During the testing stage, the outputs of Global and Top DropBlock streams are concatenated.} \label{fig:architecture} \end{figure*} \section{Proposed method} \label{sec:method} This section describes our Top DropBlock Network (Top-DB-Net) for addressing the ReID problem. We first introduce our baseline based on BDB Network~\cite{dai2019batch}. Then, we present each of the three streams of our Top-DB-Net and the loss functions used to train our model. The combination of these streams leads to improvements in the final performance and activation maps. \subsection{Baseline} We decided to use BDB Network~\cite{dai2019batch} as the baseline for our proposal because of its similarity with our approach. BDB Network uses ResNet-50~\cite{he2016deep} as backbone as in many ReID works, however, a slight variation is made by removing the last pooling layer. Thus, a larger feature map is obtained, more specifically, with a size of 2048${\mkern1mu\oldtimes\mkern1mu}$24${\mkern1mu\oldtimes\mkern1mu}$8. On top of the backbone, two streams are used. The first stream, also known as global stream, appends a global average pooling layer to obtain a 2048-dimensional feature vector. Then, a 1${\mkern1mu\oldtimes\mkern1mu}$1 convolution layer is used to further reduce the dimensions. The second stream, named as Batch DropBlock, \textit{randomly} removes regions on training batches. We denote this dropping module as Batch DropBlock. Then a global maximum pooling layer is appended by creating a 2048-dimensional feature vector. A maximum pooling helps to dismiss the effect of dropped regions. Finally, a fully connected layer is used to reduce the feature vector to 1024 dimensions. Batch DropBlock is defined to remove a region of a pre-established size based on a ratio of input images. Since BDB Network~\cite{dai2019batch} reports the best results in regions with a third of height and the same width as the feature map, our Top DropBlock is defined specifically for the same scenario, this is, removing horizontal stripes. \subsection{Top-DB-Net} Our proposed network shares the same backbone as the baseline. Global, Top DropBlock and regularizer streams (Figure~\ref{fig:architecture}) are then appended. Global streams aim to extract general features directly from the backbone, following various previous approaches~\cite{quispe2019improved,dai2019batch,luo2019bag}. The Top DropBlock stream appends two BottleNeck layers~\cite{he2016deep} to the backbone stream and removes horizontal stripes from the most activated regions in order to push the network to maintain discriminability with less relevant data. Given a training batch of $n$ images, the most activated (the most informative) stripes are defined for each image independently: the backbone outputs $n$ feature maps $F$ of size $c {\mkern1mu\oldtimes\mkern1mu} h {\mkern1mu\oldtimes\mkern1mu} w$, where $c$, $h$ and $w$ indicates channels, height and width respectively. We transform $F$ into an activation map $A$ based on the definition proposed by Zagoruyko et al\onedot~\cite{zagoruyko2016paying}: \begin{equation} \label{equ:activation-maps} A = \displaystyle\sum_{i=1}^c\abs{F_i}^p \end{equation} \noindent where $F_i$ represents every tensor slide of size $h {\mkern1mu\oldtimes\mkern1mu} w$. Assuming that $p > 1$ by definition~\cite{zagoruyko2016paying}, we will see that $p$ value is not relevant to our approach. Based on $A$, we define the relevance $R$ of each stripe $r_j$ as the average of the values on row $j$: \begin{equation} \label{equ:stripe-relevance} r_j = \frac{\displaystyle\sum_{k=1}^w A_{j, k}}{w} \end{equation} Finally, we can zero out rows with the largest $r_j$ values. We denote this module as Top DropBlock. For the dropping process, we create a binary mask TDM, named Top Drop Mask, of size $c {\mkern1mu\oldtimes\mkern1mu} h {\mkern1mu\oldtimes\mkern1mu} w$ for every feature map $F$ and apply the dot product between TDM and $G$, where $G$ is a tensor with the same size as $F$, which is the result of applying two BottleNeck layers~\cite{he2016deep} on $F$: \begin{equation} \label{equ:stripe-equivalence1} \text{TDM}_{i, j, k} = \begin{cases} 0, & \text{if}\ r_j \in \text{the largest values} \\ 1, & \text{otherwise} \end{cases} \end{equation} \noindent such that $1 \leq i \leq c$ and $1 \leq k \leq w$. It is worth mentioning that, from Equations~\ref{equ:activation-maps} to~\ref{equ:stripe-relevance}, $r_j$ can be expressed as: \begin{equation} \label{equ:stripe-equivalence2} r_j = \frac{\displaystyle\sum_{i=1}^c\sum_{k=1}^w \abs{F_{i, j, k}^p}}{w} \end{equation} Thus, the value of $p$ is not relevant because $\abs{x}^p \leq \abs{x}^{p+1}$ for every $p > 1$ and we use $r_j$ specifically for ranking. Due to the $\abs{.}$ function in the $r_j$ definition, the most relevant stripes represent areas in $F$ with values besides zero, both positives and negatives. We can consider those to hold more discriminative information. By removing them, we push the network to learn to distinguish between samples with less available information, thus enhancing its capabilities to encode low discriminative regions. However, if the dropped regions are too large, Top DropBlock can create noise in $G$ due to false positives generated by removing regions that represent unique regions between different ID inputs. To alleviate this problem, we propose a regularizer stream that will help maintain performance based on the multi-task principle~\cite{goodfellow2016deep}. This stream is only used in the training. It appends a global average pooling layer to $G$ and is then trained for ReID. Thus, it encourages $G$ to keep the information relevant to the ReID. The loss function used for the three streams is the cross entropy with the label smoothing regularizer~\cite{szegedy2016rethinking} and triplet loss with hard positive-negative mining~\cite{hermans2017defense}. During the testing process, the output of global and Top DropBlock streams are concatenated. \begin{table*}[!htb] \renewcommand{\arraystretch}{0.86} \setlength{\tabcolsep}{3.0mm} \centering \caption{Influence of Top-DB-Net streams and comparison with baseline.} \label{table:ablation} \begin{tabular}{lcccccccc} \toprule & \multicolumn{2}{c}{\textbf{Market1501}} & \multicolumn{2}{c}{\textbf{DukeMTMC-ReID}} & \multicolumn{2}{c}{\textbf{CUHK03 (L)}} & \multicolumn{2}{c}{\textbf{CUHK03 (D)}}\\ \midrule \textbf{Method} & \textbf{mAP} & \textbf{rank-1} & \textbf{mAP} & \textbf{rank-1} & \textbf{mAP} & \textbf{rank-1} & \textbf{mAP} & \textbf{rank-1} \\ \midrule no-drop Top-DB-Net & 84.7 $\pm$ 0.1 & 94.4 $\pm$ 0.3 & 72.7 $\pm$ 0.2 & 86.1 $\pm$ 0.3 & 70.7 $\pm$ 0.4 & 73.8 $\pm$ 0.6 & 68.4 $\pm$ 0.4 & 71.9 $\pm$ 0.3 \\ no-reg Top-DB-Net & 83.9 $\pm$ 0.1 & 93.9 $\pm$ 0.2 & 71.1 $\pm$ 0.2 & 86.1 $\pm$ 0.4 & 71.4 $\pm$ 0.4 & 74.6 $\pm$ 0.8 & 69.4 $\pm$ 0.4 & 73.5 $\pm$ 1.0 \\ Top-DB-Net & 85.8 $\pm$ 0.1 & 94.9 $\pm$ 0.1 & 73.5 $\pm$ 0.2 & 87.5 $\pm$ 0.3 & 75.4 $\pm$ 0.2 & 79.4 $\pm$ 0.5 & 73.2 $\pm$ 0.1 & 77.3 $\pm$ 0.5 \\ Baseline & 85.2 $\pm$ 0.1 & 94.1 $\pm$ 0.1 & 73.2 $\pm$ 0.2 & 85.6 $\pm$ 0.3 & 72.2 $\pm$ 0.3 & 74.7 $\pm$ 0.6 & 70.3 $\pm$ 0.2 & 73.7 $\pm$ 0.4 \\ \bottomrule \end{tabular} \end{table*} \section{Experimental Results} \label{sec:results} This section describes and discusses the main aspects related to implementation details, validation protocols and experimental results. An ablation study is carried out to analyze the effects of the Regularization and Top DropBlock streams on the Top-DB-Net. Then, we compare the results to our baseline and discuss the effects of our dropping top activation during the learning process. Finally, we compare our method to state-of-the-art approaches. \subsection{Implementation Details} All our experiments were conducted on a single Tesla v100 GPU. Due to this, we updated two items in the baseline code\footnote{We used author's~\cite{dai2019batch} original source code available at \url{https://github.com/daizuozhuo/batch-DropBlock-network}}: (i) we trained it with batch size of 64, instead of 128, and (ii) we reduced the learning rate by a factor of 0.5${\mkern1mu\oldtimes\mkern1mu}$ because of the ``linear scaling rule''~\cite{goyal2017accurate} to minimize the effects of training with smaller batch size. During the training step, input images are resized to 384${\mkern1mu\oldtimes\mkern1mu}$128 pixels and augmented by random horizontal flip, random zooming and random input erasing~\cite{ghiasi2018DropBlock}. As mentioned previously, our Top DropBlock stream removes horizontal stripes, thus width dropping ratio is 1. Following our baseline configuration, we use a height drop ratio of 0.3. During the testing step, no drop is applied. Top-DropDB-Net follows the same training setup than our baseline, based on Adam Optimizer~\cite{kingma2014adam} and a linear warm-up~\cite{goyal2017accurate} in the first 50 epochs with initial value of $1e-3$, then decayed to $1-e4$ and $1e-5$ after 200 and 300 epochs, respectively. The training routine takes 400 epochs. Due to the randomness of the drop masks used in our baseline and the methods used for data augmentation, we performed each experiment 5 times and reported the mean and standard deviation. This will allow for a fairer comparison between our method, baseline and ablation pipelines. To combine cross entropy loss with label smoothing regularizer~\cite{szegedy2016rethinking} and triplet loss with hard positive-negative mining~\cite{hermans2017defense}, we used the neck method~\cite{luo2019bag}. \begin{figure}[!htb] \captionsetup[subfigure]{labelformat=empty} \centering \subfloat{\includegraphics[width=1.3cm, height=2.3cm]{figs/1224_c2s3_008107_00_person.jpg}} \hspace*{0.1cm} \subfloat[120]{\includegraphics[width=1.3cm, height=2.3cm]{figs/1224_c2s3_008107_00_top_120.jpg}} \hspace*{0.1cm} \subfloat[240]{\includegraphics[width=1.3cm, height=2.3cm]{figs/1224_c2s3_008107_00_top_240.jpg}} \hspace*{0.1cm} \subfloat[400]{\includegraphics[width=1.3cm, height=2.3cm]{figs/1224_c2s3_008107_00_top_400.jpg}} \\ \subfloat{\includegraphics[width=1.3cm, height=2.3cm]{figs/1324_c2s3_030207_00_person.jpg}} \hspace*{0.1cm} \subfloat[120]{\includegraphics[width=1.3cm, height=2.3cm]{figs/1324_c2s3_030207_00_top_120.jpg}} \hspace*{0.1cm} \subfloat[240]{\includegraphics[width=1.3cm, height=2.3cm]{figs/1324_c2s3_030207_00_top_240.jpg}} \hspace*{0.1cm} \subfloat[400]{\includegraphics[width=1.3cm, height=2.3cm]{figs/1324_c2s3_030207_00_top_400.jpg}} \caption{Activation maps for Top-DB-Net in two images at different epochs. The number below the images indicates the epoch.} \label{fig:activation-examples} \end{figure} \subsection{Datasets} We evaluate our framework on three widely used datasets. DukeMTMC-ReID dataset~\cite{zheng2017unlabeled,ristani2016MTMC} has hand-drawn bounding boxes with various backgrounds of outdoor scenes. Market1501 dataset~\cite{zheng2015scalable} aims to simulate a more real-world scenario and was generated through the Deformable Part Model (DPM)~\cite{felzenszwalb2009object}. CUHK03 dataset~\cite{li2014deepReID} exhibits recurrently missing body parts, occlusions and misalignment; we tested its two versions: detected (CUHK03 (D)) and labeled (CUHK03 (L)). For training and testing, we follow the standard train/test split proposed by the dataset authors~\cite{zheng2017unlabeled,ristani2016MTMC,felzenszwalb2009object, li2014deepReID}. In the case of CUHK03, we use the new partition~\cite{zhong2017re} of 767/700, which makes this dataset more challenging. Results for each dataset are based on mean Average Precision (mAP) and Cumulative Matching Curve (CMC), more specifically, rank-1. \subsection{Ablation Study} We evaluate the effects of Top DropBlock and Regularization streams. Furthermore, we discuss the effects of Top DropBlock during the learning process and compare it to our baseline. \subsubsection{\textbf{Influence of the Top DropBlock Stream}} In this section, we aim to analyze the effect of our Top DropBlock stream. We train Top-DB-Net by removing the DropBlock stream and maintaining the global and regularization streams using the two Bottleneck layers. We refer to this version as \textit{no-drop Top-DB-Net}. During testing, we concatenate the output of global and regularization branches because both streams are trained with the same loss function. Results for this comparison are shown in Table~\ref{table:ablation}. In all datasets, we can see that removing the Top DropBlock stream decreases performance, which is also true for the standard deviation. On the Market1501~\cite{zheng2015scalable} and DukeMTMC-ReID~\cite{zheng2017unlabeled,ristani2016MTMC} datasets, the difference is usually less than 1\% for mAP and rank-1. However, on the CUHK03~\cite{li2014deepReID,zhong2017re} dataset, we can observe significant differences: performance decreases 4.7\% in mAP and 5.6\% in rank-1 on CUHK03(L) and decreases 4.8\% in mAP and 5.4\% in rank-1 on CUHK03(D). The difference in effects between datasets may be related to the fact that CUHK03 is a more challenging benchmark. This same pattern is repeated when analyzing the effect of our Regularization stream and baseline. These results are expected because the global and regularization streams follow the same optimization logic: push the backbone to encode relevant ReID information from the input images. On the other hand, when we use our Top DropBlock stream, we further encourage the backbone to recognize relevant regions and learn to describe less informative regions with richer features. \subsubsection{\textbf{Influence of the Regularization Stream}} In this section, our goal is to show that the regularization stream, in fact, helps to deal with the noise generated by the dropping step. For this purpose, we train a version of the Top-DB-Net without this stream, named \textit{no-reg Top-DB-Net} and compare it to the proposed Top-DB-Net. We can see in Table~\ref{table:ablation} a clear difference when using the regularization stream. Using our regularization stream, we observe improvements of 1.9\% and 1\% for mAP and rank-1, respectively, on Market1501 dataset~\cite{zheng2015scalable}. DukeMTMC-ReID~\cite{zheng2017unlabeled,ristani2016MTMC} also shows improvements of 2.4\% for mAP and 1.4\% for rank-1. Similar to previous ablation analysis, the most substantial changes are for CUHK03~\cite{li2014deepReID,zhong2017re}: we can observe improvements of 4.8\% for rank-1 and 4\% for mAP on CUHK03(L), and 3.8\% for rank-1 and mAP on CUHK03(D). \subsubsection{\textbf{Random DropBlock vs Top DropBlock}} Results in Table~\ref{table:ablation} show that our Top-DB-Net is better than our baseline in almost all metrics. The only metric with similar performance is mAP for DukeMTMC-ReID. The biggest differences are again on CUHK03~\cite{li2014deepReID,zhong2017re} dataset, with up to 4.7\% improvement for rank-1 and 3.2\% for mAP when using our Top-DB-Net. To further understand the difference in performance, we explore activation maps and their relation with the core of our method and the baseline: DropBlocks. Figure~\ref{fig:DropBlock_vs_topDropBlock} shows the differences between the two dropping methods. \begin{figure}[!htb] \centering \subfloat[Random DropBlock (Baseline)]{\includegraphics[width=5.6cm]{figs/DropBlock-eps-converted-to.pdf}} \\ \subfloat[Top DropBlock (Ours)]{\includegraphics[width=5.6cm]{figs/topDropBlock-eps-converted-to.pdf}} \caption{Differences between the Batch DropBlock and proposed Top DropBlock.} \label{fig:DropBlock_vs_topDropBlock} \end{figure} \begin{figure*}[!htb] \centering query\hspace{0.9cm} rank-1 \hspace{0.1cm} rank-2 \hspace{0.1cm} rank-3 \hspace{0.5cm} query\hspace{0.9cm} rank-1 \hspace{0.1cm} rank-2 \hspace{0.1cm} rank-3 \hspace{0.5cm} query\hspace{0.9cm} rank-1 \hspace{0.1cm} rank-2 \hspace{0.1cm} rank-3 \subfloat[Baseline epoch 120]{\includegraphics[width=0.3\linewidth, height=4.5cm]{figs/0191_c3s3_078444_00_baseline_120.jpg}} \hspace*{0.5cm} \subfloat[Baseline epoch 240]{\includegraphics[width=0.3\linewidth, height=4.5cm]{figs/0191_c3s3_078444_00_baseline_240.jpg}} \hspace*{0.5cm} \subfloat[Baseline epoch 400]{\includegraphics[width=0.3\linewidth, height=4.5cm]{figs/0191_c3s3_078444_00_baseline_400.jpg}} \\[0.2cm] query\hspace{0.9cm} rank-1 \hspace{0.1cm} rank-2 \hspace{0.1cm} rank-3 \hspace{0.5cm} query\hspace{0.9cm} rank-1 \hspace{0.1cm} rank-2 \hspace{0.1cm} rank-3 \hspace{0.5cm} query\hspace{0.9cm} rank-1 \hspace{0.1cm} rank-2 \hspace{0.1cm} rank-3 \subfloat[{Top-DB-Net} epoch 120]{\includegraphics[width=0.3\linewidth, height=4.5cm]{figs/0191_c3s3_078444_00_top_120.jpg}} \hspace*{0.5cm} \subfloat[{Top-DB-Net} epoch 240]{\includegraphics[width=0.3\linewidth, height=4.5cm]{figs/0191_c3s3_078444_00_top_240.jpg}} \hspace*{0.5cm} \subfloat[{Top-DB-Net} epoch 400]{\includegraphics[width=0.3\linewidth, height=4.5cm]{figs/0191_c3s3_078444_00_top_400.jpg}} \caption{Comparison of activation and rank-3 evolution. The top and bottom sets show images for our baseline and our proposed method, respectively. We can see that using Top DropBlock, instead of Random DropBlock, makes the activations more spread out over the person, which helps to create a better feature representation. Correct results are highlighted in green, whereas incorrect results are highlighted in red.} \label{fig:activation-epoch} \end{figure*} In Figure~\ref{fig:activation-epoch}, we compare the evolution of rank-3 at different epochs for our Top-DB-Net and baseline. We also show the evolution of the activation maps. This example shows that our Top DropBlock improves the dispersion of activation maps in the foreground and the feature extraction from images. At 120th epoch, the activations of the query are similarly spread over the upper body and feet, both in the baseline and our method. However, we can see that, in the gallery, our method is better spread across the lower body, causing Top-DB-Net to incorrectly obtain rank-1/2, confusing a person who shares pants similar to the query. At 240th epoch, we can see that the baseline activations for the query have barely changed. Moreover, because it focuses only on the upper-body and feet, it is confused with images of a person with a similar upper body, but wearing a squirt with similar color instead of pants. On the contrary, our Top-DB-Net changed its activations for the query between 120th and 240th epochs, and also focuses on the lower body. For this specific example, this is because our Top DropBlock removes the upper body regions and pushes the backbone to learn from the lower body since the 120th epoch, which helps to correctly match rank-1/2/3. It is also possible to notice that, because our Top DropBlock pushes the network to describe low informative regions with rich features, at 240th epoch, our network has better features to describe lower body regions, so it fixes rank-1/2 errors of 120th epoch. Finally, at 400th epoch, the baseline has still changed very little the distribution of its activations and still focuses only on the upper body and feet. It is able to obtain correct rank-2. On the other hand, our method still focuses on the entire body, retrieves the same correct baseline rank-2 and offers more similarity\footnote{Shortest Euclidean distance between features from query and gallery images.} to two images that show a strong viewpoint change and occlusions. This shows the improvement of the feature discriminability between 240th and 400th epochs. \begin{table*}[!htb] \renewcommand{\arraystretch}{0.86} \setlength{\tabcolsep}{2.5mm} \centering \caption{Comparison to the state-of-the-art approaches. RK stands for re-ranking~\cite{zhong2017re}. The sub-index indicates the ordinal position of this result (for instance, $x_3$ indicates that $x$ is the third best result).} \label{table:comparison-state-of-art} \begin{tabular}{lllllllll} \toprule & \multicolumn{2}{c}{\textbf{Market1501}} & \multicolumn{2}{c}{\textbf{DukeMTMC-ReID}}& \multicolumn{2}{c}{\textbf{CUHK03 (L)}} & \multicolumn{2}{c}{\textbf{CUHK03 (D)}} \\ \midrule \textbf{Method} & \textbf{mAP} & \textbf{rank-1} & \textbf{mAP} & \textbf{rank-1} & \textbf{mAP} & \textbf{rank-1} & \textbf{mAP} & \textbf{rank-1} \\ \midrule BoT~\cite{luo2019bag} & 85.9$_5$ & 94.5 & 76.4 & 86.4 & -- & -- & -- & -- \\ PyrNet~\cite{martinel2019aggregating} & 86.7 & 95.2$_3$ & 74.0 & 87.1 & 68.3 & 71.6 & 63.8 & 68.0 \\ Auto-ReID~\cite{quan2019auto} & 85.1 & 94.5 & -- & -- & 73.0 & 77.9 & 69.3 & 73.3 \\ MGN~\cite{wang2018learning} & 86.9$_4$ & 95.7$_1$ & 78.4$_3$ & 88.7$_4$ & 67.4 & 68.0 & 66.0 & 66.8 \\ DenSem~\cite{Zhang_2019_CVPR} & 87.6$_3$ & 95.7$_1$ & 74.3 & 86.2 & 75.2 & 78.9 & 73.1 & 78.2$_3$ \\ IANet~\cite{hou2019interaction} & 83.1 & 94.4 & 73.4 & 87.1 & -- & -- & -- & -- \\ CAMA~\cite{yang2019towards} & 84.5 & 94.7 & 72.9 & 85.8 & -- & -- & -- & -- \\ MHN~\cite{chen2019mixed} & 85.0 & 95.1$_4$ & 77.2 & 89.1$_2$ & 72.4 & 77.2 & 65.4 & 71.7 \\ ABDnet~\cite{chen2019abd} & 88.2$_2$ & 95.6$_2$ & 78.5$_2$ & 89.0$_3$ & -- & -- & -- & -- \\ SONA~\cite{xia2019second} & 88.6$_1$ & 95.6$_2$ & 78.0 & 89.2$_1$ & 79.2$_1$ & 81.8$_1$ & 76.3$_1$ & 79.1$_1$ \\ OSNet~\cite{zhou2019osnet} & 84.9 & 94.8 & 73.5 & 88.6$_5$ & -- & -- & 67.8 & 72.3 \\ Pyramid~\cite{zheng2019pyramidal} & 88.2$_2$ & 95.7$_1$ & 79.0$_1$ & 89.0$_3$ & 76.9$_2$ & 78.9 & 74.8$_2$ & 78.9$_2$ \\ Top-DB-Net (Ours) & 85.8$_6$ & 94.9$_5$ & 73.5 & 87.5$_6$ & 75.4$_3$ & 79.4$_2$ & 73.2$_3$ & 77.3$_4$ \\ \midrule SSP-ReID+RK~\cite{quispe2019improved} & 90.8 & 93.7 & 83.7 & 86.4 & 77.5 & 74.6 & 75.0 & 72.4 \\ BoT+RK~\cite{luo2019bag} & 94.2$_1$ & 95.4 & 89.1$_1$ & 90.3$_2$ & -- & -- & -- & -- \\ PyrNet+RK~\cite{martinel2019aggregating} & 94.0 & 96.1$_1$ & 87.7 & 90.3$_2$ & 78.7$_2$ & 77.1$_2$ & 82.7$_2$ & 80.8$_2$ \\ Auto-ReID+RK~\cite{quan2019auto} & 94.2$_1$ & 95.4 & -- & -- & -- & -- & -- & -- \\ Top-DB-Net+RK (Ours) & 94.1$_2$ & 95.5$_2$ & 88.6$_2$ & 90.9$_1$ & 88.5$_1$ & 86.7$_1$ & 86.9$_1$ & 85.7$_1$ \\ \bottomrule \end{tabular} \end{table*} Activation plots are useful for the interpretability of networks. In our case, our plots are generated following Equation~\ref{equ:activation-maps}. This equation is also used to define our Top DropBlock and Top Drop masks. This shows that the same tool used for interpretability can also be applied during the learning process to enhance discriminability (Table~\ref{table:ablation}). In addition to quantitative improvements, we observe a clear improvement in the quality of regions where backbone is concentrated. As shown in Figures~\ref{fig:activation-examples} and~\ref{fig:activation-epoch}, there is a consistent and significant activation improvement between 120th and 240th epochs, when they start to focus on broader body parts. From 240th to 400th epochs, we can see that the activations become more stable and well spread out in the foreground, but with an enhanced discriminability. We use the activation definition of Zagoruyko et al\onedot~\cite{zagoruyko2016paying} because it adjusts to our network pipeline and drop objective. However, there is a previous work for ReID~\cite{yang2019towards} that uses CAM~\cite{zhou2016learning}, an activation definition that introduces weights for each channel to enhance the scope of network activation. Previous literature and our findings suggest that methods used for interpretability may be useful to improve ReID and network activation in general. \subsection{State-of-the-Art Comparison} Our method focuses on ReID using information extracted only from input images. Thus, in our comparison to the state-of-the-art, we consider methods in a similar way, for instance, Zhuet al\onedot~\cite{zhu2020aware} used the camera ID and Wanget al\onedot~\cite{wang2019spatial} used the image time-stamp during training. This extra information may bias the models to learn the mapping between the camera and views or the time needed for a person to move from different viewpoints, instead of extracting reliable information from images, so that they are not included in our comparison. Table~\ref{table:comparison-state-of-art} shows a comparison between our method and state-of-the-art approaches. We compare the results separately when using re-ranking~\cite{zhong2017re}. Our results are among the top-6 results for both mAP and rank-1 on Market1501. We have a similar performance for rank-1 on DukeMTMC-ReID, however, for mAP, we achieved results comparable to state-of-the-art methods, such as OSNet~\cite{zhou2019osnet}, CAMA~\cite{yang2019towards} and IANet~\cite{hou2019interaction}. We obtained the second best rank-1 on CUHK03(L), third best mAP on both versions of CUHK03 and fourth best rank-1 on CUHK03(D). When using re-ranking, our method achieved state-of-the-art results on CUHK03(L) and CUHK03(R) in both mAP and rank-1, as well as best results for rank-1 on DukeMTMC-ReID, second best mAP on DukeMTMC-ReID and second best on Market1501 in both mAP and rank-1. \section{Conclusions and Future Work} \label{sec:conclusions} In this paper, we introduced Top-DB-Net, a network for the person re-identification problem based on Top DropBlock. Top-DB-Net encourages the network to improve its performance by learning to generate rich encoding based on low informative regions. It consists of three streams: a global stream that follows standard feature encoding for the backbone, the Top DropBlock that pushes the network to maintain its performance while using less discriminative regions by dropping most activated parts of the feature map, and a regularization stream that helps to deal with the noise created by the dropping process. Extensive experiments conducted on three widely datasets demonstrated the power of our method to achieve competitive results and its capability to generate better activation maps than competing methods. Moreover, our results suggest that methods proposed for interpretability of activation maps can help during training in ReID. As directions for future work, we expect to extend the definition of Top DropBlock to various dropping ratios, instead of only horizontal stripes. Furthermore, we intend to encode higher level features (for instance, gender) and analyze their impact on the ReID task. \section*{Acknowledgments} \label{acknowledgment} Part of this work was done while the first author was affiliated with Microsoft Corp. We are thankful to Microsoft Research, S\~ao Paulo Research Foundation (FAPESP grant \#2017/12646-3), National Council for Scientific and Technological Development (CNPq grant \#309330/2018-1) and Coordination for the Improvement of Higher Education Personnel (CAPES) for their financial support. \balance \bibliographystyle{IEEEtran}
{'timestamp': '2020-10-13T02:28:04', 'yymm': '2010', 'arxiv_id': '2010.05435', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05435'}
arxiv
\section{Introduction} Regression modeling, which refers to building models to learn conditional relationship between output targets and input features on some training samples, is a fundamental problem in statistics and machine learning. Some classical regression modeling approaches include least square regression, logistic regression and Poisson regression; see, e.g.,~\citet{bishop2006pattern},~\citet{kubat2015introduction},~\citet{fahrmeir2013regression} and the references therein. The aforementioned classic approaches usually train a single model of a single target over the entire data set. However, real-world problems can be much more complicated. In particular, the needs of utilizing high-dimensional features, population heterogeneity, and multiple interrelated targets are among the most prominent complications. To handle high-dimensional data, the celebrated regularized estimation approaches have undergone exciting developments in recent years; see, e.g.,~\citet{FanLv2010} and~\citet{Huang2012}. In the presence of population heterogeneity, the samples may form several distinct clusters corresponding to mixed relationships between the targets and the features. A popular modeling strategy in such a scenario is the {\em Finite Mixture Regression} (FMR)~\citep{mclachlan2004finite}, which is capable of adaptively learning multiple models, each of which is responsible for one subset/cluster of the data. FMR models have been widely used in market segmentation studies, patients' disease progression subtyping, motif gene-expression research, etc.; see, e.g.,~\citet{stadler2010},~\citet{khalili2011overview},~\citet{khalili2012variable},~\citet{dougru2016parameter}, and the references therein. The problem of joint learning for multiple targets is usually referred to as {\em Multi-Task Learning} (MTL) in machine learning or {\em multivariate learning} in statistics; see, e.g.,~\citet{evgeniou2007multi},~\citet{argyriou2007spectral},~\citet{chen2011integrating}, and~\citet{gong2012multi}. {We stress that the main definition of MTL considers tasks that do not necessarily share the same set of samples (and features), and that this paper focuses on a special case of MTL, where the multivariate outcomes are collected from the same set of samples and share the same set of features, whose reason will be explained later. }There have also been multi-task FMR models, e.g.,~\citet{wedel1995mixture},~\citet{xian2004robust},~\citet{kyung2016robust} and~\citet{bai2016mixture}, which mainly built on certain multivariate probability distribution such as Gaussian distribution or multivariate $t$ distribution. Thus far, a comprehensive study on multi-task mixture-regression modeling with high-dimensional data is still lacking. To tackle this problem for handling real-world applications, there remain several challenges and practical concerns. \begin{itemize} \item {\em Task Heterogeneity}. Current MTL approaches usually assume that the targets are of the same type. However, it is common that the multiple targets are of different types, such as continuous, binary, count, etc., which we refer to as task heterogeneity. For example, in anesthesia decision making~\citep{tan2010decision}, the anesthesia drugs will have impacts on multiple indicators of an anesthesia patient, such as anesthesia depth, blood pressures, heart rates, etc. The anesthesiologist needs to consider all those different aspects as well as their intrinsic dependence before making the decision. \item {\em Task Integration}. As in the anesthesiology example, the multiple tasks are typically inter-related to each other, and the potential benefit from a MTL approach needs to be realized through properly exploring and taking advantage of these relationships. In existing high-dimensional MTL approaches, the tasks are usually integrated by assuming certain shared conditional mean structures between the targets and the features. The problem is more difficult in the presence of both task and population heterogeneities. \item {\em Task Robustness}. Similar to the idea in the robust MTL approaches~\citep{passos2012flexible, gong2012robust, chen2011integrating}, it is not always the case that jointly considering all tasks by assuming certain shared structures among them would be helpful. Certain tasks, referred to as anomaly tasks, may not follow the assumed shared structure and thus can ruin the overall model performance. { More generally, tasks may even cluster into groups with different shared structures.} \end{itemize} In this paper, we propose a novel {method} named {HEterogeneous-target Robust MIxTure regression} (\methodname), to address the above challenges in a unified framework. {Here we explain that we mainly consider the setting{, where} the multivariate outcomes are collected from the same set of samples and share the same set of features because our main objective is to learn potentially shared sample clusters and feature sets among tasks.} Rigorous theoretical analysis and performance guarantees are provided. It is worthwhile to highlight the key aspects of our approach as follows. \begin{itemize} \item Our method handles mixed type of targets simultaneously. Each target follows an exponential dispersion family model~\citep{jorgensen1987exponential}, so that multiple different types of targets, e.g., continuous, binary, and counts, can be handled jointly. The tasks are naturally integrated through sharing the same clustering structure arising from population heterogeneity. Our theory allows~\methodname\, to cover sub-exponential distributions, including the commonly-encountered Bernoulli, Poisson and Gaussian as special cases. \item Our method imposes structural constraints in each mixture component of~\methodname, to deal with the curse of dimensionality and at the same time further take advantage of the interrelationship of the tasks. In particular, the group $\ell_1$ penalization is adopted to perform shared feature selection among tasks within each mixture component. \item Our method adopts {three} strategies for robustness. First, we adopt a mean-shift regularization technique~\citep{she2015robust} to detect the outlier samples automatically and adjust for its outlying effects in model estimation. The second strategy measures discrepancy of different conditional distributions to detect anomaly tasks. {The third strategy measures similarity between each pair of tasks to discover a clustered structure among tasks.} Moreover, our model can work with incomplete data and impute entry-wise missing values in the multiple targets. \end{itemize} The aforementioned key elements, e.g., multi-task learning, sample clustering, shared feature selection, and anomaly detection, are integrated in a unified mixture model setup, so that they can benefit from and reinforce each other. A generalized Expectation-Maximization (GEM)~\citep{neal1998view} algorithm is developed to conduct model estimation efficiently. For theoretical analysis, we generalize the results of~\citet{stadler2010} to establish non-asymptotic oracle performance bounds for~\methodname\, under a high-dimensional learning framework. This is not trivial due to the non-convexity (due to the population heterogeneity) and the target heterogeneity of the problem. The rest of this paper is organized as follows. Section 2 provides a brief review of the background and the related works to our method. Section 3 presents the details of the proposed~\methodname\, model and the computational algorithm. {Section 4 discusses several extensions of our method.} Section 5 shows the theoretical analysis. The empirical evaluations are presented in Section 6, followed by the {discussions and} conclusions in Section 7. \section{Background \& Related Work}\label{sec:related} Let $Y \in \mathcal{Y} \subset \mathbb{R} $ be the output target and $ \x \in \mathcal{X} \subset \mathbb{R}^{ d}$ the input feature vector. GLMs~\citep{nelder1972generalized} postulate that the conditional probability density function of $Y$ given $\x$ is \begin{equation* f(y \mid {\x,\theta}) = f(y \mid \varphi,\phi) = \exp\biggl\{\frac{y\varphi-b(\varphi)}{a(\phi)}+c(y,\phi)\biggr\}, \end{equation*} where $\varphi = \x\trans\bbeta$ with $\bbeta$ being the regression coefficient vector, $\phi$ is a dispersion parameter, and $a(\cdot),b(\cdot),c(\cdot)$ are known functions whose forms are determined by the specific distribution. Here we use $\theta$ to denote the collection of all the unknown parameters, i.e., $\theta = (\bbeta,\phi)$. Least square regression, logistic regression and Poisson regression are all special cases of GLMs. In the presence of {population} heterogeneity, a standard finite mixture model of GLM postulates that the conditional probability density function of $Y$ given $\x$ is \begin{equation* f(y \mid \x,\theta) = \sum_{r=1}^k\pi_r f(y \mid \varphi_r,\phi_{r}), \end{equation*} where $\varphi_r = \x\trans\bbeta_r$ with $\bbeta_r$ being the regression coefficient vector for the $r$th mixture component, and $\pi_r>0 \ (r=1,\dots,k)$ with $\sum_{r=1}^k\pi_r=1$. So FMR model assumes that there are $k$ sub-populations, each of which admits a different conditional relationship between $Y$ and $\x$. \citet{mclachlan2004finite} introduced finite mixture of GLM models. {\citet{bartolucci2005use} considered a special case that $\bbeta_1,\dots,\bbeta_k$ are different only in their first entries.}~\citet{khalili2012variable} discussed using sparse penalties such as Lasso and SCAD to perform feature selection for FMR models and showed asymptotic properties of the penalized estimators.~\citet{stadler2010} reparameterized the finite mixture of Gaussian regression model and used $\ell_1$ penalization to achieve bounded log-likelihood and consistent feature selection. For multiple targets,~\citet{wedel1995mixture} proposed finite mixture of GLM models with multivariate targets. { These methods only consider the univariate-outcome case}.~\citet{weruaga2015sparse} proposed multivariate Gaussian mixture regression and used $\ell_1$ penalty for sparseness of parameters. Besides mixture of GLMs, there have been many works on mixture of other continuous distributions such as $t$ and Laplace distributions, mainly motivated by the needs of robust estimation for handling heavy tailed or skewed continuous distribution; see, e.g.,~\citet{xian2004robust,dougru2016parameter,alfo2016finite,dougru2016robust, kyung2016robust,bai2016mixture}. { However, these methods assume that the targets are of the same type, and only consider interrelationship among tasks with continuous outcomes. Additionally, they all assumed that their FMR model is shared by all the tasks.} In MTL,~\citet{kumar2012learning},~\citet{passos2012flexible},~\citet{gong2012robust},~\citet{chen2011integrating},~\citet{jacob2009clustered},~\citet{chen2010graph} and~\citet{he2011graph} proposed to tackle the problem that different groups of tasks share different information, providing methods to handle anomaly tasks, clustered structure or graph-based structure among tasks.~\cite{yang2009heterogeneous} proposed a multi-task framework to jointly learn tasks with output types of Gaussian and multinomial.~\citet{zhang2012multi} proposed a multi-modal multi-task model to predict clinical variables for regression and categorical variable for classification jointly.~\citet{li2014heterogeneous} proposed a heterogeneous multi-task learning framework to learn a pose-joint regressor and a sliding window body-part detector in a deep network architecture simultaneously. {Nevertheless, these MTL methods cannot handle the heterogeneity of conditional relationship between features and targets. By contrast, the proposed FMR framework~\methodname\, is effective for handling sample heterogeneity with mixed type of tasks whose interrelationship are harnessed by structural constraints. Non-asymptotic theoretical guarantees are provided. It also handles anomaly tasks or clustered structure among tasks, for the case that not all the tasks share the same FMR structure. } \section{HEterogeneous-target Robust MIxTure regression}\label{sec:method} In this section, we first present the formulation of the { main} ~\methodname\ model, followed by penalized likelihood estimators with sparse constraint and structural constraint, respectively. We then introduce the associated optimization procedures, and describe how to perform sample clustering and make imputation of the missing/unobserved outcomes on incomplete multi-target outcomes based on the main model. {Hyper-parameter tuning is discussed at last.} {Various extensions of the main methodology, including strategies to handle anomaly tasks or clustered tasks, will be introduced in Section~\ref{sec:extension}.} \subsection{Model Formulation and Estimation Criterion} Let $\Y\in\mathbb{R}^{n\times m}$ be the output/target data matrix and $\X\in\mathbb{R}^{n\times d}$ the input/feature data matrix, consisting of $n$ independent samples $(\y_i,\x_i)$, $i=1,\ldots, n$. As such, there are $m$ different targets with a common set of $d$ features. We allow $\Y$ to contain missing values at random; define $\Omega_i =\{j\in\{1,\ldots,m\}: y_{ij} \mbox{ is observed.}\}$ be the collection of indices of observed outcome in the $i$th sample $\y_i$ ($\Omega_i\neq \emptyset$), for $i=1,\ldots,n$. To model multiple types of targets, such as continuous, binary, count, etc., we allow $y_{ij}$ to potentially follow different distributions in the exponential-dispersion family, for each $j=1,\ldots, m$. Specifically, we assume that given $\x_i$, the joint probability density function of $\oby_i = \{y_{ij};j\in \Omega_i\}$ is \begin{equation}\label{eq:exp_fm} f(\oby_i \mid \x_i,\theta) = f(y_{ij}, j\in \Omega_i \mid \x_i,\theta) = \sum_{r=1}^k\pi_r\prod_{j\in\Omega_i}f(y_{ij}\mid \varphi_{ijr},\phi_{jr}), \end{equation} where \begin{equation* f(y_{ij}\mid \varphi_{ijr},\phi_{jr}) = \exp\biggl\{\frac{y_{ij}\varphi_{ijr}-b_j(\varphi_{ijr})}{a_j(\phi_{jr})}+c_j(y_{ij},\phi_{jr})\biggr\}, \end{equation*} $\varphi_{ijr}$ is the natural parameter for the $i$th sample of the $j$th target in the $r$th mixture component, $\phi_{jr}$ is the dispersion parameter of the $j$th target in the $r$th mixture component, and the functions $a_j,b_j,c_j \ (j=1,\ldots,m)$ are determined by the specific distribution of the $j$th target. Here, the key assumption is that the $m$ tasks all correspond to the same cluster structure (e.g., the $m$ tasks all have $k$ clusters) determined by the underlying population heterogeneity; given the shared cluster label (e.g., $r$), the tasks within each mixture component then become independent of each other (depicted by the product of their probability density functions). As such, by allowing cluster label sharing, the model provides an effective way to genuinely integrate the learning of the multiple tasks. Following the setup of GLMs, we assume a linear structure in the natural parameters, i.e., \begin{equation}\label{eq:natural_parameter} \varphi_{ijr} = \x_i\bbeta_{jr}, \end{equation} where $\bbeta_{jr}$ is the regression coefficient vector of the $j$th response in the $r$th mixture component. Since $\x_i$ is possibly of high dimensionality, the $\bbeta_{jr}$s are potentially sparse vectors. For example, when the $\bbeta_{jr}$s for $j=1,\ldots,m$ share the same sparsity pattern, the tasks share the same set of relevant features within each mixture component. For $r=1,\ldots,k$, write $\bbeta_r \in \mathbb{R}^{d\times m} = [\bbeta_{1r},\bbeta_{2r},\ldots,\bbeta_{mr}]$ and $\phi_r=[\phi_{1r},\ldots,\phi_{mr}]^T$. Also write $\bbeta\in\mathbb{R}^{(d\times m)\times k} =[\bbeta_1,\ldots, \bbeta_k]$. Let $\theta = \{ \bbeta,\phi_1,\ldots,\phi_k,\pi_1,\ldots,\pi_{k}\}$ collecting all the unknown parameters, with the parameter space given by $ \Theta = \mathbb{R}^{ (d \times m) \times k} \times \mathbb{R}^{m \times k}_{>0} \times \Pi, $ where $\Pi = \{\pi;\pi_r>0 \mbox{ for } r = 1,\ldots,k \mbox{ and } \sum_{r=1}^{k} \pi_r = 1\}$. The data log-likelihood of the proposed model is \begin{equation}\label{eq:loglike} \begin{split} \ell(\theta\mid\Y,\X) & = \sum_{i=1}^n\log\left(\sum_{r=1}^k\pi_r\prod_{j\in\Omega_i}\exp\biggl\{\frac{y_{ij}\varphi_{ijr}-b_j(\varphi_{ijr})}{a_j(\phi_{jr})}+c_j(y_{ij},\phi_{jr})\biggr\}\right). \end{split} \end{equation} The missing values in $\Y$ simply do not contribute to the likelihood, which follows the same spirit as in matrix completion~\citep{candes2009}. The proposed model indeed possesses a genuine multivariate flavor, as the different outcomes share the same underlying latent cluster pattern of the heterogeneous population. We then propose to estimate $\theta$ by the following penalized likelihood criterion: \begin{equation}\label{eq:l1} \hat{\theta} = {\arg\min}_{\theta\in\Theta} \ - \ell(\theta\mid\Y,\X)/n + \mathcal{R}(\bbeta;\lambda), \end{equation} where $\mathcal{R}(\bbeta;\lambda)$ is some certain penalty term on the regression coefficients with $\lambda$ being a tuning parameter. We thus name our proposed method the HEterogeneous-target Robust MIxTure regression (\methodname). The $\mathcal{R}(\bbeta;\lambda)$ can be flexibly chosen based on specific needs of feature selection. The first sparse penalties adopted by our model is the $\ell_1$ norm (lasso-type) penalty, \begin{equation}\label{eq:pen_lasso} \mathcal{R}(\bbeta;\lambda,\pi) = \lambda\sum_{r=1}^k\pi_r^{\gamma}\|\bbeta_r\|_1, \end{equation} where $\lambda$ is the tuning parameter, $\|\cdot\|_1$ is the entry-wise $\ell_1$ norm, and $\pi_r^{\gamma}$s $(r=1,\ldots,k)$ are the penalty weights with $\gamma\in\{0,1/2,1\}$ being a pre-specified constant. Here the penalty also depends on the unknown mixture proportions $\pi$; when the cluster sizes are expected to be imbalanced, using this weighted penalization with some $\gamma>0$ is preferred~\citep{stadler2010}. This entry-wise regularization approach allows the tasks to have independent set of relevant features. Alternatively, in order to enhance the integrative learning and potentially boost the performance of clustering, it could be beneficial to encourage the internal similarity within each sub-population. Then certain group-wise regularization of the features could be considered, which are widely adopted in multi-task learning. In particular, we consider a component-specific group sparsity pattern to achieve shared feature selection among different tasks, in which the group $\ell_1$ norm penalty is used~\citep{gong2012robust,jalali2010dirty}, \begin{align}\label{eq:pen_lasso_group} \mathcal{R}(\bbeta;\lambda,\pi) = \lambda\sum_{r=1}^k\pi_r^{\gamma}\|\bbeta_r\|_{1,2}, \end{align} where $\|\cdot\|_{1,2}$ denotes the sum of the row $\ell_2$ norms of the enclosed matrix, and the weights are constructed as in~\eqref{eq:pen_lasso}. {The shared feature set in each sub-population can be used to characterize the sub-population and render the whole model more interpretable.} \subsection{Optimization}\label{subsec:optimization} We propose a generalized EM (GEM) algorithm~\citep{dempster1977maximum} to solve the minimization problem in (\ref{eq:l1}). For each $i=1,\ldots,n$, define $(\delta_{i,1},\ldots,\delta_{i,k})$ be a set of latent indicator variables, where $\delta_{i,r} = 1$ if the $i$th sample $(\y_i,\x_i)$ belongs to the $r$th component of the mixture model~\eqref{eq:exp_fm} and $\delta_{i,r} = 0$ otherwise. So $\sum_{r=1}^k\delta_{i,r}=1$, $\forall i$. These indicators are not observed since the cluster labels of the samples are unknown. Let $\delta$ denote the collection of all the indicator variables. By treating $\delta$ as missing, the EM algorithm proceeds by iteratively optimizing the conditional expectation of the complete log-likelihood criterion. The complete log-likelihood is given by \begin{align*} \ell_c(\theta\mid \Y,\X,\delta) = & \sum_{r=1}^k\biggl\{\sum_{i=1}^n\sum_{j\in\Omega_i} \delta_{i,r} \left( \frac{y_{ij}\varphi_{ijr}-b_j(\varphi_{ijr})}{a_j(\phi_{jr})} +c_j(y_{ij},\phi_{jr}) \right)\\ &+ \sum_{i=1}^n\delta_{i,r}\log(\pi_r)\biggr\}, \end{align*} where $\varphi_{ijr} = \x_i\bbeta_{jr}$, for $i = 1,\ldots,n,$ $j=1,\ldots,m$, and $r= 1,\ldots,k$. The conditional expectation of the penalized complete negative log-likelihood is then given by \begin{align*} Q_{pen}(\theta\mid \theta') = - \mathbb{E}[\ell_c(\theta\mid \Y,\X,\delta)|\Y,\X,\theta']/n + \mathcal{R}(\bbeta;\lambda,\pi), \end{align*} where $\mathcal{R}(\bbeta;\lambda,\pi)$ can be any of the penalties in~\eqref{eq:pen_lasso} or~\eqref{eq:pen_lasso_group}. It is easy to show that deriving $Q_{pen}(\theta\mid \theta')$ boils down to the computation of $\mathbb{E}[\delta_{i,r}\mid\Y,\X,\theta']$, which admits an explicit form. The EM algorithm proceeds as follows. Let $\theta^{(0)}$ be some given initial values. We repeat the following steps for $t=0,1,2,\ldots$, until convergence of the parameters or the pre-specified maximum number of iteration $T_{out}$ is reached.\\ \noindent\textbf{E-Step:} Compute $\hat{\rho}_{i,r}^{(t+1)}=\mathbb{E}[\delta_{i,r}\mid\Y,\X,\theta^{(t)}]$. For $\varphi_{ijr}^{(t)} = \x_i\bbeta_{jr}^{(t)}$, \begin{align}\label{eq:cond_prob_t} \hat{\rho}_{i,r}^{(t+1)} & = \frac{ \pi_r^{(t)}\prod_{j\in\Omega_i}\exp\{(y_{ij}\varphi_{ijr}^{(t)}-b_j(\varphi_{ijr}^{(t)}))/a_j(\phi_{jr}^{(t)}) +c_j(y_{ij},\phi_{jr}^{(t)})\}} {\sum_{r'=1}^k \pi_{r'}^{(t)}\prod_{j\in\Omega_i}\exp\{(y_{ij}g_{ijr'}^{(t)}-b_j(g_{ijr'}^{(t)}))/a_j(\phi_{jr'}^{(t)}) +c_j(y_{ij},\phi_{jr'}^{(t)})\}}. \end{align} \noindent\textbf{M-Step:} Minimize $Q_{pen}(\theta\mid\theta^{(t)})$. a) Update $\pi = (\pi_1,\ldots,\pi_k)$ by solving \begin{align* &\pi^{(t+1)} = \arg \min_{\pi} \ -\frac{1}{n} \sum_{r=1}^k\sum_{i=1}^n\hat{\rho}^{(t+1)}_{i,r} \log(\pi_r) + \mathcal{R}(\bbeta^{(t)};\lambda,\pi) \\ &s.t. \ \sum_{r=1}^k\pi_r = 1, \pi_r > 0, \forall r. \end{align*} b) Update $\bbeta,\PPhi$. \begin{align* (\bbeta^{(t+1)},\PPhi^{(t+1)}) = \arg \min_{\bbeta,\PPhi} \ &-\frac{1}{n}\sum_{r=1}^k\sum_{i=1}^n\hat{\rho}^{(t+1)}_{i,r}\sum_{j\in\Omega_i} \biggl( \frac{y_{ij}\x_i\bbeta_{jr} -b_j(\x_i\bbeta_{jr} )}{a_j(\phi_{jr})}\\ & +c_j(y_{ij},\phi_{jr}) \biggr )+ \mathcal{R}(\bbeta;\lambda,\pi^{(t+1)}). \nonumber \end{align*} For the problem in a),~\citet{stadler2010} proposed a procedure to lower the objective function by a feasible point, and we find that simply setting $\pi_r^{(t+1)} = \sum_{i=1}^n\hat{\rho}_{i,r}/n$ is good enough. For the problem in b), we use an accelerated proximal gradient (APG) method introduced in~\cite{nesterov2007gradient} with the maximum number of iteration of $T_{in}$. The update steps by proximal operators correspond to the chosen penalty form. For the entry-wise $\ell_1$ norm penalty in~\eqref{eq:pen_lasso}, \begin{align}\label{eq:proximal_lasso} \widehat{\bbeta}_r^{(t+1)} = \mbox{sign}(\widetilde{\bbeta}_r^{(t)}) \circ \max\{0, |\widetilde{\bbeta}_r^{(t)}|-\tau\lambda(\pi_r^{(t+1)})^{\gamma}\}, \end{align} where $\circ$ denotes entry-wise product, $\widetilde{\bbeta}_r^{(t)} = \bbeta_r^{(t)} + \tau\triangle\bbeta_r^{(t)}$, $\tau$ denotes the step size, and $\triangle\bbeta_r^{(t)}$ denotes the update direction of $\bbeta_r^{(t)}$ determined by APG. For the group $\ell_1$ norm penalty in~\eqref{eq:pen_lasso_group}, $$\widehat{\bbeta}_{r,j}^{(t+1)} = \widetilde{\bbeta}_{r,j}^{(t)} \circ \max\{0, 1 -\tau\lambda(\pi_r^{(t+1)})^{\gamma}/\|\widetilde{\bbeta}_{r,j}^{(t)}\|_2\}, $$ where $\bbeta_{r,j}$ denotes the $j$th column of $\bbeta_r$. We adopt the active set algorithm in~\cite{stadler2010} to speed up the computation. The time complexity of our algorithm using the speed up technique is $O(T_{out}kmnsT_{in})$ with $s$ being the number of non-zero parameters. The algorithm performs well in practice, and we have not observed any convergence issues in our extensive numerical studies. \subsection{Clustering of Samples \& Imputation of Missing Targets}\label{subsec:FMMOGLR_miss} From the model estimation, we can get estimates of both the conditional probabilities $p(\delta_{i,r} = 1 \mid y_{ij'},j' \in \Omega_i,\x_i,\theta)$ and the conditional means $\mathbb{E}[Y_{ij} \mid \x_i ,\theta,\delta_{i,r} = 1]$, where $ \mathbb{E}[Y_{ij} \mid \x_i ,\theta,\delta_{i,r} = 1 ] = \mu_j( \varphi_{ijr}) = b'_j(\x_i\bbeta_{jr})$. Specifically, the conditional probabilities can be estimated by $p(\delta_{i,r} = 1\mid y_{ij'},j' \in \Omega_i ,\x_i , \hat{\theta})$ which corresponds to~\eqref{eq:cond_prob_t}, taking $t = T_{out}$. The conditional expectations can be estimated as $\mathbb{E}[Y_{ij} \mid \x_i ,\hat{\theta},\delta_{i,r} = 1] = b'_j(\x_i\hat{\bbeta}_{jr})$. For clustering the samples, we adopt the Bayes rule, i.e., for $i=1,\ldots, n$, \begin{equation}\label{eq:hat_r_i} \hat{r}_i = \mathop{\argmax}_{r} \ p(\delta_{i,r} = 1\mid y_{ij'},j' \in \Omega_i ,\x_i , \hat{\theta}). \end{equation} Following the idea of~\citet{jacobs1991adaptive}, we propose to make imputation for the missing outcomes by \begin{equation}\label{eq:ensem2} \hat{y}_{ij} = \sum_{r=1}^{k}p(\delta_{i,r} = 1\mid y_{ij'},j' \in \Omega_i ,\x_i , \hat{\theta}) \mathbb{E}[Y_j\mid \x_i ,\hat{\theta},\delta_{i,r} = 1 ],\ \mbox{for} \ j \notin \Omega_i. \end{equation} { \subsection{Tuning Hyper-Parameters}\label{subsec:tune_hyperparam} Unless otherwise specified, all the hyper-parameters, including regularization coefficients $\lambda$s and the number of clusters $k$, are tuned to maximize the data log-likelihood in~\eqref{eq:loglike} on the held-out validation data set. In other words, we fit models on training data with different specific hyper-parameter settings, and then the optimal model is chosen as the one that gives the highest log-likelihood in~\eqref{eq:loglike} of the held-out validation data set. This approach is fairly standard and has been widely used in existing works~\citep{stadler2010}. Moreover, cross validation and various information criteria~\citep{bhat2010derivation,aho2014model} can also be applied to determine hyper-parameters. } { \section{Extensions}\label{sec:extension} We provide several extensions of the proposed~\methodname$\,$ approach described in Section~\ref{sec:method}, including robust estimation against outlier samples, handling anomaly tasks or clustered structure among tasks, and modeling mixture probabilities for feature-based prediction. } \subsection{Robust Estimation}\label{subsec:robust_estimation} To perform robust estimation for parameters in the presence of outlier samples, we propose to adopt the mean shift penalization approach~\citep{she2011outlier}. Specifically, we extend the natural parameter model to the following additive form, \begin{equation}\label{eq:outlier_g} \varphi_{ijr} = \x_i\bbeta_{jr}+\zeta_{ijr}, \end{equation} where $\zeta_{ijr}$ is a case-specific mean shift parameter to capture the potential deviation from the linear model. Apparently, when $\zeta_{ijr}$ is allowed to vary without any constraint, it can make the model fit as perfect as possible for every $y_{ijr}$. The merit of this approach is realized by assuming certain sparsity structure of the $\zeta_{ijr}$s, so that only a few of them have nonzero values corresponding to anomalies. Write $\zzeta_r \in \mathbb{R}^{n\times m} = [\zzeta_{1r},\zzeta_{2r},\ldots,\zzeta_{mr}]$ for $r=1,\ldots,k$, and $\zzeta\in\mathbb{R}^{(n\times m)\times k} =[\zzeta_1,\ldots, \zzeta_r]$. We can then conduct joint model estimation and outlier detection by extending~\eqref{eq:l1} to \begin{equation}\label{eq:estimator_outlier} (\hat{\theta},\hat{\zzeta}) = {\arg\min}_{\theta\in\Theta, \zzeta} \ - \ell(\theta\mid\Y,\X)/n + \mathcal{R}(\bbeta;\lambda_1) + \mathcal{R}(\zzeta;\lambda_2), \end{equation} where, for example, the penalty on $\zzeta$ can be chosen as the group $\ell_1$ penalty, \begin{align}\label{eq:pen_outlier_group} \mathcal{R}(\zzeta;\lambda_2) = \lambda_2\sum_{i=1}^n\sqrt{\sum_{jr}\zeta_{ijr}^2}, \end{align} {so that entries of $\zzeta$ are nonzero for only a few data samples.} The proposed GEM algorithm can be readily extended to handle the inclusion of $\zzeta$, for which we omit the details. \subsection{Handling Anomaly Tasks}\label{subsec:anomaly_tasks} { Besides outlier samples, certain tasks, referred to as anomaly tasks, may not follow the assumed shared structure and thus can ruin the overall model performance.} To handle anomaly tasks, though it is also intuitive to adopt the approach above, our numerical study suggests that its performance is sensitive to the tuning parameters. Here, we adopt the { idea of~\citet{koller1996toward} }, by utilizing the estimated conditional probabilities to measure how well a task is concordant with the estimated mixture structure. Consider the $h$th task. The main idea is to measure the discrepancy between $p(\delta_{ir} = 1\mid y_{ij}, j \in \Omega_i, \x_i,\theta)$, the conditional probability based on data from all observed targets, and $p(\delta_{ir} = 1 \mid y_{ih},\x_i,\theta)$, the conditional probability based on only the $h$th task. If $h$th task is an anomaly task, it is expected that the two conditional probabilities would differ more from each other~\citep{koller1996toward,law2002feature}. For $r= 1,\ldots,k$, $i = 1,\ldots,n$, let \begin{align}\label{eq:outlier_post} P_{\Omega,ir} & = p(\delta_{ir} = 1\mid y_{ij}, j \in \Omega_i,\x_i, \hat{\theta}) = \frac{\hat{\pi}_r\prod_{j\in\Omega_i}f(y_{ij}\mid \hat{\varphi}_{ijr},\hat{\phi}_{jr})}{\sum_{r'=1}^k\hat{\pi}_{r'}\prod_{j\in\Omega_i}f(y_{ij}\mid \hat{\varphi}_{ijr'},\hat{\phi}_{jr'})}, \\ P_{h,ir} &= p(\delta_{ir} = 1\mid y_{ih},\x_i,\hat{\theta}) = \frac{\hat{\pi}_rf(y_{ih}\mid \hat{\varphi}_{ihr},\hat{\phi}_{hr})}{\sum_{r'=1}^k\hat{\pi}_{r'}f(y_{ih}\mid \hat{\varphi}_{ihr'},\hat{\phi}_{hr'})}. \nonumber \end{align} Define $\P_{\Omega} = [P_{\Omega,ir}]_{n\times k}$ and $\P_h = [P_{h,ir}]_{n\times k}$. Then we define the concordant score of the $h$th task as \begin{equation}\label{eq:outlier_score} \begin{split} score(h) = - (D_{KL}(\P_{\Omega} \parallel \P_h) + D_{KL}(\P_h \parallel \P_{\Omega}))/{ (2n)}, \ h=1,\ldots,m, \end{split} \end{equation} where $D_{KL}$ is the widely used Kullback-Leibler divergence~\citep{cover2012elements}. The tasks can then be ranked based on their concordant scores. As such, the detection of anomaly tasks boils down to a one-dimensional outlier detection problem. { After anomaly tasks are detected, their FMR models can be built.} \subsection{Handling Clustered Structure among tasks}\label{subsec:clustered_tasks} { In practice, tasks may be clustered into groups such that each task group has its own model structure. Here we assume that each cluster of tasks shares a FMR structure defined in~\eqref{eq:exp_fm}, and propose to construct a similarity matrix to discover the potential cluster pattern among tasks. We consider a two-stage strategy. First, each task learns a FMR model on the training data independently with the same pre-fixed $k$. Then we get $\P_h = [P_{h,ir}]_{n\times k}$ for all $h=1,\ldots,m$, where \begin{equation*} P_{h,ir} = p(\delta_{h,ir} = 1\mid y_{ih},\x_i,\hat{\theta}_h) = \frac{\hat{\pi}_{hr}f(y_{ih}\mid \hat{\varphi}_{ihr},\hat{\phi}_{hr})}{\sum_{r'=1}^k\hat{\pi}_{hr'}f(y_{ih}\mid \hat{\varphi}_{ihr'},\hat{\phi}_{hr'})}, \end{equation*} and $\delta_{h,ir}(i=1,\dots,n,r = 1,\dots,k)$ and $\hat{\pi}_{hr}(r = 1,\dots,k)$ are the latent variables and the estimated prior probabilities of the $h$th task, respectively. Second, we adopt Normalized Mutual Information (NMI)~\citep{Strehl2003Cluster} to measure the similarity between each pair of tasks. We choose NMI instead of Kullback-Leibler divergence because NMI can handle the case that the orders of clusters of two $k$-cluster structures are different. Specifically, given two methods to estimate latent variables, which are denoted by method $u$ and method $v$, let $\P_u = [P_{u,ir}]_{n\times k}$ and $\P_v = [P_{v,ir}]_{n\times k}$ denote the estimated probability of latent variables of method $u$ and method $v$, respectively, where $P_{u,ir} = p(\delta_{u,ir} = 1), P_{v,ir} = p(\delta_{v,ir} = 1)$ for $i = 1,\ldots,n,r=1,\ldots,k$. NMI is defined as \begin{equation}\label{eq:NMI} NMI(\P_u ,\P_v ) = \frac{I(\P_u,\P_v)}{\sqrt{I(\P_u,\P_u)I(\P_v,\P_v)}}, \ u=1,\ldots,m,v=1,\ldots,m, \end{equation} where $I(\P_u,\P_v)$ denotes the mutual information between $\P_u,\P_v$ such that \begin{equation*}\label{eq:MI} I(\P_u,\P_v) = \sum_{a=1}^k \sum_{b=1}^k p(\delta_{u,a} = 1, \delta_{v,b} = 1)\log\left(\frac{p(\delta_{u,a} = 1,\delta_{v,b} = 1)}{p(\delta_{u,a} = 1)p(\delta_{v,b} = 1)}\right). \end{equation*} Following~\citet{Strehl2003Cluster}, we approximate $p(\delta_{u,a} = 1,\delta_{v,b} = 1)$, $p(\delta_{u,a} = 1)$ and $p(\delta_{v,b} = 1)$ by \begin{equation*}\label{eq:prob_in_MI} \begin{split} p(\delta_{u,a} = 1) &\approx \frac{1}{n}\sum_{i=1}^np(\delta_{u,ia} = 1) = \frac{1}{n}\sum_{i=1}^nP_{u,ia},\\ p(\delta_{v,b} = 1) &\approx \frac{1}{n}\sum_{i=1}^np(\delta_{v,ib} = 1) = \frac{1}{n}\sum_{i=1}^nP_{v,ib},\\ p(\delta_{u,a} = 1, \delta_{v,b} = 1) &\approx \frac{1}{n}\sum_{i=1}^np(\delta_{u,ia} = 1, \delta_{v,ib} = 1)\\ &\approx \frac{1}{n}\sum_{i=1}^np(\delta_{u,ia} = 1)p(\delta_{v,ib} = 1) =\frac{1}{n}\sum_{i=1}^nP_{u,ia}P_{v,ib}. \end{split} \end{equation*} As such, given the estimated models $\hat{\theta}_u,\hat{\theta}_v$ for the $u$th and the $v$th task, respectively, we treat $p(\delta_{u,ir} = 1\mid y_{iu},\x_i,\hat{\theta}_u)$ and $p(\delta_{v,ir} = 1\mid y_{iv},\x_i,\hat{\theta}_v)$ as $p(\delta_{u,ir} = 1)$ and $p(\delta_{v,ir} = 1)$, respectively, for $i = 1,\ldots,n,r=1,\ldots,k$. Then NMI between each pair of tasks are computed by~\eqref{eq:NMI}. We note that for simplicity we set the pre-fixed $k$ to be the same, but in general $k$ can be different for different tasks by the definition of Mutual Information. Given the similarity between each pair of tasks, any similarity-based clustering method can be applied to cluster $m$ tasks into groups. Empirically, the performance of task clustering is not sensitive to the pre-fixed $k$. As such, we set the pre-fixed $k$ to be $20$ in this paper. We then apply the proposed~\methodname$\,$ approach separately for each task group. } { \subsection{Modeling Mixture Probabilities}\label{subsec:predition} In real-applications, one may require to use $\x_i$ only to infer the latent variables $\delta_{i,r}$ and then to predict $\y_i$, for $i=1,\ldots,n,r=1,\ldots,k$. Here we further extend our method following the idea of Mixture-Of-Experts (MOE)~\citep{yuksel2012twenty} model; the only modification is that $\pi_r$ in~\eqref{eq:exp_fm} is assumed to be function of $\x_i$, for $i=1,\ldots,n$. To be specific, let $\aalpha = [\aalpha_1,\ldots,\aalpha_k] \in \mathbb{R}^{d\times k}$ collect regression coefficient vectors for a multinomial linear model. We assume that given $\x_i$, the joint probability density function of $\oby_i = \{y_{ij};j\in \Omega_i\}$ in~\eqref{eq:exp_fm} is replaced by \begin{equation* \begin{split} f(\oby_i \mid \x_i,\theta,\aalpha) &= f(y_{ij}, j\in \Omega_i \mid \x_i,\theta,\aalpha) \\ &= \sum_{r=1}^kp(\delta_{i,r} = 1\mid \x_i,\alpha_r ) \prod_{j\in\Omega_i}f(y_{ij}\mid \varphi_{ijr},\phi_{jr}), \end{split} \end{equation*} where \begin{equation}\label{eq:gate_prob} p(\delta_{i,r} = 1\mid \x_i,\alpha_r ) = \frac{\exp(\x_i\aalpha_r) }{\sum_{r'=1}^{k}\exp(\x_i\aalpha_{r'})} \end{equation} is referred to as the gating probability. All the other terms are defined the same as in~\eqref{eq:exp_fm}. Let $\theta_2 = \{ \bbeta,\phi_1,\ldots,\phi_k\}$, with the parameter space $ \Theta_2 = \mathbb{R}^{ (d \times m) \times k} \times \mathbb{R}^{m \times k}_{>0}. $ The data log-likelihood of the MOE model is \begin{equation}\label{eq:loglike_MOE} \begin{split} \ell(\theta_2,\aalpha\mid\Y,\X) = \sum_{i=1}^n\log\biggl(&\sum_{r=1}^kp(\delta_{i,r} = 1\mid \x_i,\alpha_r ) \\ &\prod_{j\in\Omega_i}\exp\biggl\{\frac{y_{ij}\varphi_{ijr}-b_j(\varphi_{ijr})}{a_j(\phi_{jr})}+c_j(y_{ij},\phi_{jr})\biggr\}\biggr). \end{split} \end{equation} The model estimation is conducted by extending~\eqref{eq:l1} to \begin{equation}\label{eq:estimator_MOE} (\hat{\theta}_2,\hat{\aalpha}) = {\arg\min}_{\theta_2\in\Theta_2, \aalpha} \ - \ell(\theta_2,\aalpha\mid\Y,\X) + \mathcal{R}(\bbeta;\lambda_1)/n + \mathcal{R}(\aalpha;\lambda_2), \end{equation} where, for example, the penalty on $\aalpha$ can be chosen as the lasso type penalty, \begin{align}\label{eq:pen_MOE} \mathcal{R}(\aalpha;\lambda_2) = \lambda_2\|\aalpha\|_1. \end{align} The minimization problem in~\eqref{eq:estimator_MOE} is also solved by GEM, for which the optimization procedure is similar to that in Section~\ref{subsec:optimization}. The differences occur at the E-step: \begin{equation}\label{eq:cond_prob_t_MOE} \hat{\rho}_{i,r}^{(t+1)} = \frac{ p(\delta_{i,r} = 1\mid \x_i,\alpha_{r}^{(t)} )\prod_{j\in\Omega_i}f(y_{ij}\mid \varphi_{ijr}^{(t)},\phi_{jr}^{(t)})} {\sum_{r'=1}^k p(\delta_{i,r'} = 1\mid \x_i,\alpha_{r'}^{(t)} )\prod_{j\in\Omega_i}f(y_{ij}\mid \varphi_{ijr'}^{(t)},\phi_{jr'}^{(t)})}, \end{equation} where $f(y_{ij}\mid \varphi_{ijr}^{(t)},\phi_{jr}^{(t)}) = \exp\{(y_{ij}\varphi_{ijr}^{(t)}-b_j(\varphi_{ijr}^{(t)}))/a_j(\phi_{jr}^{(t)}) +c_j(y_{ij},\phi_{jr}^{(t)})\}$, at the optimization for $\aalpha$: \begin{equation}\label{eq:update_alpha_MOE} \aalpha^{(t+1)} = \arg \min_{\aalpha} \ -\frac{1}{n} \sum_{r=1}^k\sum_{i=1}^n\hat{\rho}^{(t+1)}_{i,r} \log p(\delta_{i,r} = 1\mid \x_i,\alpha_{r} ) + \mathcal{R}(\aalpha^{(t)};\lambda_2), \end{equation} and at the computation of $\pi$: $\pi_r^{(t+1)} = \frac{1}{n}\sum_{i=1}^{n}p(\delta_{i,r} = 1\mid \x_i,\alpha_r^{(t+1)} )$ for $r=1,\ldots,k$. } \section{Theoretical Analysis} We study the estimation and variable selection performance of~\methodname\, under the high-dimensional framework with $d\gg n$. Both $m$ and $k$, on the other hand, are considered as fixed. This is because usually, the number of interested targets and the number of desired clusters are not large in many real problems. Here we only present the setup and the main results on non-asymptotic oracle inequalities to bound the excess risk and false selection, leaving detailed derivations in the Appendix. Our results generalize~\citet{stadler2010} to cover mixture regression models with 1) multivariate, heterogeneous (mixed-type) and incomplete response and 2) shared feature grouping sparse structure. This is not trivial due to the non-convexity and the triple heterogeneity of the problem. It turns out that additional condition on the tail behaviors of the conditional density $f(\y\mid \x,\theta)$ is required. Fortunately, the required conditions are still satisfied by a broad range of distributions. \subsection{Notations and Conditions on the Conditional Density} We firstly introduce some notations. Denote the regression parameters that are subject to regularization by $\beta = \mbox{vec}(\bbeta_1,\ldots,\bbeta_k),\phi = \mbox{vec}(\Phi_1,\ldots,\Phi_k)$, where $\mbox{vec}(\cdot)$ is the vectorization operator. The other parameters in the mixture model are denoted by $\eta = \mbox{vec} (\log(\phi),\log(\pi))$, where $\log(\cdot)$ is entry-wisely applied. Denote the true parameter by $\theta_0 = ( \bbeta_0,\Phi_{0,1},\ldots,\Phi_{0,k},\pi_{0,1},\pi_{0,k-1})$ to be estimated under the FMR model defined in~\eqref{eq:exp_fm} and~\eqref{eq:natural_parameter}. In the sequel, we always use subscripts ``$0$'' to represent parameters or structures under the true model. To study sparsity recovery, denote the set of indices of non-zero entries of the true parameter by $S$. We use $\lesssim$ to indicate that the inequality holds up to some multiplicative numerical constants. {To focus on the main idea, we consider the case of $\gamma=0$ in the following analysis}. We define average excess risk for fixed design points $\x_1,\ldots,\x_n$ based on Kullback-Leibler divergence as \begin{align*} \bar{\varepsilon}(\theta\mid \theta_0) &= \frac{1}{n}\sum_{i=1}^n \varepsilon(\theta\mid \x_i,\theta_0), \ \varepsilon(\theta\mid \x_i,\theta_0)\\ & = - \int \log\left(\frac{f(\oby_i\mid \x_i,\theta)}{f(\oby_i \mid \x_i,\theta_0)}\right)f(\oby_i \mid \x_i,\theta_0)d\oby_i, \end{align*} where $f(\oby_i \mid \x_i,\theta)$ is defined in~\eqref{eq:exp_fm}. To impose the conditions on $f(\oby_i \mid \x_i,\theta)$, denote $\psi_i = \mbox{vec}(\varphi_i,\eta)$, where $\varphi_i = \mbox{vec}(\{\varphi_{ijr};j\in\Omega_i,r = 1,\ldots,k\})$, and denote $ \psi = \mbox{vec}(\psi_1,\ldots,\psi_n)$. As such, we may write $f(\oby_i\mid \x_i,\theta) = f(\oby_i\mid\psi_i)$, $\ell(\theta\mid \oby_i,\x_i) = \log f(\oby_i\mid \x_i,\theta)= \ell(\psi_i\mid \oby_i)$, and $ \bar{\varepsilon}(\psi\mid\psi_{0}) = \frac{1}{n}\sum_{i=1}^{n}\varepsilon(\psi_i\mid\psi_{0,i}) = \bar{\varepsilon}(\theta\mid\theta_0)$. Without loss of much generality, the model parameters are assumed to be in a bounded parameter space for a constant $K$: \begin{equation}\label{eq:tTheta} \begin{split} \tilde{\Theta} \subset \{\theta; & \max_{i=1,\ldots,n}\|\varphi_i(\x_i, \bbeta)\|_{\infty}\leq K, \max_{j=1,\ldots,m} |\log a_j(\phi)|\leq K,\\ &\max_{j=1,\ldots,m} \log |b'_j(\phi)|\leq K, \|\log\phi\|_{\infty}\leq K, \\ &-K\leq \log\pi_1\leq 0, \ldots, -K \leq \log\pi_{k-1} \leq 0,\\ & \sum_{r=1}^{k-1}\pi_r < 1, \pi_k = 1 - \sum_{r=1}^{k-1}\pi_r\}. \end{split} \end{equation} We present the following conditions on $f(\oby_i\mid \psi_i)$. \begin{mycon}\label{th:con_G1} For some function $G_1(\cdot)\in \mathbb{R}$, for $i = 1,\ldots,n$, \begin{align*} \sup_{\theta\in\tilde{\Theta}}\|\frac{\partial \ell(\psi_i\mid \oby_i)}{\partial \psi_i}\|_{\infty}\leq G_1(\oby_i). \end{align*} \end{mycon} \begin{mycon}\label{th:con_tail} For a constant $c_1\geq 0$, and some constants $ c_2,c_3,c_4,c_5\geq 0$ depending $K$, and for $M>c_4$, we assume for $i = 1,\ldots,n$, \begin{align*} & \mathbb{E}[|G_1({\oby_i})|1\{|G_1(\oby_i)|>M\}] \leq \biggl[ c_3\biggl(\frac{M}{c_2}\biggr)^{c'}+ c_5 \biggr]\exp\biggl\{-\biggl(\frac{M}{c_2}\biggr)^{1/c_1}\biggr\},\\ & \mathbb{E}[|G_1(\oby_i)|^21\{|G_1(\oby_i)|>M\}] \leq \biggl[ c_3\biggl(\frac{M}{c_2}\biggr)^{c'}+ c_5 \biggr]^2\exp\biggl\{-2\biggl(\frac{M}{c_2}\biggr)^{1/c_1}\biggr\}, \end{align*} where $\oby_i = \{y_{ij}; j\in\Omega_i\}$, $c' = 2+3/c_1$ and $1\{\cdot\}$ denotes the indicator function. \end{mycon} \begin{mycon}\label{th:con_fisher} It holds that, \begin{align*} \min_{i=1,\ldots,n}\Lambda_{\min}(I(\psi_{0,i}))> {1}/{c_0} > 0, \end{align*} where $c_0$ is a constant, $\Lambda_{\min}^2(A)$ is the smallest eigenvalue of a symmetric, positive semi-definite matrix $A$ and for $i = 1,\ldots,n$, $I(\psi_{0,i})$ is the Fisher information matrix such that \begin{align*} I(\psi_{0,i}) = - \int \frac{\partial^2\ell(\psi_{0,i}\mid \oby_i)}{\partial \psi_{0,i} \partial \psi_{0,i}^T } f(\oby_i\mid \psi_{0,i}) d\oby_i. \end{align*} \end{mycon} The first condition follows from~\citet{stadler2010}, which aims to bound $\partial \ell(\psi_i\mid \oby_i)/\partial \psi_i$ with known $\oby_i$, for $i=1,\ldots,n$. The second condition is about the tail behaviors of $f(\oby_i \mid \x_i,\theta)$. The third condition depicts the local convexity of $\ell$ at the point $\theta_0$. Condition~\ref{th:con_G1} and~\ref{th:con_tail} can cover a broad range of distributions for $f$, including but not limited to mixture of sub-exponential distributions, such as our proposed~\methodname\, model with known dispersion parameters, c.f., Lemma~\ref{th:lem_subexp_tail}. \begin{mylem}\label{th:lem_subexp_tail} Condition~\ref{th:con_G1} and~\ref{th:con_tail} hold for the heterogeneous mixture distribution $f(\oby_i\mid \x_i,\theta)$ defined in~\eqref{eq:exp_fm} with known dispersion parameters. \end{mylem} The following two quantities will be used. \begin{equation}\label{eq:lambda_0} \lambda_0 = \sqrt{mk} M_n\log n \sqrt{\frac{\log(d\vee n)}{n}}, \ M_n = c_2(\log n)^{c_1}, \end{equation} where $ c_1,c_2$ are the same constants as in Condition~\ref{th:con_tail}. More specifically, we choose $c_1 = 1/2, 0, 1$ for Gaussian, Bernoulli and Poisson task, respectively. \subsection{Results for Lasso-Type Estimator} Consider first the penalized estimator defined in (\ref{eq:l1}) with the $\ell_1$ penalty in~\eqref{eq:pen_lasso}. Following~\citet{bickel2009simultaneous} and~\citet{stadler2010}, we impose the following restricted eigenvalue condition on the design. \begin{mycon}\label{th:con_REC} (Restricted eigenvalue condition). For all $ w \in \mathbb{R}^{dmk}$ satisfying $\|w_{S^c}\|_1 \leq 6\|w_S\|_1$, it holds that for some constant $\kappa\geq 1$, \begin{align*} \|w_S\|_2^2 \leq \kappa^2 \|\varphi\|_{Q_n}^2 = \frac{\kappa^2}{n}\sum_{i=1}^n\sum_{j\in\Omega_i}\sum_{r=1}^k (\x_i\bbeta_{jr})^2. \end{align*} \end{mycon} \begin{mythe}\label{th:th_bound} Consider the~\methodname\, model in (\ref{eq:exp_fm}) with { $\theta_0 \in \tilde{\Theta}$ }, and consider the penalized estimator (\ref{eq:l1}) with the $\ell_1$ penalty in (\ref{eq:pen_lasso}). Assume Conditions 1-4 hold. Suppose $\sqrt{mk} \lesssim n/M_n$, and take $\lambda > 2T\lambda_0$ for some constant $T>1$. For some constant $c>0$ and large enough $n$, with probability \begin{equation}\label{eq:prob_bound} 1 - c\exp\left(-\frac{\log^2n\log(d\vee n)}{c}\right) - \frac{1}{n}, \end{equation} we have \begin{equation}\label{eq:bound_low} \bar{\varepsilon}(\hat{\theta}\mid \theta_0) + 2(\lambda-T\lambda_0) \|\hat{\beta}_{S^c}\|_1 \leq 4(\lambda+T\lambda_0)^2\kappa^2 c_0^2s \end{equation} where $s$ is the number of non-zero parameters of $w_0$. \end{mythe} Theorem~\ref{th:th_bound} suggests that the average excess risk has a convergence rate of the order {$O(s \lambda_0^2) = O((\log n)^{2+2c_1}\log(d\vee n)smk/n)$}, by taking $\lambda = 2T\lambda_0$ and using $\lambda_0$ and $M_n$ as defined in (\ref{eq:lambda_0}). Also, the degree of false selection measured by $ \|\hat{\beta}_{S^c}\|_1$ converge to zero at rate {$O(s\lambda_0) =O(s\sqrt{(\log n)^{2+2c_1}\log(d\vee n)mk/n)} $}. Similar to~\citet{stadler2010}, under weaker conditions without the restricted eigenvalue assumption on the design, we still achieve the consistency for the average excess risk. \begin{mythe}\label{th:high_dim} Consider the~\methodname\, model in (\ref{eq:exp_fm}) with $\theta_0 \in \tilde{\Theta}$, and consider the penalized estimator (\ref{eq:l1}) with the $\ell_1$ penalty in (\ref{eq:pen_lasso}). Assume Conditions 1-3 hold. Suppose \begin{align*} \|\beta_0\|_1 &= o(\sqrt{n/((\log n)^{2+2c_1}\log(d\vee n)mk)}),\\ \sqrt{mk} &= o(\sqrt{n/((\log n)^{2+2c_1}\log(d\vee n))}) \end{align*} as $n\rightarrow \infty$, and take $\lambda = C\sqrt{(\log n)^{2+2c_1}\log(d\vee n)mk/n}$ for some constant $C>0$ sufficiently large. For some constant $c>0$ and large enough $n$, with the following probability $ 1 - c\exp\left(-\frac{ (\log n)^2\log(d\vee n)}{c}\right) - \frac{1}{n}, $ we have $ \bar{\varepsilon}(\hat{\theta}\mid \theta_0) = o_P(1). $ \end{mythe} \subsection{Results for Group-Lasso Type Estimator} Consider the following general form of the group $\ell_1$ penalty, \begin{equation}\label{eq:pen_lasso_group_general} \begin{split} \mathcal{R}(\bbeta) = \lambda\sum_{p=1}^P\|\bbeta_{\mathcal{G}_p}\|_F, \end{split} \end{equation} where $\mathcal{G}_1,\ldots,\mathcal{G}_P$ are index collections such that $ \mathcal{G}_p \bigcap \mathcal{G}_{p'} = \emptyset$ for $p\neq p'$ and $\bigcup_{p=1}^P\mathcal{G}_p = \bigcup_{l=1}^d \bigcup_{j=1}^m \bigcup_{r=1}^k (l,j,r) $ equals the universal set of indices of $\bbeta\in\mathbb{R}^{(d\times m)\times k}$, i.e., $\bbeta_{\mathcal{G}_p}$ is the $p$th group of $\bbeta$. $\|\cdot\|_F$ denotes the Frobenius norm and here for $p = 1,\ldots,P$, $\|\bbeta_{\mathcal{G}_p}\|_F = \sqrt{\sum_{(l,j,r)\in\mathcal{G}_p}w_{ljr}^2}$. This penalty form generalizes the row-wise group sparsity in~\eqref{eq:pen_lasso_group}. Denote $ \mathcal{I} = \{p: \bbeta_{0,\mathcal{G}_p} = \mathbf{0}\}$ and $ \mathcal{I}^c = \{p: \bbeta_{0,\mathcal{G}_p} \neq \mathbf{0}\}, $ where $ \bbeta_{0,\mathcal{G}_p}$ is the $p$th group of $\bbeta_{0}$. Now denote by $s$ the size of $\mathcal{I}$, with some abuse of notation. We impose the following group-version restricted eigenvalue condition. \begin{mycon}\label{th:con_REC_GS} For all $ \bbeta \in \mathbb{R}^{(d\times m)\times k}$ satisfying \begin{align*} \sum_{p\in \mathcal{I}^c}\|\bbeta_{\mathcal{G}_p}\|_F \leq 6\sum_{p\in \mathcal{I}}\|\bbeta_{\mathcal{G}_p}\|_F, \end{align*} it holds that for some constant $\kappa\geq 1$, \begin{align*} \sum_{p\in \mathcal{I}}\|\bbeta_{\mathcal{G}_p}\|_F^2 \leq \kappa^2 \|\varphi\|_{Q_n}^2. \end{align*} \end{mycon} \begin{mythe}\label{th:th_bound_GS} Consider the~\methodname\, model in (\ref{eq:exp_fm}) with $\theta_0 \in \tilde{\Theta}$, and consider the penalized estimator (\ref{eq:l1}) with the group $\ell_1$ penalty in (\ref{eq:pen_lasso_group_general}). \noindent (a) Assume conditions 1-3 and 5 hold. Suppose $\sqrt{mk} \lesssim n/M_n$, and take $\lambda > 2T\lambda_0$ for some constant $T>1$. For some constant $c>0$ and large enough $n$, with the following probability $ 1 - c\exp\left(-\frac{ (\log n)^2\log(d\vee n)}{c}\right) - \frac{1}{n}, $ we have \begin{align*} \bar{\varepsilon}(\hat{\theta}\mid\theta_0) + 2(\lambda-T\lambda_0) \sum_{p\in\mathcal{I}^c}\|\widehat{\bbeta}_{\mathcal{G}_p}\|_F \leq 4(\lambda+T\lambda_0)^2\kappa^2 c_0^2s. \end{align*} \noindent(b) Assume conditions 1-3 hold (without condition~\ref{th:con_REC_GS}), and assume \begin{align*} \sum_{p=1}^P\|\bbeta_{0,\mathcal{G}_p}\|_F & = o(\sqrt{n/((\log n)^{2+2c_1}\log(d\vee n)mk)}),\\ \sqrt{mk} &= o(\sqrt{n/((\log n)^{2+2c_1}\log(d\vee n))}) \end{align*} as $n\rightarrow \infty$. Let $\lambda = C\sqrt{(\log n)^{2+2c_1}\log(d\vee n)mk/n}$ for some $C>0$ sufficiently large. Then for some constant $c>0$ and large enough $n$, with the following probability $ 1 - c\exp\left(-\frac{ (\log n)^2\log(d\vee n)}{c}\right) - \frac{1}{n}, $ we have $ \bar{\varepsilon}(\hat{\theta}\mid\theta_0) = o_P(1). $ \end{mythe} So the average excess risk has a convergence rate of $O(s\lambda_0^2)$, and the degree of false group selection, as measured by $ \sum_{p\in\mathcal{I}^c}\|\hat{\bbeta}_{\mathcal{G}_p}\|_F$, converges to zero at rate $O(s\lambda_0)$. The estimator in (\ref{eq:l1}) using other group $\ell_1$ penalties such as~\eqref{eq:pen_lasso_group} are special cases, so the results of Theorem~\ref{th:th_bound_GS} still apply. \noindent\underline{\textbf{Remark}}. Our results can be extended to the mean-shifted natural parameter model as in~\eqref{eq:outlier_g}, with a modified restricted eigenvalue condition. See the Appendix for some details. \section{Experiments} \label{sec:exp} In this section, we present empirical studies on both synthetic and real-world data sets. \subsection{Methods for Comparison}\label{subsec:method_comp} We evaluate the following versions of the proposed~\methodname\, approach. (1) Single task learning (\textbf{Single}): It is a special case of the~\methodname\, estimator~\eqref{eq:l1} with~\eqref{eq:pen_lasso}, where each task is learned separately. (2) Separately learning (\textbf{Sep}): It is a special case of the~\methodname\, estimator~\eqref{eq:l1} with~\eqref{eq:pen_lasso}, where each type (Gaussian, Bernoulli or Poisson) of tasks is learned separately. (3) Mixed learning with entry-wise sparsity (\textbf{Mix}): It is the proposed~\methodname\, estimator~\eqref{eq:l1} with~\eqref{eq:pen_lasso} where all the tasks are jointly learned. To compare with \textbf{Sep}, we allow different tuning parameters for different types of outcomes. (4) Mixed learning with group sparsity (\textbf{Mix GS}): It is the proposed~\methodname\, estimator~\eqref{eq:l1} with~\eqref{eq:pen_lasso_group}. { (5) Mixed learning Mixture-Of-Experts model with entry-wise sparsity (\textbf{Mix MOE}): It is the proposed~\methodname\, estimator~\eqref{eq:estimator_MOE} with~\eqref{eq:pen_lasso} and~\eqref{eq:pen_MOE}. (6) Mixed learning Mixture-Of-Experts model with group sparsity (\textbf{Mix MOE GS}): It is the proposed~\methodname\, estimator~\eqref{eq:estimator_MOE} with~\eqref{eq:pen_lasso_group} and~\eqref{eq:pen_MOE}. } Besides the above FMR methods, we also evaluate several non-FMR multi-task methods below for comparison, some of which handle certain kinds of heterogeneities, such as anomaly tasks, clustered tasks and heterogeneous responses. Since they are non-FMR, they learn a single regression coefficient matrix $\bbeta \in \mathbb{R}^{d\times m}$. \begin{itemize} \item \textbf{LASSO}: $\ell_1$-norm multi-task regression with $\lambda\|\bbeta\|_1$ as penalty. Each type of tasks are learned independently. It is a special case of \textbf{Sep} when pre-fixed $\hat{k}=1$. \item \textbf{Sep L2}: ridge multi-task regression with $\lambda\|\bbeta\|_F^2$ as penalty. Each type of tasks are learned independently. \item \textbf{Group LASSO}: $\ell_{1,2}$-norm multi-task regression with $\lambda\|\bbeta\|_{1,2}$ as penalty~\citep{yang2009heterogeneous}, which handles heterogeneous responses, and is a special case of \textbf{Mix GS} when pre-fixed $\hat{k}=1$. \item \textbf{TraceReg}: trace-norm multi-task regression~\citep{ji2009accelerated}. \item \textbf{Dirty}: dirty model multi-task regression with $\lambda_1\|\S\|_{1} + \lambda_2\|\L\|_{1,\infty}(\bbeta = \L + \S)$ as penalty~\citep{jalali2010dirty}, handling entry-wise heterogeneity in $\bbeta$ comparing with \textbf{Group LASSO}. \item \textbf{MSMTFL}: multi-stage multi-task feature learning~\citep{gong2012multi} whose penalty is $\lambda_1\sum_{l=1}^{d}\min(\|\bbeta^l\|_1,\lambda_2)$, where $\bbeta^l$ denotes the $l$th row of $\bbeta$. It also handles entry-wise heterogeneity in $\bbeta$ comparing with \textbf{Group LASSO}. \item \textbf{SparseTrace}: multi-task regression, learning sparse and low-rank patterns with $\lambda_1\|\S\|_{1} + \lambda_2\|\L\|_*(\bbeta = \L + \S)$ as penalty~\citep{chen2012learning}, handling entry-wise heterogeneity in $\bbeta$ comparing with \textbf{TraceReg}, where $\|\cdot\|_{*}$ denotes the nuclear norm of the enclosed matrix. \item \textbf{rMTFL}: robust multi-task feature learning with $\lambda_1\|\S\|_{2,1} + \lambda_2\|\L\|_{1,2}(\bbeta = \L + \S)$ as penalty~\citep{gong2012robust}, handling anomaly tasks comparing with \textbf{Group LASSO}. \item \textbf{RMTL}: robust multi-task regression with $\lambda_1\|\S\|_{2,1} + \lambda_2\|\L\|_*(\bbeta = \L + \S)$ as penalty~\citep{chen2011integrating}, handling anomaly tasks comparing with \textbf{TraceReg}. \item \textbf{CMTL}: clustered multi-task learning~\citep{zhou2011clustered}, handling clustered tasks. \item \textbf{GO-MTL}: multi-task regression, handling overlapping clustered tasks~\citep{kumar2012learning}. \end{itemize} \subsection{Experimental Setting} In our experiments, for the E-step of GEM, we follow~\citet{stadler2010} to initialize $\rho$. For the M-step, we initialize the entries of $\bbeta$ from $\mathcal{N}(0,10^{-10})$. We fix $\sigma = 1$ for Gaussian tasks, and set $\gamma=1$. In the APG algorithm, step size is initialized by the Barzilai-Borwein rule~\citep{barzilai1988two} and updated by the TFOCS-style backtracking~\citep{becker2011templates}. We terminate the APG algorithm with maximum iteration step $T_{in} = 200$ or when the relative $\ell_2$-norm distance of two consecutive parameters is less than $10^{-6}$. We terminate the GEM with maximum iteration step $T_{out} = 50$, or when the relative change of two consecutive $-\ell(\theta\mid\Y,\X)/n$ is less than $10^{-6}$ or when the relative $\ell_{\infty}$-norm distance of two consecutive parameters is less than $10^{-3}$. { In the experiments on both simulated and real-world data sets, we partition the entire data set into three parts: a training set for model fitting, a validation set for tuning hyper-parameters and a testing set for testing the generalization performance of the selected models. The only exception is Section~\ref{subsubsec:sim1}, where we do not generate testing data sets because the models are evaluated by comparing the estimation results to the ground truth. In hyper-parameter tuning, the regularization parameters, i.e., $\lambda$s, are tuned from $[1e-6,1e3]$, and the number of clusters are tuned from $\{1,\ldots,10\}$. Hyper-parameters of the baseline methods are tuned according to the descriptions in their respective references. All the experiments are replicated 100 times under each model setting. } \subsection{Evaluation Metrics} The prediction of latent variable is evaluated by Normalized Mutual Information (NMI)~\citep{strehl2002cluster,fern2003random,Strehl2003Cluster}. {In detail, we compute NMI scores by~\eqref{eq:NMI}, treating estimated conditional probabilities $[\P_{\Omega,ir}]_{n\times k}$ defined in~\eqref{eq:outlier_post} and the ground truth latent variables $[\delta_{i,r}]_{n\times k}$ as $[P_{1,ir}]_{n\times k}$ and $[P_{2,ir}]_{n\times k}$, respectively.} For feature selection, firstly, the estimated components are reordered to make the best match with the true components. Then feature selection is evaluated by Area Under the ROC Curve (AUC) which is measured by the Wilcoxon-Mann-Whitney statistic provided by~\citet{hanley1982meaning}. {Concretely, absolute values of vectorized estimated regression parameters, i.e., $\hat{\beta}_{\mbox{abs}} =|\mbox{vec}( \hat{\bbeta})|$, and binarized vectorized ground truth regression parameters, i.e., $\beta_{0,\mbox{sign}} = \mbox{sign}(|\mbox{vec}(\bbeta_0)|)$, are used as inputs to AUC, where $\bbeta_0$ denotes the ground truth regression parameter and $\mbox{vec}(\cdot)$ is the vectorization operator.} {In order to show the existence of mixed relationships between features and targets, imputation performance for incomplete targets is used to compare FMR methods with non-FMR MTL methods.} Concretely, the goal is to predict one-half randomly chosen targets. The other half targets are allowed to be used. FMR methods use the other half targets to compute conditional probabilities $p(\delta_{i,r} = 1 \mid y_{ij'},j' \in \Omega_i,\x_i,\hat{\theta})(i=1,\ldots,n,r=1,\dots,k)$ and make prediction as stated in Section~\ref{subsec:FMMOGLR_miss}. Non-FMR MTL methods perform feature-based prediction. { Feature-based prediction performances are also compared between non-FMR MTL methods and our MOE methods, where only features are allowed to use to predict testing targets. For this case, the goal is to predict all the targets. } {For target prediction, Gaussian outcomes are evaluated by nMSE~\citep{chen2011integrating,gong2012robust} which is defined as the mean of each task's mean squared error (MSE) divided by the variance of its target vector. Bernoulli outcomes are evaluated by average AUC (aAUC), which is defined as the mean AUC of each task. For Poisson tasks, we firstly compute the logarithms of outcomes, then use nMSE for evaluation. } {Since our objective functions in~\eqref{eq:l1} and~\eqref{eq:estimator_MOE} are non-convex, estimated parameters may correspond to local minimums of the objective functions. Therefore, we try different initializations and report the results ranking the best 20\% on the validation data set out of the 100 replications to avoid the results that may be stuck at local minimums, suggesting that one can always select any result within the best 20\%.} \subsection{Simulation} \subsubsection{Latent Variable Prediction and Feature Selection}\label{subsubsec:sim1} We consider both low dimensional case and high dimensional case for latent variable prediction and feature selection. For the low-dimensional case, we set the number of samples $n=100$, feature dimension $d=15$, number of non-zero features (sparsity) $s=3$, and the number of tasks (responses) $m=15$. The data set includes $3$ Gaussian tasks, $10$ Bernoulli tasks, and $2$ Poisson tasks. The number of latent components $k=2$. For $r=1,\dots,k$, in the $r$th component, the first row (biases) and the $(s(r-1)+2)$th to the $(sr+1)$th row (a block of $s$ rows) of the true $\bbeta_r\in \mathbb{R}^{d\times m}$ are non-zero (to let different components have different sets of features). Non-zero parameters in $\bbeta$ are in the range of $[-3,-1]\cup[1,3]$ except that those of Poisson tasks are in the range of $[-0.3,-0.1]\cup[0.1,0.3]$. The biases are all set to $1$ except that those of Poisson tasks are set to $3$. For Gaussian tasks, all $\sigma$s are set to $1$. The entries of $\X\in\mathbb{R}^{d\times n}$ are drawn from $\mathcal{N}(0,1)$ with the first dimension being $1$. $\pi = (0.5,0.5)$. Validation data is independently generated likewise and has $n$ samples. For the high-dimensional case, we set $n=180$, $d=320$ and $m=20$. The data set includes $8$ Gaussian tasks, $10$ Bernoulli tasks, and $2$ Poisson tasks. Other settings are the same as in the low-dimensional case. We set the pre-fixed $\hat{k}$ to be equal to the true $k=2$. For targets of training data, we have tried different missing rates, which are in the range of $\{0,0.05,0.1,0.15,0.2\}$. We compare the performances of $\hat{\theta}$s estimated by \textbf{Single}, \textbf{Sep}, \textbf{Mix}, \textbf{Mix GS}, respectively, with that of $\theta_0$ (denoted by ``\textbf{True}''). { The results are shown in Fig~\ref{fig:theory}. The horizontal axis is the missing rates. Intuitively, larger missing rates may result in worse performances due to fewer data samples. \textbf{Single} provides poor results and is not sensitive to missing rate, because (1) data samples are deficient for single-task learning and (2) the influence of missing rate may be not significant when the number of samples is at this level. \textbf{Sep} outperforms \textbf{Single} and is affected significantly by missing rate, because (1) \textbf{Sep} uses the prior knowledge in data that multiple tasks share the same FMR structure and (2) \textbf{Sep} constructs separate FMR models such that tasks for each model are deficient, hence the advantage from joint learning multiple tasks can be easily affected when some targets are missing. Our~\methodname\, method \textbf{Mix} outperforms \textbf{Sep} and is robust against growing missing rate, because (1) \textbf{Mix} uses the prior knowledge in data that all the tasks share the same FMR structure and (2) \textbf{Mix} takes advantage of all the tasks, therefore, the number of tasks is then enough even some targets are missing. Our~\methodname\, method \textbf{Mix GS} outperforms \textbf{Mix}, even rivals the true model, and is also robust against growing missing rate, because (1) comparing with \textbf{Mix}, \textbf{Mix GS} further uses the prior knowledge in data that all the tasks share the same feature space in each cluster, and (2) \textbf{Mix GS} takes advantage of all the tasks as well. } \begin{figure}[htbp]\small \centering \subfigure[Latent variable prediction accuracy]{\includegraphics[width=2.3in]{Fig1a}} \subfigure[Feature selection accuracy]{\includegraphics[width=2.3in]{Fig1b}} \subfigure[Latent variable prediction accuracy]{\includegraphics[width=2.3in]{Fig1c}} \subfigure[Feature selection accuracy]{\includegraphics[width=2.3in]{Fig1d}} \caption{Latent variable prediction and feature selection performance. (a) and (b) are results on low-dimensional data; (c) and (d) are results on high-dimensional data.}\label{fig:theory} \end{figure} \subsubsection{Performances When the Pre-Fixed $\hat{k}$ Is Different with the True $k$}\label{subsubsec:sim_diff_k} We consider testing the performance of target imputation when the pre-fixed $\hat{k}$ is different with the true $k$. Four data sets are generated with the true $k = 1,2,3,4$, respectively. We set $n=1000$, $d=32$, and $m=15$. There are $3$ Gaussian tasks, $10$ Bernoulli tasks, and $2$ Poisson tasks. For each $k = 1,2,3,4$, the sparsity $s$ is set to $\lfloor d/(2k)\rfloor$ such that the total numbers of relevant features for different data sets are the same. The values of the non-zero regression parameters for Gaussian and Bernoulli tasks in $\bbeta$ are in the range of $[-6,-2]\cup[2,6]$. We set $\pi_1 = \pi_2 = \ldots = \pi_k$. Validation and testing data are independently generated likewise and both have $n$ samples. We randomly set 20\% of targets to be missing for all the training, validation and testing data. Other settings are the same as in Section~\ref{subsubsec:sim1}. One intuitive thought is that when the pre-fixed $\hat{k}$ equals the true $k$, the imputation performance will be maximized. So we set the pre-fixed $\hat{k} \in\{ 1,2,3,4,5,6,7,8\}$. We test \textbf{Mix} model in this experiment. Results by \textbf{Mix GS} model are similar. In Fig~\ref{fig:diffk_simu}, the imputation performances are truly maximized when the pre-fixed $\hat{k}$ equals the true $k$. When pre-fixed $\hat{k}$ is larger than the true $k$, the imputation performances are similar. When the true $k>1$ and when the pre-fixed $\hat{k}$ is less than the true $k$, the imputation performances grow with the pre-fixed $\hat{k}$. {One may expect that when the pre-fixed $\hat{k}$ is larger than the true $k$, the performances will deteriorate, since imputation would be based on fewer data samples. We think it is because (1) the simulated data are simple, and (2) the information sharing among tasks renders the robustness of our~\methodname\, method against decreasing sample size, which is consistent with the results in Section~\ref{subsubsec:sim1} when facing increasing missing rate (larger missing rate also indicates fewer data samples).} \begin{figure}[htbp]\small \centering \subfigure[nMSE of Gaussian targets]{\includegraphics[width=2.3in]{Fig2a}} \subfigure[aAUC of Bernoulli targets]{\includegraphics[width=2.3in]{Fig2b}} \subfigure[nMSE of log of Poisson targets]{\includegraphics[width=2.3in]{Fig2c}} \caption{Imputation performance when the pre-fixed $\hat{k}$ is different with the true $k$.}\label{fig:diffk_simu} \end{figure} \subsubsection{Comparison with Non-FMR Methods}\label{subsubsec:sim_non_FMR} We compare the imputation performance of our~\methodname\, methods \textbf{Mix} and \textbf{Mix GS} with all the non-FMR methods. We choose the data set used in Section~\ref{subsubsec:sim_diff_k} with the true $k=3$. The Poisson targets are removed since many other methods are not able to handle them. {The tuned $\hat{k}=3$.} In Table~\ref{tab:comp_base}, our~\methodname\, methods \textbf{Mix} and \textbf{Mix GS} not only outperform their special cases, i.e., \textbf{LASSO} and \textbf{Group LASSO}, respectively, but also outperform other multi-task learning methods, including those handling certain kinds of heterogeneities. \begin{table}[htbp]\small \centering \renewcommand{\multirowsetup}{\centering} \begin{tabular}{lcc} \hline &nMSE &aAUC\\ \hline LASSO & 0.6892 & 0.7384\\ \hline Mix & \textbf{0.1181} & 0.9525\\ \hline Group LASSO & 0.6850 & 0.7482\\ \hline Mix GS & 0.1212 & \textbf{0.9559}\\ \hline Sep L2 & 0.6912 & 0.7355\\ \hline GO-MTL & 0.8055 & 0.7259\\ \hline CMTL & 0.6916 & 0.7344\\ \hline MSMTFL & 0.6890 & 0.7381\\ \hline TraceReg & 0.6913 & 0.7362\\ \hline SparseTrace & 0.6904 & 0.7374\\ \hline RMTL & 0.6913 & 0.7362\\ \hline Dirty & 0.6850 & 0.7482\\ \hline rMTFL & 0.6850 & 0.7482\\ \hline \end{tabular} \caption{Comparison with non-FMR methods}\label{tab:comp_base} \end{table} \subsubsection{Detection of Anomaly Tasks}\label{subsubsec:sim_anomaly_task} We set $n=2000$. The number of tasks (responses) $m=30$. The information about the true $k$s and numbers of different types of tasks is in Table~\ref{tab:data4}. Other settings are the same as in Section~\ref{subsubsec:sim_diff_k}. In Table~\ref{tab:data4}, it can be seen that the true $k$ of the majority of tasks (the first 20 tasks) is 4. The first 20 tasks are referred to as concordant tasks, while the other 10 tasks are referred to as anomaly tasks. \begin{table}[htbp]\small \centering \begin{tabular}{ccccc} \hline Group & True k & \#Gaussian & \#Bernoulli & \#Poisson \\ \hline 1& 4 & 5 & 10 & 5 \\ 2& 1 & 1 & 1 & 1 \\ 3& 6 & 1 & 0 & 0 \\ 4& 2 & 1 & 1 & 0 \\ 5& 3 & 0 & 1 & 1 \\ 6& 5 & 1 & 1 & 0 \\ \hline \end{tabular} \caption{True $k$s and numbers of different types of tasks.}\label{tab:data4} \end{table} We compute the concordant scores using~\eqref{eq:outlier_score} for the tasks. In Fig~\ref{fig:outlier_score}, the concordant scores separate concordant tasks and anomaly tasks quite well. { Scores of Poisson tasks are similar to scores of Bernoulli tasks, because they all provide less accurate information than Gaussian tasks do.} \begin{figure}[htbp]\small \centering \subfigure[Mix]{\includegraphics[width=2.3in]{Fig3a}} \subfigure[Mix GS]{\includegraphics[width=2.3in]{Fig3b}} \caption{Concordant scores of tasks{, which are associated with Table~\ref{tab:data4}}. (a) estimated by \textbf{Mix}; (b) estimated by \textbf{Mix GS}. The first 20 tasks are concordant tasks, the last 10 tasks are anomaly tasks. {The first 5 tasks are Gaussian tasks, the subsequent 10 tasks are Bernoulli tasks and then the subsequent 5 tasks are Poisson tasks.}}\label{fig:outlier_score} \end{figure} { \subsubsection{Handling Clustered Relationship among tasks}\label{subsubsec:simu_task_cluster} We construct 4 groups of tasks. The total number of tasks (responses) $m=60$. The information about the true $k$s and numbers of different types of tasks is in Table~\ref{tab:data6}. Other settings are the same as in Section~\ref{subsubsec:sim_anomaly_task}. We first apply \textbf{Single} for each task, setting $\hat{k} = 20$. Then we apply the strategy in Section~\ref{subsec:clustered_tasks} to construct a similarity matrix by NMI defined in~\eqref{eq:NMI}. Kernel PCA~\citep{scholkopf1998nonlinear,van2009dimensionality} is then applied using the similarity matrix as the kernel matrix. The similarity matrix and the result of Kernel PCA are shown in Fig~\ref{fig:simu_task_cluster}. \begin{table}[htbp]\small \centering \begin{tabular}{ccccc} \hline Group & True k & \#Gaussian & \#Bernoulli & \#Poisson \\ \hline 1 &1 & 3 & 10 & 2 \\ 2 &2 & 3 & 10 & 2 \\ 3 &3 & 3 & 10 & 2 \\ 4 &4 & 3 & 10 & 2 \\ \hline \end{tabular} \caption{True $k$s and numbers of different types of tasks. Tasks are clustered into 4 groups.}\label{tab:data6} \end{table} \begin{figure}[htbp]\small \centering \subfigure[Similarity Matrix]{\includegraphics[width=2.3in]{Fig4a}} \subfigure[Dimension Reduction by Kernel PCA]{\includegraphics[width=2.3in]{Fig4b}} \caption{(a) Similarity matrix among tasks described in Table~\ref{tab:data6}; (b) Relationship among tasks shown by Kernel PCA.}\label{fig:simu_task_cluster} \end{figure} In Fig~\ref{fig:simu_task_cluster} (a), Group 2,3 and 4 can be recognized as three groups. In Group 1, each task shows no similarity with other tasks, because with the true $k=1$, the data samples can be randomly partitioned into $\hat{k} = 20$ sub-populations, which results in low NMI scores. In Fig~\ref{fig:simu_task_cluster} (b), basically, 4 groups of tasks are clustered into 4 different regions. } \subsubsection{Handling Outlier Samples}\label{subsubsec:simu_outlier_sample} We choose the data set used in Section~\ref{subsubsec:sim_diff_k} with the true $k = 2$, then randomly shuffle the data pairs $(\y_i,\x_i)$, for $i=1,\ldots,n$, and contaminate the true targets by the following procedure. For outlier ratio $p_{\mbox{outlier}} = 0\% , 1\% , 2\% , 5\% , 8\% , 10\%$, (1) for Gaussian targets, set all the targets of $p_{\mbox{outlier}}$ of data samples to be $100$; (2) for Bernoulli targets, set all the targets of $p_{\mbox{outlier}}$ of data samples to be $1$. Such contamination is only performed on training and validation data, leaving testing data clean. Then we evaluate two groups of methods. For the group of non-robust methods, we choose our~\methodname\, methods \textbf{Mix} and \textbf{Mix GS}. For the group of robust methods, we firstly run the robust version of the non-robust methods by adding $\zzeta$ in the natural parameter models as~\eqref{eq:outlier_g} and adding~\eqref{eq:pen_outlier_group} as the additional penalty, then we clean the data by removing $p_{\mbox{outlier}}$ of data samples associated with the largest value of $\sqrt{\sum_{jr}\zeta_{ijr}^2}$ ($i\in\{1,\ldots,n\}$). Finally, we run their non-robust version of methods on the ``cleaned'' data, respectively. We follow~\citet{gong2012robust} to adopt such two-stage strategy. The imputation performances are reported in Table~\ref{tab:comp_sample_outlier_simu}, from where it can be seen that, 1) when $p_{\mbox{outlier}} = 0\%$, robust methods are over-parameterized and may underperform non-robust methods; 2) when $p_{\mbox{outlier}} > 0\%$, robust methods significantly outperform non-robust methods. \setlength{\tabcolsep}{2pt} \begin{table}[htbp]\small \centering \renewcommand{\multirowsetup}{\centering} \begin{tabular}{ccccccccc} \hline & & & 0\% & 1\% & 2\% & 5\% & 8\% & 10\% \\ \hline \multirow{4}{*}{\myminitab[c]{nMSE \\ for Gaussian}} & \multirow{2}{*}{\textbf{Mix}} & non-robust & 0.0625 & 0.6754 & 0.6894 & 1.0122 & 1.3250 & 1.4953\\ \cline{3-9} & & robust & 0.0620 & 0.0627 & \textbf{0.0626} & 0.0737 & 0.0632 & 0.0635\\ \cline{2-9} &\multirow{2}{*}{\textbf{Mix GS}} & non-robust & 0.0658 & 0.6434 & 0.6741 & 0.7505 & 1.0736 & 1.2939\\ \cline{3-9} & & robust & \textbf{0.0599} & \textbf{0.0611} & 0.0673 & \textbf{0.0694} & \textbf{0.0602} & \textbf{0.0607}\\ \hline \multirow{4}{*}{aAUC} & \multirow{2}{*}{\textbf{Mix}} & non-robust & 0.9571 & 0.7954 & 0.7961 & 0.7982 & 0.7986 & 0.7981\\ \cline{3-9} & & robust & 0.9570 & 0.9571 & \textbf{0.9574} & \textbf{0.9519} & 0.9568 & 0.9567\\ \cline{2-9} &\multirow{2}{*}{\textbf{Mix GS}} & non-robust & 0.9509 & 0.7979 & 0.7984 & 0.7982 & 0.7979 & 0.7952\\ \cline{3-9} & & robust & \textbf{0.9581} & \textbf{0.9577} & 0.9519 & 0.9482 & \textbf{0.9578} & \textbf{0.9574}\\ \hline \multirow{4}{*}{\myminitab[c]{nMSE \\ for Poisson}} & \multirow{2}{*}{\textbf{Mix}} & non-robust & 0.2089 & 0.7368 & 0.6905 & 0.6528 & 0.6642 & 0.6736\\ \cline{3-9} & & robust & \textbf{0.2086} & \textbf{0.2105} & \textbf{0.2099} & 0.2345 & 0.2222 & \textbf{0.2230}\\ \cline{2-9} &\multirow{2}{*}{\textbf{Mix GS}} & non-robust & 0.2136 & 0.7416 & 0.7795 & 0.6587 & 0.6688 & 0.8665\\ \cline{3-9} & & robust & 0.2087 & 0.2109 & 0.2169 & \textbf{0.2202} & \textbf{0.2212} & 0.2236\\ \hline \end{tabular} \caption{Comparison between methods handling outlier samples on synthetic data.}\label{tab:comp_sample_outlier_simu} \end{table} { \subsubsection{Feature-Based Prediction by MOE}\label{subsubsec:simu_MOE} We set the true $k=3$. The true $\aalpha\in \mathbb{R}^{d\times k}$, whose first four rows are non-zero. The non-zero entries of $\aalpha$ are drawn from $\mathcal{N}(0,1)$. Number of data samples $n=1000$. For all $i=1,\ldots,n,r=1,\ldots,k$, the $i$th data sample coming from the $r$th sub-population obeys a multinomial distribution with the probability defined in~\eqref{eq:gate_prob}. Other settings are the same as in Section~\ref{subsubsec:sim_non_FMR}. We compare our~\methodname\, methods \textbf{Mix MOE} and \textbf{Mix MOE GS}. The prediction performances are shown in Table~\ref{tab:comp_MOE}, which are consistent with the results in Section~\ref{subsubsec:sim_non_FMR}. We further show in Table~\ref{tab:comp_nmi_pred} the concordance between $p(\delta_{i,r} = 1\mid \x_i,\hat{\alpha}_r )$ and $p(\delta_{i,r} = 1\mid \x_i, \alpha_{0,r} )$, where $\aalpha_0$ denotes the true $\aalpha$, for all $i=1,\ldots,n,r=1,\ldots,k$, for both training and testing data. In~\eqref{eq:update_alpha_MOE}, $\aalpha$ is optimized by partially minimizing the discrepancy between $p(\delta_{i,r} = 1\mid \x_i,\hat{\alpha}_r )$ and $ \hat{\rho}^{(t+1)}_{i,r}$ for $t=0,\ldots,T-1$. As such we also show the concordance between $p(\delta_{i,r} = 1\mid \x_i,\hat{\alpha}_r )$ and $ \hat{\rho}^{(T)}_{i,r} = p(\delta_{i,r} = 1 \mid y_{ij'},j' \in \Omega_i,\x_i,\hat{\theta}_2)$. The concordances are measured by NMI defined in~\eqref{eq:NMI}. We use NMI instead of KL-divergence, because NMI is normalized to the range of $[0,1]$. Both $p(\delta_{i,r} = 1\mid \x_i, \alpha_{0,r} )$ and $p(\delta_{i,r} = 1 \mid y_{ij'},j' \in \Omega_i,\x_i,\hat{\theta}_2)$ are approximated accurately on the training data. The approximation accuracies are lower on the testing data because the deficiency of data samples comparing with the dimension. \begin{table}[htbp]\small \centering \renewcommand{\multirowsetup}{\centering} \begin{tabular}{lcc} \hline &nMSE &aAUC\\ \hline LASSO & 0.6390 & 0.7834\\ \hline Mix MOE & 0.0656 & 0.9466\\ \hline Group LASSO & 0.6348 & 0.7878\\ \hline Mix MOE GS & \textbf{0.0579} & \textbf{0.9502}\\ \hline Sep L2 & 0.6481 & 0.7794\\ \hline GO-MTL & 0.6946 & 0.7778\\ \hline CMTL & 0.6496 & 0.7796\\ \hline MSMTFL & 0.6397 & 0.7831\\ \hline TraceReg & 0.6509 & 0.7790\\ \hline SparseTrace & 0.6473 & 0.7805\\ \hline RMTL & 0.6511 & 0.7797\\ \hline Dirty & 0.6348 & 0.7878\\ \hline rMTFL & 0.6483 & 0.7787\\ \hline \end{tabular} \caption{Prediction performances based on only features.}\label{tab:comp_MOE} \end{table} \begin{table}[htbp]\small \centering \renewcommand{\multirowsetup}{\centering} \begin{tabular}{lcccc} \hline & \multicolumn{2}{c}{Training} & \multicolumn{2}{c}{Testing}\\ \hline &$C(\hat{\aalpha}\parallel \aalpha_0 )$& $C(\hat{\aalpha}\parallel \hat{\theta}_2 )$ &$C(\hat{\aalpha}\parallel \aalpha_0 )$& $C(\hat{\aalpha}\parallel \hat{\theta}_2 )$\\ \hline Mix MOE & 0.9863 & 0.9918 &0.8440 & 0.8457\\ \hline Mix MOE GS& \textbf{0.9962} &\textbf{0.9933} & \textbf{0.8455}& \textbf{0.8516}\\ \hline \end{tabular} \caption{Approximation performances based on only features. $C(\hat{\aalpha}\parallel \aalpha_0 )$ denotes the concordance between $p(\delta_{i,r} = 1\mid \x_i,\hat{\alpha}_{r} )$ and $p(\delta_{i,r} = 1\mid \x_i, \alpha_{0,r} )$, where $\aalpha_0$ denotes the true $\aalpha$. $C(\hat{\aalpha}\parallel \hat{\theta}_2 )$ denotes the concordance between $p(\delta_{i,r} = 1\mid \x_i,\hat{\alpha}_r )$ and $p(\delta_{i,r} = 1 \mid y_{ij'},j' \in \Omega_i,\x_i,\hat{\theta}_2)$. The concordances are measured by NMI defined in~\eqref{eq:NMI}.}\label{tab:comp_nmi_pred} \end{table} } { \subsubsection{Scalability}\label{subsubsec:simu_scalability} We discuss the scalability of our method for increasing number of features and tasks. The running time is evaluated. We choose the data set used in Section~\ref{subsubsec:sim_diff_k} with the true $k=4$. The sparsity $s$ is fixed to be 4. We set the number of features $d \in \{32,64,128,256,512\}$ and the number of tasks $m\in\{15,30,60,120,240\}$. The ratios between the numbers of Gaussian, Bernoulli and Poisson tasks are the same as in Section~\ref{subsubsec:sim_diff_k}. We randomly generate 100 data sets for each pair of $(d,m)$. We report the results of the method \textbf{Mix GS} only, as the results of \textbf{Mix} are similar. In each case, $\hat{k}$ is tuned and is equal to the true $k=4$. The estimated parameters in different cases may have different numbers of relevant features. As such, in order to provide a fair comparison, we report the running time per feature, i.e., running time divided by the number of non-zero features of the estimated parameters in each case. In Fig~\ref{fig:simu_scalability}, both dimension $d$ and the number of tasks $m$ have no significant influence on running time per feature, especially when $d$ and $m$ is large, which is consistent with our time-complexity analysis in Section~\ref{subsec:optimization}. \begin{figure}[htbp]\small \centering \subfigure[Training Time]{\includegraphics[width=2.3in]{Fig5a}} \subfigure[Testing Time]{\includegraphics[width=2.3in]{Fig5b}} \caption{Running time per feature when dimension and the number of tasks grow. (a) reports the running time per feature for training the model; (b) reports the running time per feature for testing.}\label{fig:simu_scalability} \end{figure} } \subsection{Application} On the real-world data sets, we first demonstrate the existence of the heterogeneity of conditional relationship, then report the superiority of our~\methodname\, method over other methods considered in Section~\ref{subsec:method_comp}. We further interpret the advantage of our method by presenting the selected features. {Effectiveness of anomaly-task detection and task clustering strategy is also validated.} \subsubsection{Data Description} Both real-world data sets introduced in the following are longitudinal surveys for elder patients, which includes a set of questions. Some of the question answers are treated as input features and some of the questions related to indices of geriatric assessments are treated as targets. \noindent\underline{\emph{\textbf{LSOA II Data}}}. This data is from the Second Longitudinal Study of Aging (LSOA II) \footnote{https://www.cdc.gov/nchs/lsoa/lsoa2.htm.}. LSOA II is a collaborative study by the National Center for Health Statistics (NCHS) and the National Institute of Aging conducted from 1994-2000. A national representative sample of $9447$ subjects $70$ years of age and over were selected and interviewed. Three separated interviews were conducted during the periods of 1994-1996, 1997-1998, and 1999-2000, respectively. The interviews are referred to as WAVE 1, WAVE 2, and WAVE 3 interviews, respectively. We use data WAVE 2 and WAVE 3, which includes a total of $4299$ sample subjects and 44 targets, and $188$ features are extracted from WAVE 2 interview. Among the targets, specifically, three self-rated health measures, including overall health status, memory status and depression status, can be regarded as continuous outcomes; there are 41 binary outcomes, which fall into several categories: fundamental daily activity, extended daily activity, social involvement, medical condition, on cognitive ability, and sensation condition. The features include records of demographics, family structure, daily personal care, medical history, social activity, health opinion, behavior, nutrition, health insurance and income and assets, the majority of which are binary measurements. Both targets and features have missing values due to non-response and questionnaire filtering. The average missing value rates in targets and features are 13.7\% and 20.2\%, respectively. For the missing values in features, we adopt the following procedure for pre-processing. For continuous features, the missing values are imputed with sample mean. For binary features, a better approach is to treat missing as a third category as it may also carry important information; as such, two dummy variables are created from each binary feature with missing values (the third one is not necessary.) This results in totally $d=293$ features. We randomly select 30\% of the samples for training, 30\% for validation and the rest for testing. \noindent\underline{\emph{\textbf{easySHARE Data}}}. This data is a simplified data set from the Survey of Heath, Aging, and Retirement in Europe (SHARE)\footnote{http://www.share-project.org/data-access-documentation.html.}. SHARE includes multidisciplinary and cross-national panel databases on health, socio-economic status, and social and family networks of more than 85,000 individuals from $20$ European countries aged $50$ or over. Four waves of interviews were conducted during 2004 - 2011, and are referred to as WAVE 1 to WAVE 4 interviews. We use WAVE 1 and WAVE 2, which includes 20,449 sample persons and 15 targets (among which 11 are binary, and 4 are continuous), and totally 75 features are constructed from WAVE 1 interview. The targets are from four interview modules: social support, mental health, functional limitation indices and cognitive function indices. The features cover a wide range of assessments, including demographics, household composition, social support and network, physical health, mental health, behavior risk, healthcare, occupation and income. Detailed description features are not listed in this paper. Both targets and features have missing values due to non-response and questionnaire filtering. The average missing value rates in targets and features are 6.9\% and 5.1\%, respectively. The same pre-processing procedure as that for LSOA II Data has been adopted and results in totally $d=118$ features. We randomly select 10\% of the samples for training, 10\% for validation and the rest for testing. \subsubsection{Comparison with FMR Method}\label{subsubsec:real_comp_FMR} In this experiment, we compare our proposed~\methodname\, methods \textbf{Mix} and \textbf{Mix GS} which handle mixed type of outcomes with \textbf{Sep} which learns different types of tasks separately. \textbf{Single} is abandoned because it learns each task independently and is not able to use targets of other tasks to help increasing imputation performance. Results are reported in Fig~\ref{fig:diffk_simu_real}, where 1) for both the real data sets, basically, the best pre-fixed $\hat{k}>1$, except for Bernoulli tasks of easySHARE data, suggesting that the heterogeneity of conditional relationship exists in LSOA II data and the Gaussian tasks of easySHARE data; 2) FMR models benefit Gaussian targets more than Bernoulli targets; 3) \textbf{Mix} and \textbf{Mix GS} outperform \textbf{Sep} in Gaussian tasks. However, their performances are comparable with \textbf{Sep} in Bernoulli tasks, which may be because that the number of Bernoulli tasks are much more than that of Gaussian tasks such that the benefit from Gaussian tasks is limited. \begin{figure}[htbp]\small \centering \subfigure[nMSE of Gaussian targets]{\includegraphics[width=2.3in]{Fig6a}} \subfigure[aAUC of Bernoulli targets]{\includegraphics[width=2.3in]{Fig6b}} \subfigure[nMSE of Gaussian targets]{\includegraphics[width=2.3in]{Fig6c}} \subfigure[aAUC of Bernoulli targets]{\includegraphics[width=2.3in]{Fig6d}} \caption{Comparison with \textbf{Sep} on real data sets. (a) and (b) are results on LSOA II data, (c) and (d) are results on easySHARE data.}\label{fig:diffk_simu_real} \end{figure} \subsubsection{Comparison with Non-FMR Methods In this experiment we test imputation performance, comparing our~\methodname\, methods \textbf{Mix} and \textbf{Mix GS} with all the non-FMR methods. Results are reported in Table~\ref{tab:comp_base_real}, where 1) our~\methodname\, methods \textbf{Mix} and \textbf{Mix GS} not only outperform their special cases, \textbf{LASSO} and \textbf{Group LASSO}, respectively, but also outperform other methods, including those handling certain kinds of heterogeneities, except for aAUC on easySHARE, the reason of which has been discussed in Section~\ref{subsubsec:real_comp_FMR}; 2) \textbf{Mix GS} increases nMSE by 9.76\% and 14.37\% on LSOA II data and easySHARE data, respectively, comparing with its non-FMR version \textbf{Group LASSO}. The similar improvements by \textbf{Mix} are witnessed as well. \begin{table}[htbp]\small \centering \renewcommand{\multirowsetup}{\centering} \begin{tabular}{ccccc} \hline &\multicolumn{2}{c}{LSOA II}& \multicolumn{2}{c}{easySHARE}\\ \hline &nMSE &aAUC &nMSE &aAUC\\ \hline LASSO & 0.7051 & 0.7474 & 0.7869 & 0.7386\\ \hline Mix & 0.6408 & \textbf{0.7525} &0.6601 & 0.7419 \\ \hline Group LASSO & 0.6975 & 0.7413 & 0.7897 & 0.7413 \\ \hline Mix GS & \textbf{0.6294} & 0.7481 & \textbf{0.6548} & 0.7402\\ \hline Sep L2 & 0.7176 & 0.7392 & 0.7796 & 0.7464\\ \hline GO-MTL & 0.8516 & 0.6972 & 0.8231 & 0.7288\\ \hline CMTL & 0.8186 & 0.7089 & 0.7958 & 0.7364\\ \hline MSMTFL & 0.7028 & 0.7473 & 0.7803 & 0.7411 \\ \hline TraceReg & 0.7150 & 0.7408 & 0.7809 & \textbf{0.7496} \\ \hline SparseTrace & 0.6972 & 0.7475 & 0.7791 & 0.7475\\ \hline RMTL & 0.7145 & 0.7418 & 0.7808 & 0.7496\\ \hline Dirty & 0.7032 & 0.7480 & 0.7781 & 0.7486\\ \hline rMTFL & 0.6953 & 0.7418 &0.7781 & 0.7486\\ \hline \end{tabular} \caption{Comparison with non-FMR methods on real data sets}\label{tab:comp_base_real} \end{table} \subsubsection{Feature Selection}\label{subsubsec:feature_selection} We consider demonstrating the advantage of our~\methodname\, method on feature selection. We compare our~\methodname\, method \textbf{Mix GS} with its non-FMR version \textbf{Group LASSO}. Both methods select shared features across tasks. We collect the unique features that only selected for each sub-population. For LSOA II data set, {the tuned $\hat{k}=2$}. \textbf{Mix GS} selects $47/294$ features (summing up selected features of both sub-populations), while \textbf{Group LASSO} selects $48/294$ features. Descriptions of unique features of both sub-populations are listed in Table~\ref{tab:sp_feature_disc_data_1}. Sub-population 1 seems considering worse condition of patients. \setlength{\tabcolsep}{2pt} \begin{table}[htbp]\small \centering \begin{tabular}{ll} \hline Sub-population 1 ($\pi_1 = 70.09\%$) & Sub-population 2 ($\pi_2 = 29.91\%$)\\ \hline able or prevented to leave house & times seen doctor in past 3 months\\ have problems with balance & easier or harder to walk 1/4 mile\\ total number of living children & \textbf{widowed}\\ easier/harder than before: in/out of bed & \textbf{follow regular physical routine}\\ \textbf{\#(ADL activities) SP is unable to perform} & \textbf{present social activities}\\ easier or harder to walk 10 steps & \textbf{ever had a stress test}\\ do you take aspirin & \textbf{do you take vitamins}\\ \textbf{often troubled with pain} & \textbf{necessary to use steps or stairs}\\ visit homebound friend for others & \textbf{had flu shot}\\ ever had a hysterectomy & \textbf{ever had cataract surgery}\\ & \textbf{physical activity more/less/same}\\ \hline \end{tabular} \caption{Descriptions of unique features of each sub-population of LSOA II data. Features are sorted in descending order by the $\|\bbeta_r^l\|_2$ where $\bbeta_r^l$ is the $l$th row of $\bbeta_r$ ($l = 1,\ldots,d$). The bold denote the features that are not selected by \textbf{Group LASSO}. ``\#($\cdot$)'' denotes the number of the enclosed events. ``ADL'' denotes Activity of Daily Livings. ``SP'' denotes Standardized Patients. }\label{tab:sp_feature_disc_data_1} \end{table} For easySHARE data set, {the tuned $\hat{k}=5$}. \textbf{Mix GS} selects $58/118$ features, while \textbf{Group LASSO} selects $57/118$ features. Descriptions of unique features of two sub-populations are listed in Table~\ref{tab:sp_feature_disc_data_2}. Sub-population 1 seems considering more about personality and experience, while sub-population 2 seems considering more about politics and education. For both real data sets, our~\methodname\, method \textbf{Mix GS} recalls more useful features than \textbf{Group LASSO} does. \setlength{\tabcolsep}{2pt} \begin{table}[htbp]\small \centering \begin{tabular}{ll} \hline Sub-population 1 ($\pi_1 = 21.31\%$) & Sub-population 2 ($\pi_2 = 26.36\%$)\\ \hline \textbf{fatigue} & \textbf{taken part in a political organization}\\ guilt & \textbf{attended an educational or training course}\\ enjoyment & \textbf{taken part in religious organization}\\ suicidality & \textbf{none of social activities}\\ tearfullness & \textbf{cared for a sick or disabled adult}\\ \textbf{interest} & \textbf{done voluntary or charity work}\\ \textbf{current job situation:sick} & \textbf{education: lower secondary}\\ & \textbf{education: first tertiary}\\ & \textbf{education: post secondary}\\ & \textbf{education: upper secondary}\\ & \textbf{education: primary}\\ & \textbf{education: second tertiary}\\ \hline \end{tabular} \caption{Descriptions of unique features of two sub-populations of easySHARE data. Features are sorted in descending order by the $\|\bbeta_r^l\|_2$ where $\bbeta_r^l$ is the $l$th row of $\bbeta_r$ ($l = 1,\ldots,d$). The bold denote the features that are not selected by \textbf{Group LASSO}. }\label{tab:sp_feature_disc_data_2} \end{table} \subsubsection{Detection of Anomaly Tasks}\label{subsubsec:real_anmaly_task} We firstly use~\eqref{eq:outlier_score} to compute concordant scores of tasks, which are reported in Fig~\ref{fig:outlier_score_real}. Clear separations are witnessed on both data sets. We select one-third of tasks with highest scores as concordant tasks and another third with lowest scores as anomaly tasks. The descriptions of the concordant and anomaly tasks are listed in Table~\ref{tab:task_disc_data_1} and Table~\ref{tab:task_disc_data_2}, respectively. \begin{figure}[htbp]\small \centering \subfigure[LSOA II data set]{\includegraphics[width=2.3in]{Fig7a}} \subfigure[easySHARE data set]{\includegraphics[width=2.3in]{Fig7b}} \caption{Concordant scores of tasks, which were estimated by \textbf{Mix GS}. The tasks are reordered according to the scores.}\label{fig:outlier_score_real} \end{figure} \setlength{\tabcolsep}{2pt} \begin{table}[htbp]\small \centering \begin{tabular}{ll} \hline Concordant tasks (top 7) & Anomaly tasks (top 8)\\ \hline have difficulty dressing & go to movies, sports, events, etc.\\ have difficulty doing light housewrk & now have asthma\\ have difficulty using toilet & now have arthritis\\ have difficulty managing medication & now have hypertension\\ have difficulty bathing or showering & injured from fall(s)\\ have difficulty managing money & memory of year\\ have difficulty preparing meals & have deafness\\ & get together with relatives\\ \hline \end{tabular} \caption{Descriptions of tasks of LSOA II data}\label{tab:task_disc_data_1} \end{table} \setlength{\tabcolsep}{2pt} \begin{table}[htbp]\small \centering \begin{tabular}{ll} \hline Concordant tasks (top 5) & Anomaly tasks (top 5)\\ \hline activities of daily living index & numeracy score\\ instrumental activities of daily living indices & gone to sport social or other kind of club\\ mobility index & recall of words first trial\\ appetite & give help to others outside the household\\ orientation to date & provided help to family friends or neighbors\\ \hline \end{tabular} \caption{Descriptions of tasks of easySHARE data}\label{tab:task_disc_data_2} \end{table} The concordant tasks detected by our methods seem truly correlated with each other intuitively. And the information of detected anomaly tasks is diverse and seems different with that of concordant tasks. { For each data set, we apply our~\methodname\, method \textbf{Mix} (and \textbf{Mix GS}) to build two models for non-anomaly tasks (the first two-third tasks) and anomaly tasks, respectively. For LSOA II data set, the tuned $\hat{k}=4$ and $1$ for non-anomaly tasks and anomaly tasks, respectively. For easySHARE data set, the tuned $\hat{k}=6$ and $2$ for non-anomaly tasks and anomaly tasks, respectively. Averaged imputation performances are shown in Table~\ref{tab:anomaly_tasks}. By providing separate models to handle anomaly tasks, the performances improve significantly, where \textbf{Mix GS} outperforms \textbf{Mix}, maybe because the non-anomaly tasks share some relevant features. \setlength{\tabcolsep}{3.5pt} \begin{table}[htbp]\small \centering \renewcommand{\multirowsetup}{\centering} \begin{tabular}{lcccc} \hline & \multicolumn{2}{c}{LSOA II} & \multicolumn{2}{c}{easySHARE}\\ \hline & nMSE & aAUC & nMSE & aAUC \\ \hline Mix - All tasks & 0.6408 & 0.7525 &0.6601 & 0.7419 \\ \hline Mix - Handle anomalies &0.5979 & 0.7602 &0.6569 & 0.7370 \\ \hline Mix GS - All tasks & 0.6294 & 0.7481 & 0.6548 & 0.7402 \\ \hline Mix GS - Handle anomalies & \textbf{0.5923 } & \textbf{0.7649} & \textbf{0.6462} & \textbf{0.7447} \\ \hline \end{tabular} \caption{Comparison for imputation performances. ``All tasks'' denotes building one FMR model for all the tasks. ``Handle anomalies'' denotes building two models for non-anomaly tasks and anomaly tasks, respectively.}\label{tab:anomaly_tasks} \end{table} } { \subsubsection{Handling Clustered Relationship among tasks}\label{subsubsec:real_task_cluster} We adopt the same strategy as that in Section~\ref{subsubsec:simu_task_cluster} to construct a similarity matrix and perform dimension reduction for each of the real-world data sets. For LSOA II data set, the similarity matrix and results of 2D reduction are shown in Fig~\ref{fig:real_task_cluster_LSOA}. In Fig~\ref{fig:real_task_cluster_LSOA}(b), tasks are partitioned into groups. We apply k-means algorithm to separate the tasks into 4 groups. Tasks in Group 1 are mainly about current status. The descriptions of tasks of Group 2 are ``how often felt sad or depressed in the past 12 months'' and ``self rated memory''. Tasks in Group 3 and 4 are about having difficulty performing some certain actions. Group 3 is similar to Group 4, which can be reflected by Fig~\ref{fig:real_task_cluster_LSOA}(b). \begin{figure}[htbp]\small \centering \subfigure[Similarity Matrix]{\includegraphics[width=2.3in]{Fig8a}} \subfigure[Dimension Reduction by Kernel PCA]{\includegraphics[width=2.3in]{Fig8b}} \caption{Clustered Relationship among tasks on LSOA II. (a) Similarity matrix among tasks. First three tasks are Gaussian tasks. Other tasks are Bernoulli tasks. (b) Relationship among tasks shown by Kernel PCA.}\label{fig:real_task_cluster_LSOA} \end{figure} For easySHARE data set, the similarity matrix and results of 2D reduction are shown in Fig~\ref{fig:real_task_cluster_easyshare}. In Fig~\ref{fig:real_task_cluster_easyshare}(b), tasks are partitioned into groups as well. We also apply k-means algorithm to separate the tasks into 4 groups. The descriptions of tasks for each group are shown in Table~\ref{tab:clustered_task_easySHARE}, where descriptions of 4 types of interview modules are basically separated into 4 groups, respectively. The only ``misclassified'' task with the description of ``Orientation to date'' seems to be more related to other tasks in Group 2 than the tasks in Group 4. \begin{figure}[htbp]\small \centering \subfigure[Similarity Matrix]{\includegraphics[width=2.3in]{Fig9a}} \subfigure[Dimension Reduction by Kernel PCA]{\includegraphics[width=2.3in]{Fig9b}} \caption{Clustered Relationship among tasks on easySHARE. (a) Similarity matrix among tasks. First four tasks are Gaussian tasks. Other tasks are Bernoulli tasks. (b) Relationship among tasks shown by Kernel PCA.}\label{fig:real_task_cluster_easyshare} \end{figure} \begin{table}[htbp]\small \centering \renewcommand{\multirowsetup}{\centering} \begin{tabular}{cll} \hline Group & Targets &Interview module \\ \hline \multirow{3}*{1} &Activities of daily living index& Functional Limitation Indices \\ &Instrumental activities of daily living index& Functional Limitation Indices \\ &Mobility index &Functional Limitation Indices \\ \hline \multirow{7}*{2} &Depression& Mental Health \\ &Pessimism &Mental Health \\ &Sleep &Mental Health \\ &Irritability &Mental Health \\ &Appetite& Mental Health \\ &Concentration &Mental Health \\ &Orientation to date &Cognitive Function Indices \\ \hline \multirow{3}*{3}&Provided help to family friends or neighbors & Social Support \& Network \\ &Gone to sport social or other kind of club& Social Support \& Network \\ &Give help to others outside the household& Social Support \& Network \\ \hline \multirow{2}*{4}&Recall of words score& Cognitive Function Indices \\ &Numeracy score &Cognitive Function Indices \\ \hline \end{tabular} \caption{Clustered tasks of easySHARE. 15 tasks are clustered into 4 groups.}\label{tab:clustered_task_easySHARE} \end{table} For each data set, we further apply our~\methodname\, methods \textbf{Mix} and \textbf{Mix GS} for each group of tasks. For LSOA II data set, tuned $\hat{k}=3,3,5$ and $2$ for Group 1,2,3 and 4, respectively. For easySHARE data set, tuned $\hat{k}=5,2,1$ and $1$ for Group 1,2,3 and 4, respectively. Imputation performances are shown in Table~\ref{tab:comp_clustered_task_all_task}. Performances increase by building separate models for each group, suggesting that separate models for clustered tasks are more accurate. \setlength{\tabcolsep}{1pt} \begin{table}[htbp]\small \centering \renewcommand{\multirowsetup}{\centering} \begin{tabular}{lcccc} \hline & \multicolumn{2}{c}{LSOA II} & \multicolumn{2}{c}{easySHARE}\\ \hline & nMSE & aAUC & nMSE & aAUC \\ \hline Mix - All tasks & 0.6408 & 0.7525 &0.6601 & 0.7419 \\ \hline Mix - Clustered tasks & 0.6370& \textbf{0.7592} & 0.6552 & 0.7439 \\ \hline Mix GS - All tasks & 0.6294 & 0.7481 & 0.6548 & 0.7402\\ \hline Mix GS - Clustered tasks & \textbf{0.6202} & 0.7559 & \textbf{0.6533} & \textbf{0.7474}\\ \hline \end{tabular} \caption{Comparison for imputation performances. ``All tasks'' denotes building one FMR model for all the tasks. ``Clustered tasks'' denotes building different FMR models for different groups of tasks.}\label{tab:comp_clustered_task_all_task} \end{table} } { \subsubsection{Feature-Based Prediction by MOE}\label{subsubsec:real_MOE} We compare the methods using only features to predict targets on both real-world data sets. Our proposed MOE type of~\methodname\, methods, \textbf{Mix MOE} and \textbf{Mix MOE GS}, are compared with the non-FMR methods. We also integrate our strategies to handle anomaly tasks and clustered structure among tasks in both our proposed MOE type of~\methodname\, methods \textbf{Mix MOE} and \textbf{Mix MOE GS}. Concretely, we use the anomaly-task detection results in Section~\ref{subsubsec:real_anmaly_task} and the task clustering results in Section~\ref{subsubsec:real_task_cluster}. The prediction results are reported in Table~\ref{tab:comp_base_real_MOE_combine}. Our proposed~\methodname\, method \textbf{Mix MOE} and \textbf{Mix MOE GS} outperform baseline methods on LSOA II and on Gaussian tasks of easySHARE, which is consistent with the results in Table~\ref{tab:comp_base_real}. In addition, by integrating our task clustering strategy, our proposed~\methodname\, methods \textbf{Mix MOE TC} and \textbf{Mix MOE GS TC} outperform other methods on Gaussian targets, while providing comparable results on Bernoulli tasks. \textbf{Mix MOE TC} and \textbf{Mix MOE GS TC} even outperform our proposed~\methodname\, methods \textbf{Mix MOE Robust} and \textbf{Mix MOE GS Robust} on Gaussian targets, suggesting that it is more accurate to build a specific model for each cluster of tasks. Comparing Table~\ref{tab:comp_base_real_MOE_combine} with Table~\ref{tab:comp_base_real}, our MOE methods do not rival our FMR methods. We investigate the reason by showing the concordance between $p(\delta_{i,r} = 1\mid \x_i,\hat{\alpha}_r )$ and $p(\delta_{i,r} = 1 \mid y_{ij'},j' \in \Omega_i,\x_i,\hat{\theta}_2) = \hat{\rho}_{i,r}^{(T)}$ ($\hat{\rho}_{i,r}^{(T)}$ is defined in equation~\ref{eq:cond_prob_t_MOE}) in Table~\ref{tab:comp_nmi_pred_real}. In Table~\ref{tab:comp_nmi_pred_real}, the concordances of conditional probabilities measured by NMI are generally low, especially comparing with the results in Table~\ref{tab:comp_nmi_pred}, suggesting that on both real-world data sets, it is difficult to learn the mixture probabilities. \begin{table}[htbp]\small \centering \renewcommand{\multirowsetup}{\centering} \begin{tabular}{lcccc} \hline &\multicolumn{2}{c}{LSOA II}& \multicolumn{2}{c}{easySHARE}\\ \hline &nMSE &aAUC &nMSE &aAUC\\ \hline LASSO & 0.7051 & 0.7474 & 0.7869 & 0.7386\\ \hline Group LASSO & 0.6975 & 0.7413 & 0.7897 & 0.7413 \\ \hline MSMTFL & 0.7028 & 0.7473 & 0.7803 & 0.7411 \\ \hline Sep L2 & 0.7176 & 0.7392 & 0.7796 & 0.7464\\ \hline GO-MTL & 0.8516 & 0.6972 & 0.8231 & 0.7288\\ \hline CMTL & 0.8186 & 0.7089 & 0.7958 & 0.7364\\ \hline TraceReg & 0.7150 & 0.7408 & 0.7809 & \textbf{0.7496} \\ \hline SparseTrace & 0.6972 & 0.7475 & 0.7791 & 0.7475\\ \hline RMTL & 0.7145 & 0.7418 & 0.7808 & 0.7496\\ \hline Dirty & 0.7032 & 0.7480 & 0.7781 & 0.7486\\ \hline rMTFL & 0.6953 & 0.7418 &0.7781 & 0.7486\\ \hline \hline Mix MOE &0.6935 & \textbf{0.7504} & 0.7991 & 0.7395\\ \hline Mix MOE GS & 0.7054 & 0.7438 & 0.7774 & 0.7387\\ \hline Mix MOE Robust & 0.6906 & 0.7436 & 0.7642 & 0.7351\\ \hline Mix MOE GS Robust & 0.6981 & 0.7430 & 0.7668 & 0.7344\\ \hline Mix MOE TC & \textbf{0.6859} & 0.7333 & \textbf{0.7584} & 0.7389\\ \hline Mix MOE GS TC & 0.6925 & 0.7379 & 0.7657 & 0.7367\\ \hline \end{tabular} \caption{Comparison for prediction performance with non-FMR methods on real data sets. ``Robust'' denotes adopting the strategy to handle anomaly tasks. ``TC'' denotes task clustering strategy.}\label{tab:comp_base_real_MOE_combine} \end{table} \begin{table}[htbp]\small \centering \renewcommand{\multirowsetup}{\centering} \begin{tabular}{lcccc} \hline & \multicolumn{2}{c}{LSOA II} & \multicolumn{2}{c}{easySHARE}\\ \hline &Training&Testing&Training&Testing\\ \hline Mix MOE & {0.2745} & {0.1301} & 0.1314& 0.1068\\ \hline Mix MOE GS & 0.1060 & 0.0673 & {0.2527}& { 0.2054}\\ \hline \end{tabular} \caption{The concordance between $p(\delta_{i,r} = 1\mid \x_i,\hat{\alpha}_r )$ and $p(\delta_{i,r} = 1 \mid y_{ij'},j' \in \Omega_i,\x_i,\hat{\theta}_2)$. The concordances are measured by NMI defined in~\eqref{eq:NMI}.}\label{tab:comp_nmi_pred_real} \end{table} } \section{{Discussions} \& Conclusions} \label{sec:conclusion} In this paper, we propose a novel model~\methodname\, to explore heterogeneities of conditional relationship, output type and shared information among tasks. Based on multivariate-target FMR {and MOE} models, our model jointly learns tasks with mixed type of output, allows incomplete data in the output, imposes inner component-wise group $\ell_1$ constraint and handles anomaly tasks {and clustered structure among tasks}. These key elements are integrated in a unified generalized mixture model setup so that they can benefit from and reinforce each other to discover the triple heterogeneities in data. Rigorous theoretical analyses under the high dimensional framework are provided. { We mainly consider the special setting {of MTL, where} the multivariate outcomes share the same set of instances and the same set of features because our main objective is to learn potentially shared sample clusters and feature sets among tasks. However, {as stressed in the introduction, the main definition of MTL considers tasks that do not necessarily share the same set of samples/instances and the same set of features}, such as distributed learning systems (different tasks have entirely different data instances, see~\citealt{jin2006fast} and~\citealt{boyd2011distributed}) and multi-source learning systems (different tasks have entirely different feature spaces, see~\citealt{zhang2011multi} and~\citealt{jin2015heterogeneous}). For such cases, one can define the specific expected shared information among tasks and then extend our methodology. For example, although tasks do not share the same instances, they could share the same mixture model structure. Then for the distributed learning systems, our model in Section~\ref{sec:method} can still be applied. Additionally, the tasks could still share the pattern/sparsity in feature selection even though the feature sets are different, e.g.,~\citet{liu2009multi} and~\citet{gong2012multi}. Then one can build FMR models for the tasks in which the regression coefficient vectors of the tasks share the same sparsity pattern achieved by group $\ell_1$ penalization. The case of multi-source learning systems can also be handled similarly by embedding features into a shared feature space, e.g.,~\citet{zhang2011multi} and~\citet{jin2015heterogeneous}. } There are many interesting future directions. It is worthwhile to explore the theoretical and empirical performance of non-convex penalties. Meanwhile, different components should share some features, and overlapping cluster pattern of conditional relationship should also be considered in real applications, both of which require further investigation. It is also interesting to explore other low-dimensional structures in the natural parameters, e.g., low-rank structure and its sparse composition~\citep{chen2012reduced}. { Our strategies on handling anomaly tasks and clustered structure among tasks require two stages. It is worthwhile to explore one-stage models to handle such task heterogeneities during a whole learning process. More complicated structure among tasks, such as graph-based structure, should also be explored. Our theoretical results cover our method introduced in Section~\ref{sec:method} and robust estimation introduced in Section~\ref{subsec:robust_estimation}. Nonetheless, theoretical guarantees for other extensions in Section~\ref{sec:extension} are still challenging due to joint learning complicated relationship among tasks and population heterogeneity, which will be focused on in our future research.} \begin{acknowledgements} The authors would like to thank the editors and reviewers for their valuable suggestions on improving this paper. This work of Jian Liang and Changshui Zhang is (jointly or partly) funded by National Natural Science Foundation of China under Grant No.61473167 and Beijing Natural Science Foundation under Grant No. L172037. Kun Chen's work is partially supported by U.S. National Science Foundation under Grants DMS-1613295 and IIS-1718798. The work of Fei Wang is supported by National Science Foundation under Grants IIS-1650723 and IIS-1716432. \end{acknowledgements} \small \appendices \section{Definitions} \begin{mydef}\label{th:def_subexp} $Z = (Z_1,\ldots,Z_{m'})\trans \in \mathbb{R}^{m'} $ has a sub-exponential distribution with parameters $(\sigma,v,t)$ if for $M>t$, it holds \begin{align*} \mathbb{P}(\|Z\|_{\infty}>M)\leq \left\{ \begin{array}{ll} \exp\biggl(-\frac{M^2}{\sigma^2}\biggr), & t\leq M\leq \frac{\sigma^2}{v}\\ \exp\biggl(-\frac{M }{v }\biggr), & M>\frac{\sigma^2}{v}. \end{array} \right. \end{align*} \end{mydef} \section{The Empirical Process} In order to prove the first part of Theorem \ref{th:th_bound} that the bound in (\ref{eq:bound_low}) has the probability in (\ref{eq:prob_bound}), we firstly follow \citet{stadler2010} to define the empirical process for fixed data points $\x_1,\ldots,\x_n$. For $\oby_i = (y_{ij}, j\in\Omega_i)\trans\in \mathbb{R}^{|\Omega_i|}$ and $X = (X_1,\ldots,X_d)$, let \begin{align*} V_n(\theta) = \frac{1}{n}\sum_{i=1}^n\left(\ell_{\theta}(\x_i,\oby_i)-\mathbb{E}[\ell_{\theta}(\x_i,\oby_i)\mid X=\x_i]\right). \end{align*} By fixing some $T\geq 1$ and $\lambda_0\geq 0$, we define an event $\mathcal{T}$ below, upon which the bound in (\ref{eq:bound_low}) can be proved. So the probability of the event $\mathcal{T}$ is the probability in (\ref{eq:prob_bound}). \begin{equation}\label{eq:event_T}\tag{21} \mathcal{T} = \left\{\sup_{\theta \in \tilde{\Theta}} \frac{|V_n(\theta)-V_n(\theta_0)|}{(\|\bbeta-\bbeta_0\|_1 + \|\eta-\eta_0\|_2 )\vee \lambda_0}\leq T\lambda_0 \right\}. \end{equation} It can be seen that, (\ref{eq:event_T}) defines a set of the parameter $\theta$, and the bound in (\ref{eq:bound_low}) will be proved with $\hat{\theta}$ in the set. For group-lasso type estimator, define an event similar to that in (\ref{eq:event_T}) in the following. \begin{equation}\label{eq:event_T_GS}\tag{22} \mathcal{T}_{group} = \left\{\sup_{\theta \in \tilde{\Theta}} \frac{|V_n(\theta)-V_n(\theta_0)|}{(\sum_p\|\bbeta_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_2 + \|\eta-\eta_0\|_2 )\vee \lambda_0}\leq T\lambda_0 \right\}. \end{equation} \section{Lemmas} In order to show that the probability of event $\mathcal{T}$ is large, we firstly invoke the following lemma. \begin{mylem}\label{th:px} Under Condition \ref{th:con_tail}, for model (\ref{eq:exp_fm}) with $\theta_0 \in \tilde{\Theta}$, $M_n$ and $\lambda_0$ defined in (\ref{eq:lambda_0}), some constants $c_6,c_7$ depending on $K$, and for $n\geq c_7$, we have \begin{align*} \mathbb{P}_{\X}\left(\frac{1}{n}\sum_{i=1}^nF(\oby_i)>c_6\lambda_0^2/(mk)\right)\leq \frac{1}{n}, \end{align*} where $\mathbb{P}_{\X}$ denote the conditional probability given $(X_1\trans,\ldots,X_n\trans)\trans=(\x_1\trans,\ldots,\x_n\trans)\trans = \X$, and $ F(\oby_i) = G_1(\oby_i)1\{G_1(\oby_i)>M_n\} + \mathbb{E}[G_1(\oby_i)1\{G_1(\oby_i)>M_n\}\mid X=\x_i],\forall i. $ \end{mylem} A proof is given in Appendix \ref{sec:proof_px}. Then we can follow the Corollary 1 in \citet{stadler2010} to show that the probability of event $\mathcal{T}$ is large below. \begin{mylem}\label{th:pT} Use Lemma \ref{th:px}. For model (\ref{eq:exp_fm}) with $\theta_0 \in \tilde{\Theta}$, some constants $c_7,c_8,c_9,c_{10}$ depending on $K$, for $\mathcal{T}$ is defined in (\ref{eq:event_T}), and for all $T\geq c_{10}$ we have \begin{align*} \mathbb{P}_{\X}(\mathcal{T})\geq 1 - c_9\exp\left(-\frac{T^2(\log n)^2\log(d\vee n)}{c_8}\right) - \frac{1}{n}, \forall n\geq c_7. \end{align*} \end{mylem} A proof is given in Appendix \ref{sec:proof_pT}. \section{Corollaries for Models Considering Outlier Samples}\label{sec:outlier} When considering outlier samples and modifying the natural parameter model as in \eqref{eq:outlier_g}, we can show in this section the similar results. First, as $\bbeta$ and $\zzeta$ are treated in the similar way, we denote them together by $\xxi\in \mathbb{R}^{((d+n)\times m)\times k}$, and $\xi = vec(\xxi) \in\mathbb{R}^{(d+n)mk}$ such that for all $r = 1,\ldots,k$, \begin{eqnarray*} &\vvarphi_r &= \X\bbeta_r + \zzeta_r \ \Rightarrow \vvarphi_r = \A\xxi_r,\\ & \A & = [\X, \I_{n}]\in \mathbb{R}^{n\times(d+n)}, \ \xxi_r = [\bbeta_r\trans,\zzeta_r\trans]\trans \in \mathbb{R}^{ (d+n)\times m}, \end{eqnarray*} where $\I_{n}\in \mathbb{R}^{n\times n}$ is a identity matrix. Thus it can be seen that the modification only results in new design matrix and regression coefficient matrix, therefore, we can apply Theorem \ref{th:th_bound} $\sim$ \ref{th:th_bound_GS} to have similar results for the modified models. For lasso-type penalties, denote the set of indices of non-zero entries of $\beta_0$ by $S_{\beta}$, and the set of indices of non-zero entries of $\zeta_0$ by $S_{\zeta}$, where $\zeta = \mbox{vec}(\zzeta_1,\ldots,\zzeta_k)$. Denote by $s = |S_{\beta}| + |S_{\zeta}|$. Then for entry-wise $\ell_1$ penalties in \eqref{eq:pen_lasso} (for $\bbeta$) with $\gamma = 0$ and $\mathcal{R}(\zzeta) = \lambda\|\zeta\|_1$ (for $\zzeta$), we need the following modified restricted eigenvalue condition. \begin{mycon}\label{th:con_REC_outlier} For all $ \beta \in \mathbb{R}^{dmk}$ and all $ \zeta \in \mathbb{R}^{nmk}$ satisfying $\|\beta_{S_{\beta}^c}\|_1 + \|\zeta_{S_{\zeta}^c}\|_1 \leq 6(\|\beta_{S_{\beta}}\|_1+\|\zeta_{S_{\zeta}}\|_1)$, it holds for some constant $\kappa\geq 1$ that, \begin{align*} \|\beta_{S_{\beta}}\|_2^2 + \|\zeta_{S_{\zeta}}\|_2^2 \leq \kappa^2 \|\varphi\|_{Q_n}^2 = \frac{\kappa^2}{n}\sum_{i=1}^n\sum_{j\in\Omega_i}\sum_{r=1}^k (\x_i\bbeta_{jr}+\zeta_{ijr})^2. \end{align*} \end{mycon} \begin{mycor}\label{th:cor_outlier_l1} Consider the \methodname\, model in (\ref{eq:exp_fm}) with $\theta_0\in\tilde{\Theta}$, and consider the penalized estimator (\ref{eq:estimator_outlier}) with the $\ell_1$ penalties in (\ref{eq:pen_lasso}) and $\mathcal{R}(\zzeta) = \lambda\|\zeta\|_1$. \noindent (a) Assume conditions 1-3 and 6 hold. Suppose $\sqrt{mk} \lesssim n/M_n$, and take $\lambda > 2T\lambda_0$ for some constant $T>1$. For some constant $c>0$ and large enough $n$, with probability $ 1 - c\exp\left(-\frac{(\log n)^2\log(d\vee n)}{c}\right) - \frac{1}{n}, $ we have \begin{equation* \bar{\varepsilon}(\hat{\theta}\mid \theta_0) + 2(\lambda-T\lambda_0) (\|\hat{\beta}_{S_{\beta}^c}\|_1 + \|\hat{\zeta}_{S_{\zeta}^c}\|_1) \leq 4(\lambda+T\lambda_0)^2\kappa^2 c_0^2s, \end{equation*} \noindent(b) Assume conditions 1-3 hold (without condition 6), assume \begin{align*} \|\beta_0\|_1 + \|\zeta_0\|_1 &= o(\sqrt{n/((\log n)^{2+2c_1}\log(d\vee n)mk)}),\\ \sqrt{mk} &= o(\sqrt{n/((\log n)^{2+2c_1}\log(d\vee n))}) \end{align*} as $n\rightarrow \infty$. If $\lambda = C\sqrt{(\log n)^{2+2c_1}\log(d\vee n)mk/n}$ for some $C>0$ sufficiently large, and for some constant $c>0$ and large enough $n$, with the following probability $ 1 - c\exp\left(-\frac{ (\log n)^2\log(d\vee n)}{c}\right) - \frac{1}{n}, $ we have $ \bar{\varepsilon}(\hat{\theta}\mid\theta_0) = o_P(1). $ \end{mycor} For group-lasso type penalties, denote \begin{align*} &\mathcal{I}_{\beta} = \{p: \bbeta_{0,\mathcal{G}_{\beta,p}} = \mathbf{0}\}, \ \mathcal{I}_{\beta}^c = \{p: \bbeta_{0,\mathcal{G}_{\beta,p}} \neq \mathbf{0}\},\\ &\mathcal{I}_{\zeta} = \{q: \zzeta_{0,\mathcal{G}_{\zeta,q}} = \mathbf{0}\}, \ \mathcal{I}_{\zeta}^c = \{q: \zzeta_{0,\mathcal{G}_{\zeta,q}} \neq \mathbf{0}\}, \end{align*} where $\bbeta_{0,\mathcal{G}_{\beta,p}}$ and $\zzeta_{0,\mathcal{G}_{\zeta,q}}$ denote the $p$th group of $\bbeta_0$ and the $q$th group of $\zzeta_0$, respectively. Now denote $s = |\mathcal{I}_{\beta}| + |\mathcal{I}_{\zeta}|$ with some abuse of notation. Then for group $\ell_1$ penalties in \eqref{eq:pen_lasso_group_general} (for $\bbeta$) and $\mathcal{R}(\zzeta) = \sum_q^Q\|\zzeta_{\mathcal{G}_{\zeta,q}}\|_F$ (for $\zzeta$), we need the following modified restricted eigenvalue condition. \begin{mycon}\label{th:con_REC_GS_outlier} For all $ \bbeta \in \mathbb{R}^{d\times mk}$ and all $ \zzeta \in \mathbb{R}^{n\times mk}$ satisfying \begin{align*} \sum_{p\in \mathcal{I}_{\beta}^c}\|\bbeta_{\mathcal{G}_{\beta,p}}\|_F + \sum_{q\in \mathcal{I}_{\zeta}^c}\|\zzeta_{\mathcal{G}_{\zeta,q}}\|_F \leq 6\left(\sum_{p\in \mathcal{I}_{\beta}}\|\bbeta_{\mathcal{G}_{\beta,p}}\|_F + \sum_{q\in \mathcal{I}_{\zeta}}\|\zzeta_{\mathcal{G}_{\zeta,q}}\|_F \right), \end{align*} it holds that for some constant $\kappa\geq 1$, \begin{align*} \sum_{p\in \mathcal{I}_{\beta}}\|\bbeta_{\mathcal{G}_{\beta,p}}\|_F^2 + \sum_{q\in \mathcal{I}_{\zeta}}\|\zzeta_{\mathcal{G}_{\zeta,q}}\|_F^2 \leq \kappa^2 \|\varphi\|_{Q_n}^2 =\frac{\kappa^2}{n}\sum_{i=1}^n\sum_{j\in\Omega_i}\sum_{r=1}^k (\x_i\bbeta_{jr}+\zeta_{ijr})^2. \end{align*} \end{mycon} \begin{mycor}\label{th:cor_outlier_l1_group} Consider the \methodname\, model in (\ref{eq:exp_fm}) with $\theta_0\in\tilde{\Theta}$, and consider estimator (\ref{eq:estimator_outlier}) with the group $\ell_1$ penalties in (\ref{eq:pen_lasso_group_general}) and $\mathcal{R}(\zzeta) = \sum_q^Q\|\zzeta_{\mathcal{G}_{\zeta,q}}\|_F$. \noindent (a) Assume conditions 1-3 and 7 hold. Suppose $\sqrt{mk} \lesssim n/M_n$, and take $\lambda > 2T\lambda_0$ for some constant $T>1$. For some constant $c>0$ and large enough $n$, with probability $ 1 - c\exp\left(-\frac{(\log n)^2\log(d\vee n)}{c}\right) - \frac{1}{n}, $ we have \begin{align*} \bar{\varepsilon}(\hat{\theta}\mid\theta_0) + 2(\lambda-T\lambda_0)\biggl(\sum_{p\in\mathcal{I}_{\beta}^c}\|\hat{\bbeta}_{\mathcal{G}_{\beta,p}}\|_F+\sum_{q\in\mathcal{I}_{\zeta}^c}\|\hat{\zzeta}_{\mathcal{G}_{\zeta,q}}\|_F\biggr) \leq 4(\lambda+T\lambda_0)^2\kappa^2 c_0^2s, \end{align*} \noindent(b) Assume conditions 1-3 hold (without condition 7), assume \begin{align*} \sum_{p=1}^P\|\bbeta_{0,\mathcal{G}_{\beta,p}}\|_F + \sum_{q=1}^Q\|\zzeta_{0,\mathcal{G}_{\zeta,q}}\|_F & = o(\sqrt{n/((\log n)^{2+2c_1}\log(d\vee n)mk)}),\\ \sqrt{mk} &= o(\sqrt{n/((\log n)^{2+2c_1}\log(d\vee n))}) \end{align*} as $n\rightarrow \infty$. If $\lambda = C\sqrt{(\log n)^{2+2c_1}\log(d\vee n)mk/n}$ for some $C>0$ sufficiently large, and for some constant $c>0$ and large enough $n$, with the following probability $ 1 - c\exp\left(-\frac{ (\log n)^2\log(d\vee n)}{c}\right) - \frac{1}{n}, $ we have $ \bar{\varepsilon}(\hat{\theta}\mid\theta_0) = o_P(1). $ \end{mycor} \section{Proof of Lemma \ref{th:lem_subexp_tail}}\label{sec:condition} \begin{proof} For non-negative continuous variable $X$, we have \begin{align* \mathbb{E}[X1\{X>M\}] & = \int_M^{\infty}tf_X(t)dt = \int_M^{\infty}\int_0^tf_X(t)dxdt \nonumber \\ & = \int_0^M\int_M^{\infty}f_X(t)dtdx + \int_M^{\infty}\int_x^{\infty}f_X(t)dtdx \nonumber \\ &= M\mathbb{P}(X>M) + \int_M^{\infty}\mathbb{P}(X>x)dx. \end{align*} Similarly, we have $ \mathbb{E}[X^21\{X>M\}] = M^2\mathbb{P}(X>M) + \int_M^{\infty}2x\mathbb{P}(X>x)dx. $ For $X$ sub-exponential with parameters $(\sigma ,v ,t) $ such that for $M>t $ \begin{align*} \mathbb{P}(X>M)\leq \left\{ \begin{array}{ll} \exp\biggl(-\frac{M^2}{\sigma^2}\biggr), & t \leq M\leq \frac{\sigma^2}{v}\\ \exp\biggl(-\frac{M }{v }\biggr), & M\geq\frac{\sigma^2}{v}, \end{array} \right. \end{align*} we have the following. If $M\leq \frac{\sigma^2}{v} $, we have \begin{align*} \mathbb{E}[X1\{X>M\}] &= M\mathbb{P}(X>M) + \int_M^{\infty}\mathbb{P}(X>x)dx\\ & \leq M\exp\biggl(-\frac{M^2}{\sigma^2}\biggr) + \int_M^{\frac{\sigma^2}{v}}\exp\biggl(-\frac{x^2}{\sigma^2}\biggr)dx + \int_{\frac{\sigma^2}{v}}^{\infty}\exp\biggl(-\frac{x }{v }\biggr)dx\\ & \leq M\exp\biggl(-\frac{M^2}{\sigma^2}\biggr) + (\frac{\sigma^2}{v} - M)\exp\biggl(-\frac{M^2}{\sigma^2}\biggr) + v\exp\biggl(-\frac{M}{v}\biggr)\\ & = M \exp\biggl(-\frac{M^2}{\sigma^2}\biggr) + v\exp\biggl(-\frac{M}{v}\biggr)\leq (M+v) \exp\biggl(-\frac{M^2}{\sigma^2}\biggr), \end{align*} and similarly, $\mathbb{E}[X^21\{X>M\}] \leq \biggl(M^2+ 2v^2+2\sigma^2\biggr)\exp\biggl(-\frac{M^2}{\sigma^2}\biggr).$ If $M> \frac{\sigma^2}{v} $, we have $\mathbb{E}[X1\{X>M\}] \leq (M+v)\exp\biggl(-\frac{M }{v }\biggr)$ and $\mathbb{E}[X^21\{X>M\}] \leq (M^2+2v^2+2vM)\exp\biggl(-\frac{M }{v }\biggr)$. Then for some constants $c_1,c_2,c_3,c_4,c_5>0$, for non-negative continuous variable $X$ which is sub-exponential with parameters $(\sigma,v,t)$, for $M>c_4>t$ and $c' = 2+\frac{3}{c_1}$, we have \begin{align*} &\mathbb{E}[X1\{X>M\}] \leq \biggl[ c_3\biggl(\frac{M}{c_2}\biggr)^{c'}+ c_5 \biggr]\exp\biggl\{-\biggl(\frac{M}{c_2}\biggr)^{1/c_1}\biggr\},\\ &\mathbb{E}[X^21\{X>M\}] \leq \biggl[ c_3\biggl(\frac{M}{c_2}\biggr)^{c'}+ c_5 \biggr]^2\exp\biggl\{-2\biggl(\frac{M}{c_2}\biggr)^{1/c_1}\biggr\}. \end{align*} If $t \leq M\leq \frac{\sigma^2}{v}$, $c_1 =1/2, c_2 = \sqrt{2}\sigma, c_3 = 16\sigma^8$. And if $M\geq\frac{\sigma^2}{v}$, $c_1 = 1,c_2 = 2v,c_3 = 32v^5$. And $c_5 = \sqrt{2}(v + \sigma)$. For non-negative discrete variables, the result is the same. The result of Lemma \ref{th:lem_subexp_tail} follows from the result above, $\oby_i$ has a finite mixture distribution for $i=1,\ldots,n$ and the following. When dispersion parameter $\phi$ is known, for a constant $c_K$ depending on $K$, we have \begin{equation* G_1(\oby_i) = e^K \max_{j\in\Omega_i}|y_{ij}| + c_K, \ i=1,\ldots,n. \end{equation*} \end{proof} \section{Proof of Lemma \ref{th:px}}\label{sec:proof_px} \begin{proof} Under Condition \ref{th:con_tail}, $M_n = c_2(\log n)^{c_1}$, and $\lambda_0$ defined in (\ref{eq:lambda_0}), for a constant $c_6$ depending on $K$, for $i=1,\ldots,n$, we have \begin{align*} &\mathbb{E}[|G_1(\oby_i)|1\{|G_1(\oby_i)|>M_n\}] \leq c_6\lambda_0^2/(mk), \\ &\mathbb{E}[|G_1(\oby_i)|^21\{|G_1(\oby_i)|>M_n\}] \leq c_6^2\lambda_0^4/(mk)^2. \end{align*} The we can get \begin{align*} &\mathbb{P}_{\X}\biggl(\frac{1}{n}\sum_{i=1}^nG_1(\oby_i)1\{G_1(\oby_i)>M_n\} + \mathbb{E}[G_1(\oby_i)1\{G_1(\oby_i)>M_n\}]>3c_6\lambda_0^2/(mk) \biggr)\\ &\leq \mathbb{P}_{\X}\biggl(\frac{1}{n}\sum_{i=1}^nG_1(\oby_i)1\{G_1(\oby_i)>M_n\} - \mathbb{E}[G_1(\oby_i)1\{G_1(\oby_i)>M_n\}]>c_6\lambda_0^2/(mk) \biggr)\\ &\leq \frac{\mathbb{E}[|G_1(\oby_i)|^21\{|G_1(\oby_i)|>M_n\}]}{n}\frac{m^2k^2}{c_6^2\lambda_0^4} \leq \frac{1}{n}. \end{align*} \end{proof} \section{Proof of Lemma \ref{th:pT}}\label{sec:proof_pT} \begin{proof} We follow \citet{stadler2010} to give a Entropy Lemma and then prove Lemma \ref{th:pT}. We use the following norm $\|\cdot\|_{P_n}$ introduced in the Proof of Lemma 2 in \citet{stadler2010} and use $H(\cdot,\mathcal{H},\|\cdot\|_{P_n})$ as the entropy of covering number (see \citet{van2000applications}) which is equipped the metric induced by the norm for a collection $\mathcal{H}$ of functions on $\mathcal{X}\times \mathcal{Y}$, \begin{align*} \|h(\cdot,\cdot)\|_{P_n} = \sqrt{\frac{1}{n}\sum_{i=1}^nh^2(\x_i,\oby_i)}. \end{align*} Define $ \tilde{\Theta}(\epsilon) = \{\theta\in \tilde{\Theta}: \|\bbeta-\bbeta_0\|_1 + \|\eta - \eta_0\|_2 \leq \epsilon \}$. \begin{mylem} (Entropy Lemma) For a constant $c_{12}>0$, for all $u>0$ and $M_n>0$, we have \begin{align*} H\biggl(u,\biggl\{(\ell_{\theta} - \ell_{\theta^{\star}})1\{G_1\leq M_n\}: \theta\in\tilde{\Theta}(\epsilon)\biggr\}, \|\cdot\|_{P_n}\biggr) \leq c_{12}\frac{mk\epsilon^2M_n^2}{u^2}\log\biggl(\frac{\sqrt{mk}\epsilon M_n}{u}\biggr). \end{align*} \end{mylem} \begin{proof} (For Entropy Lemma) The difference between this proof and that of Entropy Lemma in the proof of Lemma 2 of \citet{stadler2010} is in the notations and the effect of multivariate responses. For multivariate responses we have for $i=1,\ldots,n$, \begin{align*} |\ell_{\theta}(\x_i,\oby_i) - \ell_{\theta'} (\x_i,\oby_i)|^2 &\leq G_1^2(\oby_i)\|\psi_i - \psi'_i \|_1^2 \leq d_{\psi}G_1^2(\oby_i)\|\psi_i- \psi'_i\|_2^2\\ & = d_{\psi}G_1^2(\oby_i) \biggl[\sum_{r=1}^k\sum_{j\in\Omega_i}|\x_i(\bbeta_{rj}- \bbeta'_{rj}) |^2 +\|\eta - \eta'\|_2^2\biggr], \end{align*} where $d_{\psi} = (2m+1)k$ is the maximum of dimension of $\psi_i$ for $i=1,\ldots,n$. Under the definition of the norm $\|\cdot\|_{P_n}$ we have \begin{align*} \|(\ell_{\theta} - \ell_{\theta'})1\{G_1\leq M_n\}\|_{P_n}^2 \leq d_{\psi}M_n^2\left[ \frac{1}{n}\sum_{i=1}^n\sum_{r=1}^k\sum_{j\in\Omega_i}|\x_i(\bbeta_{rj}- \bbeta'_{rj}) |^2 + \|\eta - \eta'\|_2^2 \right]. \end{align*} Then by the result of \citet{stadler2010} we have \begin{align*} H (u,\{\eta\in\mathbb{R}^{d_{\eta}}: \|\eta-\eta_0\|_2\leq \epsilon\},\|\cdot\|_2 )\leq d_{\eta}\log\biggl(\frac{5\epsilon}{u}\biggr), \end{align*} where $d_{\eta} = (m+1)k$ is the dimension of $\eta$. And we follow \citet{stadler2010} to apply Lemma 2.6.11 of \citet{van1996weak} to give a bound as \begin{align*} & H \biggl(2u,\biggl\{ \sum_{r=1}^k\sum_{j\in\Omega_i}\x_i(\bbeta_{rj}- {\bbeta}_{0,rj}) : \|\bbeta-\bbeta_0\|_1\leq\epsilon \biggr\}, \|\cdot\|_{P_n}\biggr) \leq \biggl(\frac{\epsilon^2}{u^2}+1\biggr)\log(1+kmd). \end{align*} Thus we can get \begin{align*} &H \biggl(3\sqrt{d_{\psi}}M_nu,\biggl\{ (\ell_{\theta} - \ell_{\theta_0})1\{G_1\leq M_n\} : \theta\in\tilde{\Theta}(\epsilon) \biggr\}, \|\cdot\|_{P_n}\biggr) \\ &\leq \biggl(\frac{\epsilon^2}{u^2}+1+d_{\eta}\biggr)\biggl(\log(1+kmd)+\log\biggl(\frac{5\epsilon}{u}\biggr)\biggr). \end{align*} \end{proof} Now we turn to prove Lemma \ref{th:pT}. We follow \citet{stadler2010} to use the truncated version of the empirical process below. \begin{align*} V_n^{trunc}(\theta) = \frac{1}{n}\sum_{i=1}^n\biggl( \ell_{\theta}(\x_i,\oby_i)1\{G_1(\oby_i)\leq M_n\} - \mathbb{E}[\ell_{\theta}(\x_i,\oby_i)1\{G_1(\oby_i)\leq M_n\}\mid X=\x_i]. \biggr) \end{align*} We follow \citet{stadler2010} to apply the Lemma 3.2 in \citet{van2000applications} and a conditional version of Lemma 3.3 in \citet{van2000applications} to the class \begin{align*} \biggl\{ (\ell_{\theta} - \ell_{\theta_0})1\{G_1\leq M_n\} : \theta\in\tilde{\Theta}(\epsilon) \biggr\}, \forall \epsilon>0. \end{align*} For some constants $\{c_{t}\}_{t>12}$ depending on $K$ and $\Lambda_{\max}$ in Condition 2 of \citet{stadler2010}, using the notation of Lemma 3.2 in \citet{van2000applications}, we follow \citet{stadler2010} to choose $\delta = c_{13} T\epsilon \lambda_0$ and $R = c_{14}(\sqrt{mk}\epsilon \wedge 1)M_n$. Thus we by choosing $M_n = c_2(\log n)^{c_1}$ we can satisfy the condition of Lemma 3.2 of \citet{van2000applications} to have \begin{align*} & \int_{\epsilon/c_{15}}^R H^{1/2} \biggl(u,\biggl\{(\ell_{\theta} - \ell_{\theta^{\star}})1\{G_1\leq M_n\}: \theta\in\tilde{\Theta}(\epsilon)\biggr\}, \|\cdot\|_{P_n}\biggr) du \vee R \\ =&\int_{\epsilon/c_{15}}^{c_{14}\sqrt{mk}(\epsilon \wedge 1)M_n} c_{12}\biggl(\frac{\sqrt{mk}\epsilon M_n}{u}\biggr)\log^{1/2}\biggl(\frac{\sqrt{mk}\epsilon M_n}{u}\biggr)du \vee (c_{14}(\epsilon \wedge 1)M_n)\\ \leq& \frac{2}{3}c_{12}\sqrt{mk}\epsilon M_n [ \log^{3/2} (c_{15}\sqrt{mk}M_n) - \log^{3/2} (\frac{\sqrt{mk}\epsilon M_n}{c_{14}\sqrt{mk}(\epsilon \wedge 1)M_n}) ]\vee (c_{14}\sqrt{mk}(\epsilon \wedge 1)M_n) \\ \leq& \frac{2}{3}c_{12}\sqrt{mk}\epsilon M_n\log^{3/2} (c_{15}\sqrt{mk}M_n)\\ \leq& c_{16} \sqrt{mk}\epsilon M_n\log^{3/2} (n) \quad (\mbox{by choosing} \ M_n = c_2(\log n)^{c_1}, \mbox{and} \ \sqrt{mk} \leq c_{17}\frac{n}{M_n}) \\ \leq& c_{18} \sqrt{n} T\epsilon \lambda_0\leq \sqrt{n}(\delta - \epsilon). \end{align*} Now for the rest we can apply Lemma 3.2 of \citet{van2000applications} to give the same result with Lemma 2 of \citet{stadler2010}. So we have \begin{align*} \sup_{\theta \in \tilde{\Theta}} \frac{|V_n^{trunc}(\theta) - V_n^{trunc}(\theta_0)|}{(\|\bbeta-\bbeta_0\|_1 + \|\eta-\eta_0\|_2 )\vee \lambda_0} \leq 2c_{23}T \lambda_0 \end{align*} with probability at least $ 1 - c_{9}\exp\biggl[- \frac{T^2(\log n)^2\log(d\vee n) }{c_{8}^2}\biggr].$ At last, for the case when $G_1(\oby_i)>M_n$, for $i=1,\ldots,n$, we have \begin{align*} | (\ell_{\theta}(\x_i,\oby_i) - \ell_{\theta_0}(\x_i,\oby_i))1\{G_1(\oby_i)> M_n\} |\leq d_{\psi}KG_1(\oby_i)1\{G_1(\oby_i)> M_n\}, \end{align*} and \begin{align*} &\frac{|(V_n^{trunc}(\theta) - V_n^{trunc}(\theta_0)) -(V_n(\theta)-V_n(\theta_0)) |} {(\|\bbeta-\bbeta_0\|_1 + \|\eta-\eta_0\|_2 )\vee \lambda_0}\\ &\leq \frac{d_{\psi}K}{n\lambda_0}\sum_{i=1}^n \biggl( G_1(\oby_i)1\{G_1(\oby_i)>M_n\} + \mathbb{E}[G_1(\oby_i)1\{G_1(\oby_i)>M_n\}\mid X=\x_i] \biggr). \end{align*} Then the probability of the following inequality under our model is given in Lemma \ref{th:px}. \begin{align*} \frac{d_{\psi}K}{n\lambda_0}\sum_{i=1}^n \biggl( G_1(\oby_i)1\{G_1(\oby_i)>M_n\} + \mathbb{E}[G_1(\oby_i)1\{G_1(\oby_i)>M_n\}\mid X=\x_i] \biggr) \leq c_{23}T \lambda_0, \end{align*} where $d_{\psi} = 2(m+1)k$. \end{proof} \section{Proof of Theorem \ref{th:th_bound}} \begin{proof} This proof mostly follows that of Theorem 3 of \citet{stadler2010}. The only difference is in the notations. As such, we omit the details. \end{proof} \section{Proof of Theorem \ref{th:high_dim}}\label{sec:app_proof_high_dim} \begin{proof} This proof also mostly follows that of Theorem 5 of \citet{stadler2010}. The difference is in the notations and the choice of $M_n$. If the event $\mathcal{T}$ happens, with $M_n = c_2(\log n)^{c_1}$ for some constants $0\leq c_1,c_2<\infty$, where $c_2$ depends on $K$, $$\lambda_0 = \sqrt{mk} M_n\log n\sqrt{\log(d\vee n)/n} = c_2\sqrt{mk\log^{2+2c_1}\log(d\vee n)/n},$$ we have \begin{align*} \bar{\varepsilon}(\hat{\psi}\mid \psi_0) + \lambda\|\hat{\beta}\|_1 \leq T\lambda_0[(\|\hat{\beta}-\beta_0\|_1 + \|\eta-\eta_0\|_2 )\vee \lambda_0] + \lambda\|\beta_0\|_1 + \bar{\varepsilon}(\psi_0\mid\psi_0). \end{align*} Under the definition of $\theta \in \tilde{\Theta}$ in (\ref{eq:tTheta}) we have $\|\eta-\eta_0\|_2\leq 2K$. And as $ \bar{\varepsilon}(\psi_0\mid\psi_0) =0$ we have for $n$ sufficiently large. \begin{align*} &\bar{\varepsilon}(\hat{\psi}\mid \psi_0) + \lambda\|\hat{\beta}\|_1 \leq T\lambda_0(\|\hat{\beta}\|_1 +\|\beta_0\|_1 + 2K ) + \lambda\|\beta_0\|_1\\ &\rightarrow \bar{\varepsilon}(\hat{\psi}\mid \psi_0) + (\lambda-T\lambda_0)\|\hat{\beta}\|_1 \leq T\lambda_0 2K + (\lambda+T\lambda_0)\|\beta_0\|_1 \end{align*} As $C>0$ sufficiently large we have $\lambda\geq 2T\lambda_0$. And using the condition on $\|\beta_0\|_1$ and $\sqrt{mk}$, we have both $T\lambda_02K = o(1)$ and $(\lambda+T\lambda_0)\|\beta_0\|_1 = o(1)$, so we have $\bar{\varepsilon}(\hat{\psi}\mid \psi_0)\rightarrow 0 \ (n\rightarrow \infty)$. At last, as the event $\mathcal{T}$ has large probability, we have $ \bar{\varepsilon}(\hat{\theta}_{\lambda}\mid\theta_0) = o_P(1) \ (n\rightarrow \infty). $ \end{proof} \section{Proof of Theorem \ref{th:th_bound_GS} } \begin{proof} First we discuss the bound for the probability of $\mathcal{T}_{group}$ in \eqref{eq:event_T_GS}. The difference between $\mathcal{T}_{group}$ and $\mathcal{T}$ in (\ref{eq:event_T}) is only related to the following entropy of the Entropy Lemma in the proof of Lemma \ref{th:pT}. \begin{align*} H \biggl(2u,\biggl\{ \sum_{r=1}^k\sum_{j\in\Omega_i}\x_i(\bbeta_{rj}- {\bbeta}_{0,rj}) : \sum_p\|\bbeta_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F\leq\epsilon \biggr\}, \|\cdot\|_{P_n}\biggr) , \ \mbox{for} \ i = 1\ldots,n, \end{align*} where $\sum_p\|\bbeta_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F\leq\epsilon$ still maintains a convex hull for $\bbeta$ in the metric space equipped with the metric induced by the norm $\|\cdot\|_{P_n}$ defined in the proof of Lemma \ref{th:pT}. Thus it still satisfies the condition of Lemma 2.6.11 of \citet{van1996weak} which can still be applied to give \begin{align*} & H \biggl(2u,\biggl\{ \sum_{r=1}^k\sum_{j\in\Omega_i}\x_i(\bbeta_{rj}- {\bbeta}_{0,rj}) : \sum_p\|\bbeta_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F\leq\epsilon \biggr\}, \|\cdot\|_{P_n}\biggr) \\ & \leq \biggl(\frac{\epsilon^2}{u^2}+1\biggr)\log(1+kmd), \ \mbox{for} \ i = 1\ldots,n. \end{align*} So the probability of event $\mathcal{T}_{group}$ remains the same form with that in Lemma \ref{th:pT}. Then we discuss the bound for the average excess risk and feature selection. If the event $\mathcal{T}_{group}$ happens, we have \begin{align*} \bar{\varepsilon}(\hat{\psi}\mid \psi_0) + \lambda\sum_p\|\hat{\bbeta}_{\mathcal{G}_p}\|_F &\leq T\lambda_0\biggl[\biggl(\sum_{\mathcal{G}_p}\|\hat{\bbeta}_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F + \|\eta-\eta_0\|_2 \biggr)\vee \lambda_0\biggr]\\ &+ \lambda\sum_p\| \bbeta_{0,\mathcal{G}_p}\|_F + \bar{\varepsilon}(\psi_0\mid\psi_0). \end{align*} Using Condition \ref{th:con_fisher} we have $ \bar{\varepsilon}(\psi_0\mid\psi_0) =0$ and $ \bar{\varepsilon}(\hat{\psi}\mid \psi_0) \geq {\|\hat{\psi}-\psi_0\|_{Q_n}^2}/{c_0^2}. $ \noindent\textbf{Case 1} When the following is true: \begin{align*} \sum_p\|\hat{\bbeta}_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F + \|\hat{\eta}-\eta_0\|_2 \leq \lambda_0, \end{align*} we have \begin{align*} \bar{\varepsilon}(\hat{\psi}\mid \psi_0) &\leq T\lambda_0^2 + \lambda\sum_p\|\hat{\bbeta}_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F + \bar{\varepsilon}(\psi_0\mid\psi_0) \leq (\lambda+T\lambda_0)\lambda_0. \end{align*} \textbf{Case 2} When the following is true: \begin{align*} &\sum_p\|\hat{\bbeta}_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F + \|\hat{\eta}-\eta_0\|_2 \geq \lambda_0,\\ & T\lambda_0\|\hat{\eta}-\eta_0\|_2 \geq (\lambda+T\lambda_0)\sum_{p\in\mathcal{I}}\|\hat{\bbeta}_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F. \end{align*} As $\sum_{p\in\mathcal{I}^c}\|\bbeta_{0,\mathcal{G}_p}\|_F=0$, we have \begin{align*} &\bar{\varepsilon}(\hat{\psi}\mid \psi_0) + (\lambda-T\lambda_0)\sum_{p\in\mathcal{I}^c}\|\hat{\bbeta}_{\mathcal{G}_p}\|_F \leq 2T\lambda_0\|\hat{\eta}-\eta_0\|_2\\ &\leq 2T^2\lambda_0^2c_0^2 + \|\hat{\eta}-\eta_0\|_2^2/(2c_0^2) \leq 2T^2\lambda_0^2c_0^2 + \bar{\varepsilon}(\hat{\psi}\mid \psi_0)/2. \end{align*} Then we get \begin{align*} \bar{\varepsilon}(\hat{\psi}\mid \psi_0) + 2(\lambda-T\lambda_0)\sum_{p\in\mathcal{I}^c}\|\hat{\bbeta}_{\mathcal{G}_p}\|_F\leq 4T^2\lambda_0^2c_0^2. \end{align*} \textbf{Case 3} When the following is true: \begin{align*} &\sum_p\|\hat{\bbeta}_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F + \|\hat{\eta}-\eta_0\|_2 \geq \lambda_0,\\ &T\lambda_0\|\hat{\eta}-\eta_0\|_2 \leq (\lambda+T\lambda_0)\sum_{p\in\mathcal{I}}\|\hat{\bbeta}_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F, \end{align*} we have \begin{align*} &\bar{\varepsilon}(\hat{\psi}\mid \psi_0) + (\lambda-T\lambda_0)\sum_{p\in\mathcal{I}^c}\|\hat{\bbeta}_{\mathcal{G}_p}\|_F \leq 2(\lambda+T\lambda_0)\sum_{p\in\mathcal{I}}\|\hat{\bbeta}_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F. \end{align*} Thus we have \begin{align*} \sum_{p\in\mathcal{I}^c}\|\hat{\bbeta}_{\mathcal{G}_p}\|_F \leq 6 \sum_{p\in\mathcal{I}}\|\hat{\bbeta}_{\mathcal{G}_p}-\bbeta_{0,\mathcal{G}_p}\|_F, \end{align*} so we can use the Condition \ref{th:con_REC_GS} for $\hat{\bbeta} -\bbeta_0$ to have \begin{align*} &\bar{\varepsilon}(\hat{\psi}\mid \psi_0) + (\lambda-T\lambda_0)\sum_{p\in\mathcal{I}^c}\|\hat{\bbeta}_{\mathcal{G}_p}\|_F \leq 2(\lambda+T\lambda_0)\sqrt{s}\sum_{p\in\mathcal{I}}\|\hat{\bbeta}_{\mathcal{G}_p}-\hat{\bbeta}_{0,\mathcal{G}_p}\|_F\\ &\leq 2(\lambda+T\lambda_0)\sqrt{s}\kappa\|\hat{\varphi}-(\varphi_0)\|_{Q_n} \leq 2(\lambda+T\lambda_0)^2 s \kappa^2 c_0^2 + \|\hat{\varphi}-(\varphi_0)\|_{Q_n}^2/(2c_0^2)\\ &\leq 2(\lambda+T\lambda_0)^2 s \kappa^2 c_0^2 +\bar{\varepsilon}(\hat{\psi}\mid \psi_0)/2. \end{align*} So we have \begin{align*} \bar{\varepsilon}(\hat{\psi}\mid \psi_0) + 2(\lambda-T\lambda_0)\sum_{p\in\mathcal{I}^c}\|\hat{\bbeta}_{\mathcal{G}_p}\|_F\leq 4(\lambda+T\lambda_0)^2s \kappa^2 c_0^2. \end{align*} And without restricted eigenvalue condition \ref{th:con_REC_GS}, we can prove similarly as in Appendix~\ref{sec:app_proof_high_dim}, assuming event $\mathcal{T}_{group}$ happens and using the condition on $\sum_p\|\bbeta_{0,\mathcal{G}_p}\|_F$ and $\sqrt{mk}$. \end{proof} \newpage \vskip 0.2in \bibliographystyle{spbasic}
{'timestamp': '2020-10-13T02:27:54', 'yymm': '2010', 'arxiv_id': '2010.05430', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05430'}
arxiv
\section{Introduction} In any piece of news, there is a chance that the viewpoint of its authors and of the media organization they work for, would be reflected in the way the story is being told. The emergence of the Web and of social media has lead to the proliferation of information sources, whose leading political ideology or bias may not be explicit. Yet, systematic exposure to such bias may foster intolerance as well as ideological segregation, and ultimately it could affect voting behavior, depending on the degree and the direction of the media bias, and on the voters' reliance on such media~\cite{dellavigna2007fox,iyengar2009red,10.1145/2505515.2505623,graber2017mass}. Thus, making the general public aware, e.g.,~by tracking and exposing bias in the news is important for a healthy public debate given the important role media play in a democratic society. Media bias can come in many different forms, e.g.,~by omission, by over-reporting on a topic, by cherry-picking the facts, or by using propaganda techniques such as appealing to emotions, prejudices, fears, etc. \cite{EMNLP2019:propaganda:finegrained,DaSanMartinoSemeval20task11,IJCAI2020:propaganda:survey} Bias can occur with respect to a specific topic, e.g.,~COVID-19, immigration, climate change, gun control, etc. \cite{ICWSM2020:Unsupervised:Stance:Twitter,stefanov-etal-2020-predicting} It could also be more systematic, as part of a political ideology, which in the Western political system is typically defined as left vs. center vs. right political leaning. Predicting the bias of individual news articles can be useful in a number of scenarios. For news media, it could be an important element of internal quality assurance as well as of internal or external monitoring for regulatory compliance. For news aggregator applications, such as Google News, it could enable balanced search, similarly to what is found on AllSides.\footnote{\url{http://allsides.com/}} For journalists, it could enable news exploration from a left/center/right angle. It could also be an important building block in a system that detects bias at the level of entire news media~\cite{baly2018predicting,baly2019multi,baly2020written}, such as the need to offer explainability, i.e.,~if a website is classified as left-leaning, the system should be able to pinpoint specific articles that support this decision. In this paper, we focus on predicting the bias of news articles as left-, center-, or right-leaning. Previous work has focused on doing so at the level of news media~\cite{baly2020written} or social media users \cite{ICWSM2020:Unsupervised:Stance:Twitter}, but rarely at the article level~\cite{kulkarni2018multi}. The scarce article-level research has typically used distant supervision, assuming that all articles from a given medium should share its overall bias, which is not always the case. Here, we revisit this assumption. Our contributions can be summarized as follows: \begin{itemize} \item We create a new dataset for predicting the political ideology of news articles. The dataset is annotated at the article level and covers a wide variety of topics, providing balanced left/center/right perspectives for each topic. \item We develop a framework that discourages the learning algorithm from modeling the source instead of focusing on detecting bias in the article. We validate this framework in an experimental setup where the test articles come from media that were not seen at training time. We show that adversarial media adaptation is quite helpful in that respect, and we further propose to use a triplet loss, which shows sizable improvements over state-of-the-art pre-trained Transformers. \item We further incorporate media-level representation to provide background information about the source, and we show that this information is quite helpful for improving the article-level prediction even further. \end{itemize} The rest of this paper is organized as follows: We discuss related work in Section~\ref{sec:related_work}. Then, we introduce our dataset in Section~\ref{sec:dataset}, we describe our models for predicting the political ideology of a news article in Section~\ref{sec:methodology}, and we present our experiments and we discuss the results in Section~\ref{sec:results}. Finally, we conclude with possible directions for future work in Section~\ref{sec:conclusion}. \section{Related Work} \label{sec:related_work} Most existing datasets for predicting the political ideology at the news article level were created by crawling the RSS feeds of news websites with known political bias~\cite{kulkarni2018multi}, and then projecting the bias label from a website to all articles crawled from it, which is a form of distant supervision. The crawling could be also done using text search APIs rather than RSS feeds~\cite{horne2019different,gruppi2020nelagt2019}. The media-level annotation of political leaning is typically obtained from specialized online platforms, such as News Guard,\footnote{\url{http://www.newsguardtech.com}} AllSides,\footnote{\url{http://allsides.com/}} and Media Bias/Fact Check,\footnote{\url{http://mediabiasfactcheck.com}} where highly qualified journalists use carefully designed guidelines to make the judgments. As manual annotation at the article level is very time-consuming, requires domain expertise, and it could be also subjective, such annotations are rarely available at the article level. As a result, automating systems for political bias detection have opted for using distant supervision as an easy way to obtain large datasets, which are needed to train contemporary deep learning models. Distant supervision is a popular technique for annotating datasets for related text classification tasks, such as detecting hyper-partisanship~\cite{Horne:2018:ANL:3184558.3186987,DBLP:journals/corr/PotthastKRBS17} and propaganda/satire/hoaxes~\cite{Rashkin}. For example, \citet{kiesel-etal-2019-semeval} created a large corpus for detecting hyper-partisanship (i.e.,~articles with extreme left/right bias) consisting of 754,000 articles, annotated via distant supervision, and additional 1,273 manually annotated articles, part of which was used as a test set for the SemEval-2019 task~4 on Hyper-partisan News Detection. The winning system was an ensemble of character-level CNNs~\cite{jiang2019team}. Interestingly, all top-performing systems in the task achieved their best results when training on the manually annotated articles only and ignoring the articles that were labeled using distant supervision, which illustrates the dangers of relying on distant supervision. \citet{BARRONCEDENO20191849} extensively discussed the limitations of distant supervision in a text classification task about article-level propaganda detection, in a setup that is similar to what we deal with in this paper: the learning systems may learn to model the source of the article instead of solving the task they are actually trained for. Indeed, they have shown that the error rate may drastically increase if such systems are tested on articles from sources that were never seen during training, and that this effect is positively correlated with the representation power of the learning model. They analyzed a number of representations and machine learning models, showing which ones tend to overfit more, but, unlike our work here, they fell short of recommending a practical solution. \citet{budak2016fair} measured the bias at the article level using crowd-sourcing. This is risky as public awareness of media bias is limited~\cite{elejalde2018nature}. Moreover, the annotation setup does not scale. Finally, their dataset is not freely available, and their approach of randomly crawling articles does not ensure that topics and events are covered from different political perspectives. \citet{lin-etal-2006-side} built a dataset annotated with the ideology of 594 articles related to the Israeli-Palestinian conflict published on \url{bitterlemons.org}. The articles were written by two editors and 200 guests, which minimizes the risk of modeling the author style. However, the dataset is too small to train modern deep learning approaches. \citet{kulkarni2018multi} built a dataset using distant supervision and labels from AllSides. Distant supervision is fine for the purpose of training, but they also used it for testing, which can be problematic. Moreover, their training and test sets contain articles from the same media, and thus models could easily learn to predict the article's source rather than its bias. In their models, they used both the text and the URL contents of the articles. Overall, political bias has been studied at the level of news outlet~\cite{DBLP:conf/interspeech/Dinkov0KN19,baly2018predicting,baly2020written,zhang-etal-2019-tanbih}, user~\cite{ICWSM2020:Unsupervised:Stance:Twitter}, article~\cite{DBLP:journals/corr/PotthastKRBS17,saleh2019team}, and sentence~\cite{sim-etal-2013-measuring,10.1145/2505515.2505623}. In particular, \citet{baly2018predicting} developed a system to predict the political bias and the factuality of news media. In a follow-up work,~\citet{baly2019multi} showed that bias and factuality of reporting should be predicted jointly. A finer-grained analysis is performed in~\cite{Horne:2018:ANL:3184558.3186987}, where a model was trained on 10K sentences from a dataset of reviews~\cite{pang-lee-2004-sentimental}, and used to discriminate objective versus non-objective sentences in news articles. \citet{lin-etal-2006-side} presented a sentence-level classifier, where the labels were projected from the document level. \begin{figure*}[ht] \centering \includegraphics[width=1\textwidth]{balanced_search.png} \caption{AllSides: balanced search on the topic of \textit{reopening after the coronavirus lockdown}.} \label{fig:balanced_search} \end{figure*} \section{Dataset} \label{sec:dataset} In this section, we describe the dataset that we created and that we used in our experiments. While most of the platforms that analyze the political leaning of news media provide in-depth analysis of particular aspects of the media, AllSides stands out as it provides annotations of political ideology for individual articles, which ensures high-quality data for both training and testing, which is in contrast with distant supervision approaches used in most previous research, as we have seen above. In AllSides, these annotations are made as a result of a rigorous process that involves blind bias surveys, editorial reviews, third-party analysis, independent reviews, and community feedback.\footnote{\url{http://www.allsides.com/media-bias/media-bias-rating-methods}} Furthermore, AllSides uses the annotated articles to enable its \textit{Balanced Search}, which shows news coverage on a given topic from media with different political bias. In other words, for each trending event or topic (e.g.,~\textit{impeachment} or \textit{coronavirus pandemic}), the platform pushes news articles from all sides of the political spectrum, as shown in Figure~\ref{fig:balanced_search}. We took advantage of this and downloaded all articles along with their political ideology annotations (\textit{left}, \textit{center}, or \textit{right}), their assigned topic(s), the media in which they were published, their author(s), and their publication date. Thus, our dataset contains articles that were manually selected and annotated, and that are representative of the real political scenery. Note that the \textit{center} class covers articles that are biased towards a centrist political ideology, and not articles that lack political bias (e.g., \emph{sports} and \emph{technology}), which commonly exist in news corpora that were built by scraping RSS feeds. We collected a total of 34,737 articles published by 73 news media and covering 109 topics.\footnote{In some cases, an article could be assigned to multiple topics, e.g.,~it could go simultaneously into \emph{coronavirus}, \emph{public health}, and \emph{healthcare}.} In this dataset, a total of 1,080 individual articles (3.11\%) have a political ideology label that is different from their source's. This suggests that, while the distant supervision assumption generally holds, we would still find many articles that defy it. Table~\ref{tbl:label_stats} shows some statistics about the dataset. \begin{table}[h!] \centering \scalebox{0.95}{ \begin{tabular}{lrr} \toprule \bf Political Ideology & \bf Count & \bf Percentage\\ \midrule Left & 12,003 & 34.6\% \\ Center & 9,743 & 28.1\% \\ Right & 12,991 & 37.3\% \\ \bottomrule \end{tabular}} \caption{Statistics about our dataset.} \label{tbl:label_stats} \end{table} Figure~\ref{fig:topics_biases} illustrates the distribution of the different political bias labels within each of the most frequent topics. We can see that our dataset is able to represent topics or events from different political perspectives. This is yet another advantage, as it enables a more challenging task for machine learning models to detect the linguistic and the semantic nuances of different political ideologies in news articles, as opposed to cases where certain topics might be coincidentally collocated with certain labels, in which case the models would be actually learning to detect the topics instead of predicting the political ideology of the target news article. \vspace{0.5cm} \begin{figure}[h!] \centering \includegraphics[width=0.465\textwidth]{topics_biases.png} \caption{Political ideology for the most frequent topics: \textit{elections}, \textit{immigration}, \textit{coronavirus}, and \textit{politics}.} \label{fig:topics_biases} \end{figure} It is worth noting that since most article labels are aligned with their source labels, it is likely that machine learning classifiers would end up modeling the source instead of the political ideology of the individual articles. For example, a model would be learning the writing style of each medium, and then it would associate it with a particular ideology. Therefore, we pre-processed the articles in a way that eliminates explicit markers such as the name of the authors, or the name of the medium that usually appears as a preamble to the article's content, or in the content itself. Furthermore, in order to ensure that we are actually modeling the political ideology as it is expressed in the language of the news, we created evaluation splits in two different ways: ({\em i})~~randomly, which is what is typically done (for comparison only), and ({\em ii})~~based on media, where all articles by the same medium appear in either the training, the validation, or the testing dataset. The latter form of splitting would help us indicate what a trained classifier has actually learned. For instance, if it modeled the source, then it would not be able to perform well on the test set, since all its articles would belong to sources that were never seen during training. In order to ensure fair one-to-one comparisons between experiments, we created these two different sets of splits, while making sure that they share the same test set, as follows: \begin{itemize} \item \textbf{Media-based Split:} We sampled 1,200 articles from 12 news media (100 per medium) and used them as the \textit{test} set, and we excluded the remaining 5,470 articles from these media. Then, we used the articles from the remaining 61 media to create the \textit{training} and the \textit{validation} sets, where all articles from the same medium would appear in the same set: training, development, or testing. This ensures that the model is fine-tuned and tested on articles whose sources were not seen during training. \item \textbf{Random Split:} Here, the \textit{test} set is the same as in the media-based split. The 5,470 articles that we excluded from the 12 media are now added to the articles from the 61 remaining media. Then, we split this collection of articles (using stratified random sampling) into \textit{training} and \textit{validation} sets. This ensures that the model is fine-tuned and evaluated only on articles whose sources were observed during training. \end{itemize} Table~\ref{tbl:splits_stats} shows statistics about both splits, including the size of each set and the number of media and topics they cover. We release the dataset, along with the evaluation splits, and the code,\footnote{\url{http://github.com/ramybaly/Article-Bias-Prediction}} which can be used to extend the dataset as more news articles are added to AllSides. \begin{table}[h!] \centering \scalebox{0.95}{ \begin{tabular}{llrrr} \toprule & & \bf Train & \bf Valid. & \bf Test \\ \midrule \multirow{3}{*}{\bf Media-based} & \it Count & 22,969 & 5,098 & 1,200 \\ & \it Media & 46 & 15 & 12 \\ & \it Topics & 108 & 105 & 93 \\ \midrule \multirow{3}{*}{\bf Random} & \it Count & 26,828 & 6,709 & 1,200 \\ & \it Media & 73 & 73 & 12 \\ & \it Topics & 108 & 107 & 93 \\ \bottomrule \end{tabular}} \caption{Statistics about our dataset and its two splits: \textit{media-based} and \textit{random}.} \label{tbl:splits_stats} \end{table} \section{Methodology} \label{sec:methodology} \subsection{Classifiers} The task of predicting the political ideology of news articles is typically formulated as a classification problem, where the textual content of the articles is encoded into a vector representation that is used to train a classifier to predict one of $C$ classes (in our case, $C=3$: \textit{left}, \textit{center}, and \textit{right}). In our experiments, we use two deep learning architectures: ({\em i})~~\textit{Long Short-Term Memory networks} (LSTMs), which are Recurrent Neural Networks (RNNs), which use gating mechanisms to selectively pass information across time and to model long-term dependencies~\cite{hochreiter1997long}, and ({\em ii})~~\textit{Bidirectional Encoder Representations from Transformers} (BERT), with a complex architecture yielding high-quality contextualized embeddings, which have been successful in several Natural Language Processing tasks~\cite{devlin2019bert}. \subsection{Removing Media Bias} \label{sec:debias} Ultimately, our goal is to develop a model that can predict the political ideology of a news article. Our dataset, along with some others, has a special property that might stand in the way of achieving this goal. Most articles published by a given source have the same ideological leaning. This might confuse the model and cause it to erroneously associate the output classes with features that characterize entire media outlets (such as detecting specific writing patterns, or stylistic markers in text). Consequently, the model would fail when applied to articles that were published in media that were unseen during training. The experiments in Section~\ref{sec:results} confirm this. Thus, we apply two techniques to \textit{de-bias} the models, i.e.,~to prevent them from learning the style of a specific news medium rather than predicting the political ideology of the target news article. \subsubsection{Adversarial Adaptation (AA)} This model was originally proposed by~\citet{ganin2016domain} for unsupervised domain adaptation in image classification. Their objective was to adapt a model trained on labelled images from a \textit{source} domain to a novel \textit{target} domain, where the images have no labels for the task at hand. This is done by adding an adversarial \textit{domain classifier} with a gradient reversal layer to predict the examples' domains. The \textit{label predictor's} is minimized for the labelled examples (from the source domain), and the adversarial \textit{domain classifier's} loss is maximized for all examples in the dataset. As a result, the encoder can extract representation that is ({\em i})~~discriminative for the main task and also ({\em ii})~~invariant across domains (due to the gradient reversal layer). The overall loss is minimized as follows: \begin{equation} \sum_{\substack{i=1:N \\ d_i=0}} \mathcal{L}_y^i(\theta_f, \theta_y) - \lambda\sum_{i=1:N}\mathcal{L}^i_d(\theta_f, \theta_d),\label{eq:aa_1} \end{equation} \noindent where $N$ is the number of training examples, $\mathcal{L}^i_y(\cdot,\cdot)$ is the label predictor's loss, the condition $d_i=0$ means that only examples from the source domain are used to calculate the label predictor's loss, $\mathcal{L}^i_d(\cdot,\cdot)$ is the domain classifier's loss, $\lambda$ controls the trade-off between both losses, and $\{\theta_f,\theta_y,\theta_d\}$ are the parameters of the encoder, the label predictor, and the domain classifier, respectively. Further details about the formulation of this method is available in~\cite{ganin2016domain}. We adapt this architecture as follows. Instead of a \textit{domain classifier}, we implement a \textit{media classifier}, which, given an article, tries to predict the medium it comes from. As a result, the encoder should extract representation that is discriminative for the main task of predicting political ideology, while being invariant for the different media. This approach was originally proposed as an unsupervised domain adaptation, since labelled examples were available for one domain only, whereas in our case, all articles from different media were labelled for their political ideology. Therefore, we jointly minimize the losses of both the \textit{label predictor} and the \textit{media classifier} over the entire dataset. The new objective function to minimize is as follows: \begin{equation} \sum_{i=1:N} \mathcal{L}_y^i(\theta_f, \theta_y) - \lambda\sum_{i=1:N}\mathcal{L}^i_m(\theta_f, \theta_m),\label{eq:aa_2} \end{equation} \noindent where $\mathcal{L}^i_m(\cdot,\cdot)$ is the loss of the \textit{media classifier}, and $\theta_m$ is its set of parameters. \subsubsection{Triplet Loss Pre-training (TLP)} In this approach, we pre-train the encoder using a triplet loss~\cite{schroff2015facenet}. The model is trained on a set of triplets, each composed of an anchor, a positive, and a negative example. The objective in Eq.~\ref{eq:triplet_loss} ensures that the positive example is always closer to the anchor than the negative example is, where $\boldsymbol{a}$, $\boldsymbol{p}$ and $\boldsymbol{n}$ are the encodings of the anchor, of the positive, and of the negative examples, respectively, and $D(\cdot, \cdot)$ is the Euclidean distance: \begin{equation} \mathcal{L} =\max\left(D\left(\boldsymbol{a},\boldsymbol{p}\right) - D\left(\boldsymbol{a},\boldsymbol{n}\right) + \epsilon, 0\right).\label{eq:triplet_loss} \end{equation} Figure~\ref{fig:adaptationtriplet} shows an example of such a triplet. The positive example shares the same ideology as the anchor's, but they are published by different media. The negative example has a different ideology than the anchor's, but they are published by the same medium. In this way, the encoder will be clustering examples with similar ideologies close to each other, regardless of their source. Once the encoder has been pre-trained, its parameters, along with the softmax classifier's, are fine-tuned on the main task by minimizing the cross-entropy loss when predicting the political ideology of articles. \begin{figure}[h!t] \centering \includegraphics[width=0.475\textwidth]{triplet_loss.png} \caption{An example triplet used for de-biasing.} \label{fig:adaptationtriplet} \end{figure} \subsection{Media-level Representation} \label{sec:media_features} Finally, we explore the benefits of incorporating information describing the target medium, which can serve as a complementary representation for the article. While this seems to be counter-intuitive to what we have been proposing in Subsection~\ref{sec:debias}, we believe that medium-level representation can be valuable when combined with an accurate representation of the article. Intuitively, having an accurate understanding of the natural language in the article, together with a glimpse into the medium it is published in, should provide a more complete picture of its underlying political ideology. \citet{baly2020written} proposed a comprehensive set of representation to characterize news media from different angles: how a medium portrays itself, who is its audience, and what is written about it. Their results indicate that exploring the \textit{Twitter bios} of a medium's followers offers a good insight into its political leaning. To a lesser extent, the content of a \textit{Wikipedia} page describing a medium can also help unravel its political leaning. Therefore, we concatenated these representations to the encoded articles, at the output of the encoder and right before the \textsc{softmax} layer, so that both the article encoder and the classification layer that is based on the article and the external media representations are trained jointly and end-to-end. Similarly to~\cite{baly2020written}, we retrieved the profiles of up to a 1,000 Twitter followers for each medium, we encoded their bios using the Sentence-BERT model~\cite{reimers2019sentence}, and we then averaged these encodings to obtain a single representation for that medium. As for the Wikipedia representation, we automatically retrieved the content of the page describing each medium, whenever applicable. Then, we used the pre-trained base BERT model to encode this content by averaging the word representations extracted from BERT's second-to-last layer, which is common practice, since the last layer may be biased towards the pre-training objectives of BERT. \section{Experiments and Results} \label{sec:results} We evaluated both the LSTM and the BERT models, assessing the impact of ({\em i})~~de-biasing and ({\em ii})~~incorporating media-level representation. \subsection{Experimental Setup} We fine-tuned the hyper-parameters of both models on the validation set using a guided grid search trial while fixing the seeds of the random weights initialization. For LSTM, we varied the length of the input (128--1,024 tokens), the number of layers (1--3), the size of the LSTM cell (200--400), the dropout rate (0--0.8), the learning rate ($1\mathrm{e}{-3}$ to $1\mathrm{e}{-5}$), the gradient clipping value (0--5), and the batch size (8--256). The best results were obtained with a 512-token input, a 2-layer LSTM of size 256, a dropout rate of 0.7, a learning rate of $1\mathrm{e}{-3}$, gradient clipping at 0.5, and a batch size of 32. This model has around 1.1M trainable parameters, and was trained with 300-dimensional GloVe input word embeddings~\cite{pennington2014glove}. For BERT, we varied the length of the input, the learning rate, and the gradient clipping value. The best results were obtained using a 512-token input, a learning rate of $2\mathrm{e}{-5}$, and gradient clipping at 1. This model has 110M trainable parameters. We trained our models on 4 \textit{Titan X Pascal} GPUs, and the runtime for each epoch was 25 seconds for the LSTM-based models and 22 minutes for the BERT-based models. For each experiment, the model was trained only once with fixed seeds used to initialize the models' weights. For the Adversarial Adaptation (AA), we have an additional hyper-parameter $\lambda$ (see Equation~\ref{eq:aa_2}), which we varied from 0 to 1, where 0 means no adaptation at all. The best results were obtained with $\lambda=0.7$, which means that we need to pay significant attention to the adversarial classifier's loss in order to mitigate the media bias. For the Triplet Loss Pre-training (PLT), we sampled 35,017 triplets from the training set, such that the examples in each triplet discuss the same topic in order to ensure that the change in topic has minimal impact on the distance between the examples. To evaluate our models, we use accuracy and macro-$F_1$ score ($F_1$ averaged across all classes), which we also used as an early stopping criterion, since the classes were slightly imbalanced. Moreover, given the ordinal nature of the labels, we report the Mean Absolute Error (MAE), shown in Equation~\eqref{eq:mae}, where $N$ is the number of instances, and $y_i$ and $\hat{y}_i$ are the number of correct and of predicted labels, respectively. \begin{equation} \text{MAE} = \frac{1}{N}\sum_{i=1}^N\left|y_i-\hat{y}_i\right|\label{eq:mae} \end{equation} \subsection{Results} \paragraph{Baseline Results} The results in Table~\ref{tbl:baselines} show the performance for LSTM and for BERT at predicting the political ideology of news articles for both the \textit{media-based} and the \textit{random} splits. We observe sizable differences in performance between the two splits. In particular, both models perform much better when they are trained and evaluated on the \textit{random} split, whereas they both fail on the \textit{media-based} split, where they are tested on articles from media that were not seen during training. This observation confirms our initial concerns that the models would tend to learn general characteristics about news media, and then would face difficulties with articles coming from new unseen media. \begin{table}[h!] \centering \scalebox{0.85}{ \begin{tabular}{llccc} \toprule \bf Model & \bf Split & \bf Macro $\boldsymbol{F_1}$ & \bf Acc. & \bf MAE \\ \midrule \it Majority & & 19.61 & 41.67 & 0.92 \\ \midrule \multirow{2}{*}{\it LSTM} & \it Media-based & 31.51 & 32.30 & 0.97 \\ & \it Random & 65.50 & 66.17 & 0.52 \\ \midrule \multirow{2}{*}{\it BERT} & \it Media-based & 35.53 & 36.75 & 0.90 \\ & \it Random & 80.19 & 79.83 & 0.33 \\ \bottomrule \end{tabular}} \caption{Baseline experiments (without de-biasing or media-level representation) for the two splits.} \label{tbl:baselines} \end{table} \paragraph{Removing the Source Bias} In order to further confirm the bias towards modeling the media, we ran a side experiment of fine-tuning BERT on the task of predicting the medium given the article's content, which is a 73-way classification problem. We used stratified random sampling to create the evaluation splits and to make sure each set contains all labels (media). The results in Table~\ref{tbl:source_prediction} confirm that BERT is much stronger than the majority class baseline, despite the high number of classes, which means that predicting the medium in which a target news article was published is a fairly easy task. \begin{table}[h!] \centering \scalebox{1}{ \begin{tabular}{lrr} \toprule \bf Model & \bf Macro $\boldsymbol{F_1}$ & \bf Acc. \\ \midrule \it Majority & 0.25 & 10.21 \\ \it BERT & 59.72 & 80.12 \\ \bottomrule \end{tabular}} \caption{Predicting the medium in which a target news article was published.} \label{tbl:source_prediction} \end{table} \begin{table}[b] \centering \scalebox{0.95}{ \begin{tabular}{lcccc} \toprule \bf Model & \bf De-bias & \bf Macro $\boldsymbol{F_1}$ & \bf Acc. & \bf MAE \\ \midrule \multirow{3}{*}{\it LSTM} & \it None & 31.51 & 32.30 & 0.97 \\ & \it AA & 40.33 & 40.57 & 0.69 \\ & \it TLP & \bf 45.44 & \bf 46.42 & \bf 0.62 \\ \midrule \multirow{3}{*}{\it BERT} & \it None & 35.53 & 36.75 & 0.90 \\ & \it AA & 43.87 & 46.22 & 0.59 \\ & \it TLP & \bf 48.26 & \bf 51.41 & \bf 0.51 \\ \bottomrule \end{tabular}} \caption{Impact of de-biasing (adversarial adaptation and triplet loss) on article-level bias detection.} \label{tbl:debiasing} \end{table} \begin{table*}[tbh] \centering \scalebox{1}{ \begin{tabular}{clccc@{ }@{ }@{ }@{ }@{ }ccc} \toprule \multicolumn{2}{c}{} & \multicolumn{3}{c}{\bf LSTM} & \multicolumn{3}{c}{\bf BERT} \\ \bf \# & \bf Representation & \bf Macro $\boldsymbol{F_1}$ & \bf Acc. & \bf MAE & \bf Macro $\boldsymbol{F_1}$ & \bf Acc. & \bf MAE \\ \midrule 1 & \it Article (baseline) & 31.51 & 32.30 & 0.97 & 35.53 & 36.75 & 0.90 \\ 2 & \it Article with TLP & 45.44 & 46.42 & 0.62 & 48.26 & 51.41 & 0.51 \\ \cdashlinelr{1-8} 3 & \it Wikipedia & 41.39 & 41.86 & 0.92 & 41.39 & 41.86 & 0.92 \\ 4 & \it Wikipedia $+$ Article & 40.49 & 40.79 & 0.92 & 42.33 & 41.90 & 0.90 \\ 5 & \it Wikipedia $+$ Article with TLP & 48.25 & 46.47 & 0.69 & 51.16 & 49.75 & 0.32 \\ 6 & \it Twitter bios & 60.30 & 62.69 & 0.42 & 60.30 & 62.69 & 0.42 \\ 7 & \it Twitter bios $+$ Article & 60.30 & 62.69 & 0.42 & 60.42 & 63.12 & 0.40 \\ 8 & \it Twitter bios $+$ Article with TLP & \bf 62.02 & \bf 70.03 & \bf 0.32 & \bf 64.29 & \bf 72.00 & \bf 0.29 \\ \bottomrule \end{tabular}} \caption{Impact of adding media-level representations to the article-level representations (with and without de-biasing). Note that the results in rows 3 and 6 are the same for both LSTM and BERT because no articles were involved, and the media-level representations were directly used to train the classifier.} \label{tbl:media_features} \end{table*} In order to remove the bias towards modeling the medium, we evaluated the impact of the adversarial adaptation (AA) and the Triplet Loss Pre-training (TLP) with the media-based split. The results in Table~\ref{tbl:debiasing} show sizeable improvements when either of these approaches is used, compared to the baseline (no de-biasing). In particular, TLP yields an improvement of 14.12 points absolute in terms of accuracy, and 12.73 points in terms of macro-$F_1$. \paragraph{Impact of Media-Level Representation} Finally, we evaluated the impact of incorporating the media-level representation (Twitter followers' bios and Wikipedia content) in addition to teh article-level representation. Table~\ref{tbl:media_features} illustrates these results in an incremental way. First, we evaluated the performance of the media-level representation alone at predicting the political ideology of news articles (see rows 3 and 6). We should note that these results are identical for the LSTM and the BERT columns since no article was encoded in these experiments, and the media representation was used directly to train the logistic regression classifier. Then, adding the article representation from either model, without any de-biasing, had no or little impact on the performance (see rows 4~vs.~3, and 7~vs.~6). This is not surprising, since we have shown that, without de-biasing, both models learn more about the source than about the bias in the language used by the article. Therefore, the ill-encoded articles do not provide more information than what the medium representation already gives, which is why no or too little improvement was observed. When we use the triplet loss to mitigate the source bias, the resulting article representation is more accurate and meaningful, and the medium representation does offer complementary information, and eventually contributes to sizeable performance gains (see rows 5 and 8~vs.~2). The Twitter bios representation appears to be much more important than the representation from Wikipedia, which shows the importance of inspecting the media followers' background and their point of views, which is also one of the observations in~\cite{baly2020written}. Overall, comparing the best results to the baseline (rows 8~vs.~1), we can see that ({\em i})~~using the triplet loss to remove the source bias, and ({\em ii})~~incorporating media-level representation from Twitter followers yields 30.51 and 28.76 absolute improvement in terms of macro $\boldsymbol{F_1}$ on the challenging \textit{media-based} split. \section{Conclusion and Future Work} \label{sec:conclusion} We have explored the task of predicting the leading political ideology of news articles. In particular, we created a new large dataset for this task, which features article-level annotations and is well-balanced across topics and media. We further proposed an adversarial media adaptation approach, as well as a special triplet loss in order to prevent modeling the source instead of the political bias in the news article, which is a common pitfall for approaches dealing with data that exhibit high correlation between the source of a news article and its class, as is the case with our task here. Finally, our experimental results have shown very sizable improvements over using state-of-the-art pre-trained Transformers. In future work, we plan to explore topic-level bias prediction as well as going beyond left-center-right bias. We further want to develop models that would be able to detect specific fragments in an article where the bias occurs, thus enabling explainability. Last but not least, we plan to experiment with other languages, and to explore to what extent a model for one language is transferable to another one given that the left-center-right division is not universal and does not align perfectly across countries and cultures, even when staying within the Western political world. \section*{Acknowledgments} This research is part of the Tanbih project\footnote{\url{http://tanbih.qcri.org/}}, which aims to limit the effect of ``fake news,'' propaganda and media bias by making users aware of what they are reading. The project is developed in collaboration between the Qatar Computing Research Institute, HBKU and the MIT Computer Science and Artificial Intelligence Laboratory.
{'timestamp': '2020-10-13T02:25:30', 'yymm': '2010', 'arxiv_id': '2010.05338', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05338'}
arxiv
\section{Introduction}\label{sec:introduction} Songwriters are increasingly experimenting with machine learning as a way to extend their personal expression~\cite{barbican2020songs}. For example, in the symbolic domain, the band Yacht used MusicVAE~\cite{roberts2018hierarchical}, a variational autoencoder type of neural network, to find melodies hidden in between songs by interpolating between the musical lines in their back catalog, commenting that \emph{``it took risks maybe we aren’t willing to''}~\cite{mattise2019yacht}. In the audio domain, Holly Herndon uses neural networks trained on her own voice to produce a polyphonic choir.~\cite{maas2020holly,denton2019holly}. In large part, these human-AI experiences were enabled by major advances in machine learning and deep generative models~\cite{oord2016wavenet, vaswani2017attention, dieleman2018challenge}, many of which can now generate coherent pieces of long-form music~\cite{huang2019music, hawthorne2018enabling, payne2019muse, dhariwal2020jukebox}. Although substantial research has focused on improving the algorithmic performance of these models, much less is known about what musicians actually need when songwriting with these sophisticated models. Even when composing short, two-bar counterpoints, it can be challenging for novice musicians to partner with a deep generative model: users desire greater agency, control, and sense of authorship vis-a-vis the AI during co-creation~\cite{louie2020novice}. Recently, the dramatic diversification and proliferation of these models have opened up the possibility of leveraging a much wider range of model options, for the potential creation of more complex, multi-domain, and longer-form musical pieces. Beyond using a single model trained on music within a single genre, how might humans co-create with an open-ended set of deep generative models, in a complex task setting such as songwriting? In this paper, we conduct an in-depth study of what people need when partnering with AI to make a song. Aside from the broad appeal and universal nature of songs, songwriting is a particularly compelling lens through which to study human-AI co-creation, because it typically involves creating and interleaving music in multiple mediums, including text (lyrics), music (melody, harmony, etc), and audio. This unique conglomeration of moving parts introduces unique challenges surrounding human-AI co-creation that are worthy of deeper investigation. As a probe to understand and identify human-AI co-creation needs, we conducted a survey during a large-scale human-AI songwriting contest, in which 13 teams (61 participants) with mixed (musician-developer) skill sets were invited to create a 3-minute song, using whatever AI algorithms they preferred. Through an in-depth analysis of survey results, we present findings on what users needed when co-creating a song using \ai, what challenges they faced when songwriting with \ai, and what strategies they leveraged to overcome some of these challenges. We discovered that, rather than using large, end-to-end models, teams almost always resorted to breaking down their musical goals into smaller components, leveraging a wide combination of smaller generative models and re-combining them in complex ways to achieve their creative goals. Although some teams engaged in active co-creation with the model, many leveraged a more extreme, multi-stage approach of first generating a voluminous quantity of musical snippets from models, before painstakingly curating them manually post-hoc. Ultimately, use of AI substantially changed how users iterate during the creative process, imposing a myriad of additional model-centric iteration loops and side tasks that needed to be executed alongside the creative process. Finally, we contribute recommendations for future AI music techniques to better place them in the music co-creativity context. In sum, this paper makes the following contributions: \vspace{-5pt} \begin{itemize} \item{A description of common patterns these teams used when songwriting with a diverse, open-ended set of deep generative models.} \vspace{-4pt} \item{An analysis of the key challenges people faced when attempting to express their songwriting goals through AI, and the strategies they used in an attempt to circumvent these AI limitations.} \vspace{-4pt} \item{Implications and recommendations for how to better design human-AI systems to empower users when songwriting with AI.} \end{itemize} \section{Related work} Recent advances in AI, especially in deep generative models, have renewed interested in how AI can support mixed-initiative creative interfaces~\cite{mici2017deterding} to fuel human-AI co-creation~\cite{geyer2020hai}. \emph{Mixed initiative}~\cite{horvitz1999principles} means designing interfaces where a human and an AI system can each ``take the initiative'' in making decisions. \emph{Co-creative}~\cite{liapis2016mixedinitiative} in this context means humans and AI working in partnership to produce novel content. For example, an AI might add to a user's drawing ~\cite{fan2019collabdraw,oh2018lead}, alternate writing sentences of a story with a human~\cite{clark2018creative}, or auto-complete missing parts of a user's music composition~\cite{bazin2019nonoto,huang2018mixed,huang2019bach,louie2020novice}. Within the music domain, there has been a long history of using AI techniques to model music composition~\cite{papadopoulos1999ai, fernandez2013ai,pasquier2016introduction, herremans2017functional}, by assisting in composing counterpoint~\cite{farbood2001analysis, herremans2013composing}, harmonizing melodies~\cite{pachet2001musical, chuan2007hybrid,koops2013functional}, more general infilling~\cite{hadjeres2016deepbach,huang2017coconet,ippolito2018infilling,shaw2019multitask}, exploring more adventurous chord progressions~\cite{nichols2009data, fukayama2013chord, huang2016chordripple}, semantic controls to music and sound generation~\cite{simon2008mysong,cartwright2013social,huang2014active, ferreira2019learning}, building new instruments through custom mappings or unsupervised learning~\cite{fiebrink2011real, donahue2019piano}, and enabling experimentation in all facets of symbolic and acoustic manipulation of the musical score and sound~\cite{agon2006om, bresson2008om}. More recently, a proliferation of modern deep learning techniques~\cite{briot2017deep, briot2020artificial} has enabled models capable of generating full scores~\cite{huang2020pop}, or producing music that is coherent to both local and distant regions of music~\cite{huang2019music,payne2019muse}. The popular song form has also been an active area of research to tackle modeling challenges such as hierarchical and multi-track generation~\cite{ papadopoulos2016assisted, roberts2017hierarchical, simon2018learning, zhou2018bandnet}. Despite significant progress in deep generative models for music-making, there has been relatively little research examining how humans interact with this new class of algorithms during co-creation. A recent study on this topic~\cite{louie2020novice} found that deep learning model output can feel non-deterministic to end-users, making it difficult for users to steer the AI and express their creative goals. Recent work has also found that users desire to retain a certain level of creative freedom when composing music with AI~\cite{frid2020music,louie2020novice,sturm2019machine}, and that semantically meaningful controls can significantly increase human sense of agency and creative authorship when co-creating with AI~\cite{louie2020novice}. While much of prior work examines human needs in the context of co-creating with a single tool, we expand on this emerging body of literature by investigating how people assemble a broad and open-ended set of real-world models, data sets, and technology when songwriting with AI. \section{Method and Participants} \todo{The research was conducted during the first three months of 2020, at the AI Song Contest organized by \textsc{VPRO}~\cite{dijk2020ai}. The contest was announced at ISMIR in November 2019, with an open call for participation.} Teams were invited to create songs using any artificial intelligence technology of their choice. The songs were required to be under 3 minutes long, with the final output being an audio file of the song. At the end, participants reflected on their experience by completing a survey. Researchers obtained consent from teams to use the survey data in publications. \todo{The survey consisted of questions to probe how teams used AI in their creative process:} \vspace{-4pt} \todo{ \begin{itemize} \item{How did teams decide which aspects of the song to use AI and which to be composed by musicians by hand? What were the trade-offs?} \vspace{-4pt} \item{How did teams develop their AI system? How did teams incorporate their AI system into their workflow and generated material into their song?} \end{itemize} } \vspace{-4pt} In total, 13 teams (61 people) participated in the study. The teams ranged in size from 2 to 15 (median=4). \todo{Nearly three fourths of the teams had 1 to 2 experienced musicians.} \todo{A majority of teams had members with a dual background in music and technology: 5 teams had 3 to 6 members each with this background, and 3 teams had 1 to 2 members.} We conducted an inductive thematic analysis~\cite{braun2006using,braun2014can,adams2008qualititative} on the survey results to identify and better understand patterns and themes found in the teams' survey responses. One researcher reviewed the survey data, identifying important sections of text, and two researchers collaboratively examined relationships between these sections, iteratively converging on a set of themes. \begin{table*}[] \centering \resizebox{2\columnwidth}{!}{% \begin{tabular}{ll} \toprule Music building blocks & Models \& techniques \\ \midrule \noalign{\vskip .5ex} Lyrics & GPT2, LSTM, Transformer \\ \midrule Melody & CharRNN, SampleRNN, LSTM + CNN, WaveNet + LSTM, GAN, Markov model \\ Harmony & LSTM, RNN autoencoder, GAN, Markov model \\ Bassline & LSTM + CNN, WaveNet + LSTM, GAN \\ Drums & DrumRNN, Neural Drum Machine, SampleRNN, Markov model \\ Multi-part & MusicVAE trio (melody, bass, drums), MiniVAE trio, Coconet/Coucou (4-part counterpoint), \\ & MusicAutobot (melody, accompaniment), Transformer (full arrangement) \\ Structure & Markov model \\ \midrule Vocal synthesis & WaveNet, SampleRNN, Vocaloid, Sinsy, Mellotron, Emvoice, Vocaloid, custom vocal assistant \\ Instrument synthesis & SampleRNN, WaveGAN, DDSP \\ \bottomrule \end{tabular}% } \caption{Overview of musical building blocks used by teams.}\label{tab:bblocks} \end{table*} \section{How did teams co-create with \ai?} The vast majority of teams broke down song composition into smaller modules, using multiple smaller models that align with the musical building blocks of a song, before combining their results: \textit{``So my workflow was to build the song, section by section, instrument by instrument, to assemble the generated notes within each section to form a coherent whole''} (T12). A few teams first attempted to use end-to-end models to generate the whole song at once, such as through adversarial learning from a corpus of pop song audio files (T6) or through generating an audio track using SampleRNN~\cite{mehri2016samplernn} (T13). However, they quickly learned that they were unable to control the model or produce professional quality songs, and thus turned to the modular approach instead. \todo{In the following sections, we summarize how teams used modular building blocks, combined and curated them, and in some cases more actively co-created with AI to iterate on the outcomes.} \subsection{\todo{Leveraging modular musical building blocks}} Overall, teams leveraged a wide range of models for musical components such as lyrics, (vocal) melody, harmony, bassline, drums, arrangement, and vocal and instrument synthesis. Table \ref{tab:bblocks} shows an overview of models used for each song component, and Figure \ref{fig:thumbnails} illustrates how the 13 teams co-created with AI along these different components. The number of unique model types used by teams ranged from 1 to 6 (median 4). Some teams used the same type of model for modeling different song components. \begin{figure}[h!] \centerline{ \includegraphics[width=\columnwidth, trim={0.5cm 0.5cm 0.5cm 0.5cm},clip]{figs/ai_song_thumbnail_final.png}} \caption{\todo{An overview of how 13 teams co-created with AI in songwriting. Each column shows whether each song's component was musician composed, AI generated then human curated, or both. Nearly all teams manually aligned AI generated \emph{lyrics} and \emph{melody}, except teams in the first three columns. T5 used a two-stage pipeline by first generating \emph{lyrics} and \emph{melody} separately, then algorithmically matching them up using their stress patterns. T10 first generated \emph{lyrics}, and then conditioned on \emph{lyrics} to generate \emph{melody}. T1 jointly modeled \emph{lyrics} and \emph{melody}, generating syllables and notes in an interleaving fashion. T12, 8, 4, 7 all generated \emph{melodic lines} first, and then manually \textbf{stitched} them together by layering them vertically as \emph{melody} and \emph{bassline} to yield \emph{harmony}. In contrast, T11, 3 first generated \emph{chords}, then conditioned on \emph{chords} to generate \emph{melody} (and \emph{bassline} separately) in a \textbf{pipeline}. T13 iterated between conditioning on \emph{melody} to jointly generate the other parts and vice versa. T2, 6 and 9 focused on models that could \textbf{jointly} generate multiple parts at once.}} \label{fig:thumbnails} \end{figure} All teams used AI to generate lyrics and melodies, and more than half of the teams synthesized vocals for parts of the song. Some of these decisions were due to model availability and existing levels of model performance. For example, teams almost always generated lyrics using AI because \todo{high-performing models like GPT-2~\cite{radford2019language} along with a fine-tuning script were readily available}. Teams with professional musicians often chose to only generate lyrics and melodic lines, in order to \todo{leave enough creative space to musicians to decide how the various lines can be put together and to arrange the song in their own style (T5, 8). One exception is T3 who generated a lead sheet with lyrics, melody and harmony.} Teams with more ML and less music expertise opt for minimal arrangements (T10, 6, 9), and often used multi-part models because they could generate melody, harmony, bass, drums together in a coherent way, providing teams with larger building blocks to work with. In one extreme case, \todo{the team was able to generate all sections of their song by traversing the latent space of MusicVAE (T9) (see ``Bridging sections through latents" below for more detail)}. \subsection{Combining building blocks} Teams leveraged many strategies for combining outputs of smaller models, piecing together the musical building blocks to form a coherent song. These ranged from manually combining individual components, to using heuristics to automatically pair them up, to creating a pipeline between models, to adopting models that jointly model multiple components at once. \header{Stitching} \todo{Many teams manually ``stitched'' together machine generated material, with the result informing the manual composition of other musical components.} \todo{In one team, a musician \textit{``selected, tweaked, and weaved AI-generated melody, chords and drum parts into a ballad song form''}, while another musician wrote the bassline \textit{``that seemed more or less implied by the AI materials''} (T7).} \todo{This is echoed by another team, who composed the accompaniment \textit{``based on chordal movements predicted by the melodic fragments''} (T5).} \todo{Several teams layered melodic lines to yield harmony (T1, 12, 8, 4)}. \header{Pipelines} Several teams leveraged model pipe-lining, feeding the output of one model into the input of another model. \todo{To generate melody that aligns well with lyrics, one team first used GPT-2 to generate lyrics, then a lyric-conditioned model to generate melody~\cite{yu2019conditional} (T10).} One team decomposed melody generation into two steps, first using a LSTM to generate rhythm as note onset patterns, and then a CNN to assign a pitch to each onset (T8). \todo{While many teams ``stitched'' together melodic lines to create harmony, two teams first generated chords and then melody (and bassline) (T11 and T13)}. % Pipeline approaches allowed teams to refine the output at each intermediate stage before passing content into the next model. \header{Joint modeling} To generate multiple parts together, several teams adopted models such as MusicVAE trio~\cite{roberts2017hierarchical}, Coconet~\cite{huang2017coconet}, MusicAutobot~\cite{shaw2019music} or Transformers that are trained to jointly model multiple instrumental parts \todo{(T13, 2, 6, 9)}. One team experimented with jointly modeling notes and syllables from pairs of melodies and lyrics, but found it \textit{``very hard to concurrently generate semantically meaningful lyrics and a melody that is not aimless''} (T1). \subsection{Generate then curate} A common approach was to generate a large quantity of musical samples, followed by automatically or manually curating them post-hoc. Teams took a range of approaches to curating the large quantity of results, ranging from brute-force manual curation, to a two-stage process of first filtering with AI, then curating manually. \header{Generation} Often, teams used models to generate a large volume of samples to choose from. For instance, one team used their pipeline LSTM + CNN model to generate over 450 melodies and basslines (T8). Another team generated 10K lines of death metal lyrics (T13). \header{Manual curation} While curating, teams were often looking for the key musical themes or motifs to use for their song. For example, one team used MusicVAE to generate several combinations of lead, bass, and drums, and \textit{``handpicked the most appealing''} version to serve as their verse (T2). Another team was looking for a small, catchy snippet or \textit{``earworms"} to flesh out the music (T11). \header{Two-stage curation} A few teams first used automated methods to narrow down the choices, before manually selecting what would fit best in their song. For example, one team used a \textit{``catchiness''} classifier trained on rankings of songs to filter melodies before handing them to an artist (T8). Another team curated their generated material by first algorithmically matching up the stress patterns of lyrics and melodies to make sure the material could be more immediately useful (T5). Several teams found the process of generating and curating painstaking, or similar to a difficult puzzle (T1). However, one team described this massive generation process as exhilarating, or like \textit{``raging with the machines"} (T5). They most appreciated the unexpected surprises, and actively engaged with this firehose of raw, AI-generated material: \textit{``We couldn't resist including as much of the good and quirky machine output as possible...makes it much less repetitive than much of the music we might produce as humans. We really enjoyed having this firehose of generative capability...its constantly moving nature"} (T5). \subsection{Active co-creation} Some teams co-created music with AI in a more blended manner, where the model outputs influenced human composing and vice versa, similar to how human musicians might work together to write a song. A few teams used AI-generated output as an underlying foundation for composing on top of, such as improvising a melody over AI-generated chords: \textit{``we played the chords, and all of us around the table hummed along until we got to a simple and catchy melody''} (T11). Others took the AI output as raw material generated in a predefined structure, and manually composed an underlying beat (T8). Others took AI output as an initial seed for inspiration and further elaboration. For example, one team trained SampleRNN on acappellas, which generated nonsensical output similar to babbling. A musician then tried to ``transcribe'' the words and the melody, and sang along with it. \textit{``She found sections that sounded like lyrics. She wrote those lyrics down and sang them. She spent a day riffing on those lyrics, building a dialogue"}. These riffs and words fueled the formation of the larger story and song (T13). For one participant, working with the AI was like jamming with another musician, an active back and forth process of priming the AI with chord progressions, hearing AI output, riffing on that output, then using those new ideas to seed the AI again (T12). One team described making some deliberate decisions about how much agency to provide the AI vs. themselves as artists. To preserve the AI's content, an artist tried to only transpose and not ``mute'' any of the notes in two-bar AI-generated sequences, as he chose which ones to stitch together to align with lyrics. However, to bring the artist's own signature as a rapper, he decided to compose his own beat, and also improvise on top of the given melodies freely with a two-syllable word that was made up by ML\; (T8). \section{Teams overcoming AI limitations} In the previous section, we described the ways in which participants co-created with AI. Although teams made some headway by breaking down the composition process into smaller models and building blocks, we observed a wide range of deeper challenges when they attempted to control the co-creation process using this plethora of models. In this section, we describe participants' creative coping strategies given these challenges, and the strategies they used to better direct the co-creation process. \subsection{ML\; is not directly steerable} Due to the stochastic nature of ML\; models, their output can be unpredictable. During song creation, teams leveraged a wide range of strategies in an attempt to influence model output, such as through data during fine-tuning, or through input or conditioning signals during generation. Below, we describe the most common patterns observed: \header{Fine-tuning} After experimenting with a model, many teams tried to influence the mood or style of the generated content by fine-tuning models on a smaller dataset. For example, teams fine-tuned GPT-2 with lyrics from uplifting pop\; songs to German death metal (T13), in order to steer the generation towards phrase structures more common in lyrics and also sub-phrases that reflect the desired sentiment and style. \header{Priming} While co-creating, teams often desired to create musical content in a particular key, chord, contour, or pitch range. To do so, many attempted to reverse engineer the process by priming the model's input sequence using music containing the desired property, in the hopes that it would produce a continuation with similar characteristics: \textit{``I found that I could control the generation process by using different kinds of input. So if I wanted a sequence that is going upward, I would give that kind of input. If I wanted the model to play certain notes, I would add those notes in the input pattern''} (T12). This seemingly simple way of requesting for continuations led to a wide range of controls when used creatively. To further direct content in lyrics, a team used specific words to start off each sentence (T5). Another team wondered \textit{``can pop\; songs convey insightful messages with only two words?''}, and put together a verse with frequent bigrams from that dataset, such as \textit{``my love''}, \textit{``your heart''}. They entered this verse through the TalkToTransformer~\cite{king2019talk} web-app interface as context for GPT-2 to generate the next verses (T11). \header{Interpolating} Models such as MusicVAE provide a continuous latent space that supports interpolating between existing sequences to generate new sequences that bear features of both~\cite{roberts2018learning}. Some teams leveraged this latent space as a way to explore. For example, one participant found by chance that \textit{``interpolating between really simple sequences at high temperatures would end up giving me these really cool baseline sequences''} (T12). \subsection{ML\; is not structure-aware} Because large, end-to-end models were not easily decomposable into meaningful musical structures, most teams used multiple smaller, independent models. Yet, these smaller, independent ML\; models are not able to take into account the holistic context of the song when generating local snippets. To address this, users created their own workarounds to fill in this contextual gap, by arranging and weaving these independent pieces into a coherent whole. \header{Creating an overall song structure} To create a backbone for the song, some teams used their musical knowledge to first curate chord progressions that can serve well for each song section (i.e. verse, chorus). One team then used a conditioned model (pretrained to be conditioned on chord progressions) to generate melody and basslines that would go well with those chords (T3). \header{Creating contrast between sections} The verse and chorus sections of a song often carry contrast. However, participants did not have a direct way to express this desire for structured contrast while preserving overall coherence between verse and chorus. To address this, one team used their verse as a starting point to generate various continuations to the melody and bass lines, and finally chose a variation for the chorus section (T2). Another team used similar priming approaches but used different temperatures to generate the verse and chorus in order to \textit{``add some randomness into the generation''} (T12). These approaches gave users a way to manually create structured variety \header{Rewriting to add variation} Rewriting allows one to generate new material while borrowing some structure from the original material. For example, one team was able to generate a \textit{``darker version''} of the chorus of another song by rewriting it multiple times, alternating between re-generating the melody conditioned on the accompaniment, and then re-generating the accompaniment conditioned on the melody. To create a coherent song structure, the team initially attempted to \textit{``repeat the same rave section twice"}, but later \textit{``realized that was boring''}. The team then decided to vary how the second section ended by reharmonizing the melody with a new flavor: \textit{``Coconet is great at reharmonizing melodies with a baroque flavor. We entered in the notes from our rave chorus. After a few tries, it made this awesome extended cadence''} (T13). \header{Bridging sections through latents} One team devised an unusual strategy for connecting different sections of a song in a meaningful way (T9). They first trained multiple miniVAEs~\cite{dinculescu2019midime}, one for each section of the song (e.g. intro, verse, chorus or genre such as rock and pop). They then composed the song by computing the \emph{``shortest path''} through these latent spaces, allowing the sections to share elements in common with each other, despite each being distinctive. The genre miniVAEs also made style transfer possible by interpolating an existing trio towards their latent areas, allowing them to tweak the style of each section. \subsection{ML setup can interfere with musical goals} A logistical hurdle faced by teams was the significant setup and customization issues encountered to even start composing with a model. Aside from musical considerations, many teams chose or abandoned models based on what was available out-of-the-box, such as pre-trained checkpoints, fine-tuning scripts, scripts for retraining on a different dataset, data pre-processing scripts. In addition, different models expected different types of music representation as input (e.g. MIDI, piano roll, custom), adding additional pre-processing overhead to begin experimenting with them. To decrease time spent model wrangling, large teams sometimes divide-and-conquered, exploring several models in parallel to see which worked best. Ultimately, teams' co-creation process involved navigating not only their musical goals, but also the logistical costs and benefits of using one model or another. \section{Discussion} \subsection{Decomposeable and context-aware modeling} Writing a song involves composing multiple sections, and multiple vocal and instrumental parts that all need to work well together as a whole. Because end-to-end models lacked meaningful hierarchical structures, and because smaller models lacked global awareness, participants often needed to reverse engineer a multitude of models, applying heuristics and domain knowledge to approximate high-level structure or to achieve desired musical effects. To ameliorate this process, one approach could be to infuse smaller models with more context-awareness, and exposing the common ways that they can be customized through user-facing controls. For example, a melody model could allow users to express whether they are creating a verse as opposed to a chorus, or whether they would like it to contrast with the next section. Another possibility is to design end-to-end models to have intermediate representations that align with the musical objects that musicians already know how to work with. The sweet spot is probably a hybrid that combines the flexibility of smaller models with the benefits of global context in end-to-end modeling. \subsection{AI-defined vs. User-defined building blocks} The design of ML\; models for music involves a series of upstream decisions that can have a large impact on how musicians think about music when they co-create with these models downstream. Whereas regular songwriting often starts with an initial spark of a human idea, in this work we found that the practical availability and limitations of AI tools were instead key drivers of the creative process, defining the scope of what's musically legitimate or possible. For example, most teams broke down songwriting into lyrics, melody, chords, etc., in part because these models were readily available. Yet, there are also other music building blocks that do not have corresponding, ready-made generative modsels (e.g. motif, verse, chorus, coda, etc.) or that currently are not treated as separate, first-class building blocks in deep models (e.g. rhythm, pitch). Likewise, a musician's creative thought process can be unintentionally influenced by the order of steps taken to fine-tune, condition, prime, and apply a model. In the future, the design of ML\; models should be coupled with a more careful consideration of what workflows and building blocks end-users already use in their existing practice, and perhaps start with those as first-class principles in guiding the design of AI systems. \subsection{Support for parallel music and ML exploration} A central aspect of the creative process involves a ``flare and focus"~\cite{buxton2010sketching} cycle of ideating, exploring those ideas, selecting ideas, then rapidly iterating. We found that a key challenge of human-AI co-creation was the need to juggle not only this \textit{creative} process, but also the \textit{technological} processes imposed by the idiosyncrasies and lack of steerability of learning algorithms. For instance, while ideating motifs for a song, participants needed to carry out a large additional burden of sub-tasks, such as selecting which combination of models to use, re-training or conditioning them as necessary, chaining them together, and ``gluing" their outputs together. In essence, the typical ``flare and focus" cycles of creativity were compounded with a parallel cycle of having to first explore and curate a wide range of models and model outputs (Figure~\ref{fig:parallel}). While some of these model-wrangling tasks led to new inspiration, many interfered with the rapid-iteration cycle of creativity. \begin{figure}[h!] \centerline{ \includegraphics[width=0.95\columnwidth, trim={0cm 0cm 0cm 0cm},clip]{figs/ai_song_workflow_final.png}} \caption{Parallel music and ML feedback loops in human-AI co-creative songwriting.} \label{fig:parallel} \end{figure} These issues raise important questions around how best to support users in juggling the dual processes of creative and technological iteration cycles. One approach is to have ML models readily available to musicians in their natural workflows. For example, Magenta Studio~\cite{roberts2019magenta} makes available a suite of model plug-ins to music production software such as Ableton Live~\cite{ableton}, and Cococo~\cite{louie2020novice} allows users to semantically steer a model directly in its user interface. Beyond this, human-AI interfaces could scaffold the \textit{strategic} part of the model exploration and selection process by surfacing effective model combinations (e.g. using general infilling models for rewriting or to reharmonize another generated melody) or fruitful workflows (e.g. matching lyric and melody stress patterns), so that new users can benefit from past users' experiences. Reducing this overhead of model-based decisions could empower users to more easily prototype their creative ideas, accelerating the feedback and ideation cycle. \vspace{-9pt} \section{Conclusion} We conducted an in-depth examination of how people leverage modern-day deep generative models to co-create songs with AI. We found that participants leveraged a wide range of workarounds and strategies to steer and assemble a conglomeration of models towards their creative goals. These findings have important implications for how human-AI systems can be better designed to support complex co-creation tasks like songwriting, paving the way towards more fruitful human-AI partnerships. \section{Acknowledgements} We thank Karen van Dijk and VPRO for organizing the AI Song Contest, and also NPO Innovatie, 3FM and EBU. We want to thank all participants for their insights and contributions. We also thank Tim Cooijmans for creating early versions of the figures and Michael Terry for feedback on this manuscript. %
{'timestamp': '2020-10-13T02:26:50', 'yymm': '2010', 'arxiv_id': '2010.05388', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05388'}
arxiv
\section{More background} \subsection{Calculus on manifold} \begin{definition}[Levi-Civita Connection] Let $(M,g)$ be a Riemannian manifold. An affine connection is said to be the Levi-Civita connection if it is torsion-free. i.e. \[ \nabla_XY-\nabla_YX=[X,Y] \] for every pair of vector fields $X,Y$ on $M$ and preserves the metric i.e. \[ \nabla g=0. \] \end{definition} \begin{comment} \begin{definition}[Riemannian Curvature Tensor] Let $(M,g)$ be a Riemannian manifold with the associated Levi-Civita connection $\nabla$. Define the Riemannian curvature tensor as \[ R(u,v)w=\nabla_u\nabla_vw-\nabla_v\nabla_uw-\nabla_{[u,v]}w. \] where $u,v$ are vector fields on the $M$. \end{definition} \begin{definition}[Sectional Curvature] Let $(M,g)$ be a Riemannian manifold with the Riemannian curvature tensor $R$. The sectional curvature $K$ is \[ c=\frac{\langle R(u,v)v,u\rangle}{\langle u,u\rangle\langle v,v\rangle-\langle u,v\rangle^2} \] where $u,v$ are linearly independent vectors on the tangent space at a point on the manifold. \end{definition} \begin{definition}[Ricci Curvature]\label{ricci} Let $(M,g)$ be a Riemannian manifold with the Riemannian curvature tensor $R$. The Ricci curvature tensor $Ric_M$ is the trace of the linear map \[ X\rightarrow R(X,Y)Z. \] where $X,Y,Z$ are vector fields on $M$. \end{definition} Note the Ricci curvature is not used in the proof but used in presenting the estimate of the log-Sobolev constant. The following results on Jacobi field is used in proving Theorem \ref{convergence:constant curvature}. \begin{definition}[Variation through geodesic] Let $I,K\subset\mathbb{R}$ are intervals, $\gamma:I\rightarrow M$ is a geodesic, and $\Gamma:K\times I\rightarrow M$ is a variation of $\gamma$. We say that $\Gamma$ is a variation through geodesic if each of the main curves $\Gamma_s(t)=\Gamma(s,t)$ is also a geodesic. \end{definition} \begin{theorem}[The Jacobi Equation] Let $(M,g)$ be a Riemannian manifold, let $\gamma$ be a geodesic, and let $J(t)$ be a vector field along $\gamma$. If $J$ is the variation field of a variation through geodesic, then $J(t)$ satisfies the following equation, called the Jacobi equation: \[ D^2_tJ(t)+R(J(t),\gamma'(t))\gamma'(t)=0. \] \end{theorem} \begin{definition}[Jacobi Field] We call a smooth vector field along a geodesic that satisfies the Jacobi equation a Jacobi field. \end{definition} \end{comment} \begin{definition}[Riemannian Volume] Let $(M,g)$ be an orientable Riemannian manifold. The volume form on the manifold in local coordinates is given as \[ d\mathrm{Vol}=\sqrt{\det (g)}dx_1\wedge...\wedge dx_n. \] \end{definition} We denote $\abs{g}=\det(g)$ and $dx=d\mathrm{Vol}$ (if no ambiguities caused) for short throughout following context. \\ The following Theorem is used to guarantee the exponential map is defined on the whole tangent space, which is equivalent to require $M$ to be complete. This property is satisfied in our setting for $M$ to be compact without boundary. \begin{theorem}[Hopf-Rinow] Let $(M,g)$ be a connected Riemannian manifold. Then the followings are equivalent. \begin{enumerate} \item The closed and bounded subsets of $M$ are compact. \item $M$ is a complete metric space. \item $M$ is geodescically complete: for every point $x\in M$, the exponential map $\mathrm{Exp}_x$ is defined on the entire tangent space $T_xM$. \end{enumerate} \end{theorem} The notion of differential operators, e.g. gradient, divergence and Laplacian for the differentiable functions and vector fields on Euclidean space can be generalized to Riemannian manifold. In local coordinate system, $\{\partial_i=\frac{\partial}{\partial x_i}:i\in[n]\}$ is a basis of the tangent space $T_xM$. Denote $g_{ij}$ the metric matrix, $g^{ij}$ the inverse of $g_{ij}$ and $\abs{g}=\det g_{ij}$ the determinant of matrix $g_{ij}$. Let $f$ and $V$ be differentiable function and vector field on $M$, then the Riemannian gradient of $f$ and the divergence of $V$ are written as \[ \mathrm{grad} f=\sum_{i,j}g^{ij}\frac{\partial f}{\partial x_i}\partial_i \ \ \ \text{and}\ \ \ \mathrm{div} V=\frac{1}{\sqrt{\abs{g}}}\sum_{i}\frac{\partial}{\partial x_i}\left(\sqrt{\abs{g}}V_i\right) \] where $V_i$ is the $i$-th component of $V$. The Laplace-Beltrami operator $\Delta_M$ acting on $f$ is defined to be the divergence of the gradient of $f$, i.e. \[ \Delta_Mf=\mathrm{div}(\mathrm{grad} f)=\frac{1}{\sqrt{\abs{g}}}\sum_i\frac{\partial}{\partial x_i}\left(\sqrt{\abs{g}}\sum_{j}g^{ij}\frac{\partial f}{\partial x_j}\right). \] In Euclidean space, $\Delta_M$ boils down to the classic Laplacian $\Delta f=\nabla\cdot(\nabla f)$. \\ The following integration by parts formulas are used in proof of main lemmas. Let $M$ be a compact oriented Riemannian manifold of dimension $n$ with boundary $\partial M$. Let $X$ be a vector field on $M$. The integration by parts is given by \[ \int_M\langle\mathrm{grad} f,X\rangle=-\int_M f\mathrm{div} X+\int_{\partial M}f\langle X,n\rangle \] or Green's formula \[ \int_M(f\Delta_M g-g\Delta_M f)=-\int_{\partial M}\left(f\frac{\partial g}{\partial n}-g\frac{\partial f}{\partial n}\right) \] If $\partial M$ is empty or the vector field $X$ decay sufficiently fast at infinity of $M$ provided $M$ is open, we have \[ \int_M\langle\mathrm{grad} f,X\rangle=-\int_Mf\mathrm{div} X. \] \begin{definition}[First eigenvalue of Laplacian]\label{eigenLaplacian} The first eigenvalue $\lambda_1\ge 0$ of the Laplacian operator on $M$ is defined to be \[ \lambda_1=\inf_{f\in C_c^{\infty}}\Big\lbrace\frac{\int_M\norm{\mathrm{grad} f}^2dx}{\int_M\norm{f}^2dx}\Big\rbrace. \] \end{definition} \subsection{Stochastic analysis on manifold} Recall that the standard Brownian motion in $\mathbb{R}^n$ is a random process $\{X_t\}_{t\ge 0}$ whose density evolves according to the diffusion equation \[ \frac{\partial\rho(x,t)}{\partial t}=\frac{1}{2}\Delta\rho(x,t). \] Similarly, the Brownian motion in manifold $M$ is $M$-valued random process $\{W_t\}_{t\ge 0}$ whose density function evolves according to the diffusion equation with respect to Laplace-Beltrami operator which is the counterpart of the Laplace operator on Euclidean space. \[ \frac{\partial\rho(x,t)}{\partial t}=\frac{1}{2}\Delta_M\rho(x,t). \] In local coordinate, the Laplace-Beltrami is written as \[ \Delta_M=\sum_{i.j}g^{ij}\frac{\partial^2}{\partial x_i\partial x_j}+\sum_ib_i\frac{\partial}{\partial x_i}, \] where \begin{equation}\label{b} b_i=\sum_j\frac{1}{\sqrt{\abs{g}}}\frac{\partial}{\partial x_j}\left(\sqrt{\abs{g}}g^{ij}\right)=\sum_{j,k}g^{jk}\Gamma^i_{jk}. \end{equation} We can construct Brownian motion in the local coordinate as the solution of the stochastic differential equation for a process $\{X_t\}_{t\ge 0}$: \[ dX_t=\frac{1}{2}b(X_t)dt+\sigma(X_t)dB_t \] where the component $b_i(X_t)$ of $b(X_t)$ is given by (\ref{b}) and $\sigma=(\sigma_{ij})$ is the unique symmetric square root of $g^{-1}=(g^{ij})$. \begin{comment} \begin{definition} A probability measure $\nu$ on $M$ is called to satisfy the logarithmic Sobolev inequality (LSI) if there exists a constant $\alpha>0$ such that \[ \int_Mg^2\log g^2d\nu-\left(\int_Mg^2d\nu\right)\log\left(\int_Mg^2d\nu\right)\le\frac{2}{\alpha}\int_M\norm{\nabla g}^2d\nu, \] for all smooth functions $g:M\rightarrow\mathbb{R}$ with $\int_Mg^2\le\infty$. The largest possible constant $\alpha$ is called the logarithmic Sobolev constant (LSC). \end{definition} It is well known that if a compact manifold always satisfies log-Sobolev inequality \cite{LGross, OV, Rothaus81, Rothaus86, Wang1997, Wang1997x}. \end{comment} \section{Derivation of the GLA} In this section, we give detailed explanation on that the Riemannian Langevin algorithm, as a stochastic process, captures the dynamics of the evolution of the density function for the stochastic process. The derivation is firstly to write the diffusion equation in local coordinate system of the manifold, and then compare the corresponding terms to the Fokker-Planck equation related to stochastic differential equation that gives insight to the local expression of Riemannian Langevin algorithm. In order to do this, recall that the density $e^{-f}$ on $M$ is the stationary solution of the PDE \begin{align} \frac{\partial \rho_t}{\partial t}&=\mathrm{div}\left(\rho_t\mathrm{grad} f+\mathrm{grad} \rho_t\right). \end{align} Using the local expression of Riemannian gradient and divergence operator, this PDE can be written as \begin{align} \frac{\partial \rho_t}{\partial t}=&\frac{1}{\sqrt{\abs{g}}}\sum_{i=1}^n\frac{\partial}{\partial x_i}\left(\sqrt{\abs{g}}\left(\sum_j g^{ij}\frac{\partial f}{\partial x_j}\right)\rho_t+\sqrt{\abs{g}}\sum_jg^{ij}\frac{\partial \rho_t}{\partial x_j}\right) \\ =&\frac{1}{\sqrt{\abs{g}}}\sum_i\frac{\partial}{\partial x_i}\left(\left(\sum_jg^{ij}\frac{\partial f}{\partial x_j}-\frac{1}{\sqrt{\abs{g}}}\sum_j\frac{\partial}{\partial x_j}\left(\sqrt{\abs{g}}g^{ij}\right)\right)\sqrt{\abs{g}}\rho_t\right) \\ &+\frac{1}{\sqrt{\abs{g}}}\sum_{i,j}\frac{\partial^2}{\partial x_i\partial x_j}\left(g^{ij}\sqrt{\abs{g}}\rho_t\right) \end{align} Denoting $\tilde{\rho}_t=\sqrt{\abs{g}}\rho_t$, we have the Fokker-Planck equation of density in Euclidean space as follows, \begin{equation}\label{FP1} \pder[\tilde{\rho}_t]{t}=-\sum_i\pder{x_i}\left(\left(\frac{1}{\sqrt{\abs{g}}}\sum_j\pder{x_j}\left(\sqrt{\abs{g}}g^{ij}\right)-\sum_jg^{ij}\pder[f]{x_j}\right)\tilde{\rho}_t\right)+\sum_{i,j}\frac{\partial^2}{\partial x_i\partial x_j}\left(g^{ij}\tilde{\rho}_t\right). \end{equation} Since for any stochastic differential equation of the form \[ dX_t=F(X_t,t)dt+\sigma(X_t,t)dB_t \] the density $p_t$ for $X_t$ satisfies \begin{equation}\label{FP2} \frac{\partial p(x,t)}{\partial t}=-\sum_{i=1}^n\frac{\partial}{\partial x_i}\left(F_i(x,t)p(x,t)\right)+\sum_{i=1}^n\sum_{j=1}^n\frac{\partial^2}{\partial x_i\partial x_j}\left(A_{ij}(x,t)p(x,t)\right) \end{equation} where $A=\frac{1}{2}\sigma\sigma^{\top}$, i.e. $A_{ij}=\frac{1}{2}\sum_{k=1}^n\sigma_{ik}(x,t)\sigma_{jk}(x,t)$. Compare equations (\ref{FP1}) and (\ref{FP2}), we have the drift and diffusion terms in local coordinate systems are given by \[ F_i(x_t)=-\sum_jg^{ij}\frac{\partial f}{\partial x_j}+\frac{1}{\sqrt{\abs{g}}}\sum_j\frac{\partial}{\partial x_j}\left(\sqrt{\abs{g}}g^{ij}\right) \] and \[ \sigma(x_t)=\sqrt{2(A_{ij})}=\sqrt{2(g^{ij})}=\sqrt{2g^{-1}}. \] So the local Langevin equation is \begin{equation} dX_t=F(X_t)dt+\sqrt{2g^{-1}}dB_t. \end{equation} This equation describes infinitesimal evolution of $X_t$, which can be seen as a process in the tangent space of $M$. The Riemannian Langevin algorithm is the classic Euler-Maruyama discretization in the tangent space, i.e., by letting $X_t$ move in the tangent space for a positive time interval $t\in[0,\epsilon]$ with the drift and diffusion at current location. Suppose the initial point is $x_0$, the tangent vector is \[ \epsilon F(x_0)+\sqrt{2\epsilon g^{-1}(x_0)}\xi_0 \] where $\xi_0\sim\mathcal{N}(0,I)$ is the standard Gaussian noise. Then the updated point is obtained by mapping the vector to the base manifold via exponential map, \[ x_1=\mathrm{Exp}_{x_0}\left(\epsilon F(x_0)+\sqrt{2\epsilon g^{-1}(x_0)}\xi_0\right). \] Renaming $x_k=x_0$ and $x_{k+1}=x_1$, we have the general form \[ x_{k+1}=\mathrm{Exp}_{x_k}\left(\epsilon F(x_k)+\sqrt{2\epsilon g^{-1}(x_k)}\xi_0\right). \] We give the expression of the algorithm in normal coordinate, for convenience in part of the proofs of main theorems. For any manifold $M$, and $x\in M$, $T_xM$ is isomorphic to $\mathbb{R}^n$, $\exp_x^{-1}$ gives a local coordinate system of $M$ around $x$. This is called the normal coordinates at $x$. The following lemmas are from Lee-Vampalar \begin{lemma} In normal coordinate, we have \[ g_{ij}(x)=\delta_{ij}-\frac{1}{3}\sum_{kl}R_{ikjl}(x)x^kx^l+O(\abs{x}^3). \] \end{lemma} Under normal coordinate, the RLA can be written as \[ x_{t+1}=\mathrm{Exp}_{x_t}(-\epsilon\nabla f(x_t)+\sqrt{2\epsilon}\xi_0). \] Note that the expression in the tangent space is exactly the same as unadjusted Langevin algorithm in Euclidean space. \section{Missing proofs of Section \ref{MainResults}} \subsection{Proof of Theorem \ref{convergence:continuous}} In this section, we proof that the KL divergence decreases along the process evolving following Riemannian Langevin equation. \\ \\ Firstly, need show that according to the SDE on manifold in local chart, the density function evolves according to Fokker-Planck/diffusion equation on this manifold. \begin{customlemma}{\ref{lemma:continuous1} Suppose $\rho_t$ evolves following the Fokker-Planck equation (\ref{FP00}), then \[ \frac{d}{dt}H(\rho_t|\nu)=-\int_M\rho_t(x)\norm{\mathrm{grad}\log\frac{\rho_t(x)}{\nu(x)}}^2dx \] where $dx$ is the Riemannian volume element. \end{customlemma} \begin{proof} Since \begin{align} \int_M\rho_t\frac{\partial}{\partial t}\log\frac{\rho_t}{\nu}dx&=\int_M\rho_t\frac{\partial}{\partial t}(\log\rho_t+f)dx \\ &=\int_M\frac{\partial \rho_t}{\partial t}dx \\ &=\frac{d}{dt}\int_M\rho_tdx=0, \end{align} we have \begin{align} \frac{d}{dt}H(\rho_t|\nu)&=\frac{d}{dt}\int_M\rho_t\log\frac{\rho_t}{\nu}dx \\ &=\int_M\frac{d}{dt}\left(\rho_t\log\frac{\rho_t}{\nu}\right)dx \\ &=\int_M\frac{\partial\rho_t}{\partial t}\log\frac{\rho_t}{\nu}dx+\int_M\rho_t\frac{\partial}{\partial t}\log\frac{\rho_t}{\nu}dx \\ &=\int_M\frac{\partial\rho_t}{\partial t}\log\frac{\rho_t}{\nu}dx. \end{align} Plug in with diffusion equation \[ \frac{\partial\rho_t}{\partial t}=\mathrm{div}(\rho_t\mathrm{grad} f+\mathrm{grad} \rho_t) \] and apply integration by parts, we obtain \begin{align} \frac{d}{dt}H(\rho_t|\nu)&=\int_M\mathrm{div}(\rho_t\mathrm{grad} f+\mathrm{grad} \rho_t)\log\frac{\rho_t}{\nu}dx \\ &=-\int_{M}\rho_t\norm{\mathrm{grad}\log\frac{\rho_t}{\nu}}^2dx \\ &+\int_{\partial M}\log\frac{\rho_t}{\nu}\langle\rho_t\mathrm{grad} f+\mathrm{grad}\rho_t,n\rangle dx \end{align} Since $M$ is compact and has no boundary, the boundary integral equals to zero, then we have \[ \frac{d}{dt}H(\rho_t|\nu)=-\int_M\rho_t\norm{\mathrm{grad}\log\frac{\rho_t}{\nu}}^2dx \] \end{proof} \begin{customthm}{\ref{convergence:continuous}} Suppose $\nu$ satisfies LSI with constant $\alpha>0$. Then along the Riemannian Langevin equation, i.e. the SDE (\ref{FP:local}) in local coordinate systems, the density $\rho_t$ satisfies \[ H(\rho_t|\nu)\le e^{-2\alpha t}H(\rho_0|\nu). \] \end{customthm} \begin{proof} By LSI, we have \[ \frac{d}{dt}H(\rho_t|\nu)\le-2\alpha H(\rho_t|\nu), \] multiplying both sides by $e^{\alpha t}$, \[ e^{2\alpha t}\frac{d}{dt}H(\rho_t|\nu)\le-2\alpha e^{2\alpha t}H(\rho_t|\nu) \] and then \[ e^{2\alpha t}\frac{d}{dt}H(\rho_t|\nu)+2\alpha e^{2\alpha t}H(\rho_t|\nu)=\frac{d}{dt}e^{2\alpha t}H(\rho_t|\nu)\le 0. \] Integrating for $0\le t\le s$, the result holds as \[ e^{2\alpha s}H(\rho_s|\nu)-H(\rho_0|\nu)=\int_0^s\frac{d}{dt}e^{2\alpha t}H(\rho_t|\nu)\le 0. \] Rearranging and renaming $s$ by $t$, we conclude \[ H(\rho_t|\nu)\le e^{-2\alpha t}H(\rho_t|\nu) \] \end{proof} \subsection{Proof of Theorem \ref{convergence:discrete}} \begin{lemma}\label{lemma:1} Assume $\nu=e^{-f}$ is $L$-smooth. Then \[ \mathbb{E}_{\nu}[\norm{\mathrm{grad} f}^2]\le nL. \] \end{lemma} \begin{proof} Since \[ \mathbb{E}_{\nu}[\norm{\mathrm{grad} f}^2]=\int_M\langle\mathrm{grad} f,\mathrm{grad} f\rangle e^{-f}dx=-\int_M\langle\mathrm{grad} e^{-f},\mathrm{grad} f\rangle dx, \] where $dx$ is the Riemannian volume element. Integration by parts on manifold gives the following \[ -\int_M\langle\mathrm{grad} e^{-f},\mathrm{grad} f\rangle dx=\int_Me^{-f}\Delta_Mfdx-\int_{\partial M}e^{-f}\langle\mathrm{grad} f,n\rangle ds \] where $ds$ is the area element on $\partial M$. By the assumption that $M$ is boundaryless, the integral on the boundary is 0. By the assumption $\mathrm{Hess} f$ is $L$-smooth and the fact that $\mathrm{Hess} f\ge\frac{1}{n}\Delta_Mf$, we conclude $\mathbb{E}_{\nu}[\norm{\mathrm{grad} f}^2]\le nL$ \end{proof} \begin{lemma}\label{lemma:2} Suppose $\nu$ satisfies Talagrand inequality with constant $\alpha>0$ and $L$-smooth. Then for any $\rho$, \[ \mathbb{E}_{\rho}[\norm{\mathrm{grad} f}^2]\le\frac{4L^2}{\alpha}H(\rho|\nu)+2nL. \] \end{lemma} \begin{proof} Let $x\sim\rho$ and $y\sim\nu$ with optimal coupling $(x,y)$ so that \[ \mathbb{E}[d(x,y)^2]=W_2(\rho,\nu)^2. \] $\mathrm{grad} f$ is $L$-Lipschitz from the assumption that $f$ is $L$-smooth. So we have the following inequality: \begin{align} \norm{\mathrm{grad} f(x)}&\le\norm{\mathrm{grad} f(x)-\Gamma_y^x\mathrm{grad} f(y)}+\norm{\Gamma_y^x\mathrm{grad} f(y)} \\ &\le Ld(x,y)+\norm{\Gamma_y^x\mathrm{grad} f(y)} \\ &=Ld(x,y)+\norm{\mathrm{grad} f(y)} \end{align} where the equality follows from that parallel transport is an isometry. The same arguments as V-W gives \[ \norm{\mathrm{grad} f(x)}^2\le(Ld(x,y)+\norm{\mathrm{grad} f(y)})^2\le 2Ld(x,y)^2+2\norm{\mathrm{grad} f(y)}^2 \] and \begin{align} \mathbb{E}_{\rho}[\norm{\mathrm{grad} f(x)}^2]&\le 2L^2\mathbb{E}[d(x,y)^2]+2\mathbb{E}_{\nu}[\norm{\mathrm{grad} f(y)}^2] \\ &=2L^2W_2(\rho,\nu)^2+2\mathbb{E}_{\nu}[\norm{\mathrm{grad} f(y)}^2]. \end{align} By Talagrand inequality and previous lemma, the result follows. \end{proof} \begin{assumption} We next assume the existence of constants shown in the convergence result. Let the joint distribution $p_{0t}(x_0,x)$ be differentiable and assume that $\frac{\frac{\partial^2p_{0t}(x_0,x)}{\partial x_i\partial x_j}\log\frac{p_t}{\nu}}{p_{0t}(x_0,x)}$ is bounded by $K_2$ and $\frac{\abs{\frac{\partial p_{0t}(x_0,x)}{\partial x_i}}\log\frac{p_t}{\nu}}{p_{0t}(x_0,x)}$ is bounded by $K_3$. \end{assumption} \begin{lemma}\label{lemma:4} Suppose $\nu$ satisfies LSI with constant $\alpha>0$ and is $L$-smooth. If $\epsilon$ small enough, then along each step, \[ H(p_{\epsilon}|\nu)\le e^{-\alpha\epsilon}H(p_0|\nu)+4\epsilon^2(2nL^2+2n^3K_2C+nK_3K_4) \] for small $\epsilon$, and \[ H(p_{k+1}|\nu)\le e^{-\alpha\epsilon}H(p_k|\nu)+4\epsilon^2(2nL^2+2n^3K_2C+nK_3K_4). \] for all $k\in\mathbb{N}$. \end{lemma} \input{new} \begin{customthm}{\ref{convergence:discrete}} Suppose $M$ is a compact manifold without boundary and $R$ is the Riemann curvature, $\nu=e^{-f}$ a density on $M$ with $\alpha>0$ the log-Sobolev constant. Then there exists a global constant $K_2,K_3,K_4,C$, such that for any $x_0\sim\rho_0$ with $H(\rho_0|\nu)\le\infty$, the iterates $x_k\sim\rho_k$ of GLA with stepsize $\epsilon\le\min\{\frac{\alpha}{4L\sqrt{L^2+n^2K_2C}},\frac{2nL^2+2n^3K_2C+nK_3K_4}{2(nL^3+n^3K_2CL)},\frac{1}{2L},\frac{1}{2\alpha}\}$ satisfty \[ H(p_k|\nu)\le e^{-\alpha k\epsilon}H(p_0|\nu)+\frac{16\epsilon}{3\alpha}(2nL^2+2n^3K_2C+nK_3K_4) \] \end{customthm} \begin{proof} \begin{align} H(p_k|\nu)&\le e^{-\alpha k\epsilon}H(p_0|\nu)+\frac{1-e^{-\alpha k\epsilon}}{1-e^{-\alpha\epsilon}}4\epsilon(2nL^2+2n^3K_2C+nK_3K_4) \\ &\le e^{-\alpha k\epsilon}H(p_0|\nu)+\frac{4}{3\alpha\epsilon}4\epsilon^2(2nL^2+2n^3K_2C+nK_3K_4) \\ &= e^{-\alpha k\epsilon}H(p_0|\nu)+\frac{16\epsilon}{3\alpha}(2nL^2+2n^3K_2C+nK_3K_4) \end{align} \begin{comment} By Lemma \ref{lemma:4}, we have the following relation of $H(\rho_k|\nu)$ and $H(\rho_0|\nu)$, \begin{align} H(\rho_k|\nu)&\le e^{-\frac{k}{2}\alpha\epsilon}H(\rho_0|\nu)+\frac{1}{1-e^{-\frac{1}{2}\alpha\epsilon}}(6\epsilon^2nL^2+4K(R)nL\epsilon^3). \end{align} Since for $0<\alpha\epsilon\le \frac{1}{2}$, (this also implies that $\epsilon\le\frac{1}{\alpha}$), we have $1-e^{-\frac{1}{2}\alpha\epsilon}\ge \frac{3}{8}\alpha\epsilon$, and then \[ H(\rho_k|\nu)\le e^{-\frac{k}{2}\alpha\epsilon}H(\rho_0|\nu)+\frac{16\epsilon nL^2}{\alpha}+\frac{32K(R)nL\epsilon^2}{3\alpha}. \] Choosing $\epsilon\le\frac{3L}{2K(R)}$ so that $\frac{32K(R)nL\epsilon^2}{3\alpha}\le\frac{16\epsilon nL^2}{\alpha}$, the above inequality can be simplified to \[ H(\rho_k|\nu)\le e^{-\frac{k}{2}\alpha\epsilon}H(\rho_0|\nu)+\frac{32\epsilon nL^2}{\alpha} \] \end{comment} \end{proof} \newpage \section{Experiments} As mentioned before, for simplicity, we can implement GLA without using the exponential map where a geodesic ODE solver is required, especially for the case when $M$ is a submanifold of $\mathbb{R}^n$. In general, the retraction map from $T_xM$ to $M$ is used in optimization on Riemannian manifold \cite{Boumal1}, as a replacement of exponential map. In this section, we give experiments on sampling from distributions on the unit sphere in comparison of exponential map and orthogonal projection as a retraction in the geodesic step of GLA. The experiments are designed to verify the following properties: \begin{enumerate} \item GLA captures the target distribution $e^{-f}$ as expected; \item The projection map behaves well in replacing the exponential map without solving geodesic equations. \end{enumerate} In each set of figures, (a) is the landscape of the ideal distribution, (b) and (c) are the results with small number of iterations for exponential map and projection, (d) and (e) are enhanced with large number of iterations. We start with the definition of the general retraction in optimization on manifold. \begin{definition}[Retraction] A retraction on a manifold $M$ is a smooth mapping $\mathrm{Retr}$ from the tangent bundle $TM$ to $M$ satisfying properties 1 and 2 below: Let $\mathrm{Retr}_x:T_xM\rightarrow M$ denote the restriction of $Retr$ to $T_xM$. \begin{enumerate} \item $\mathrm{Retr}_x(0)=x$, where $0$ is the zero vector in $T_xM$. \item The differential of $\mathrm{Retr}_x$ at $0$ is the identity map. \end{enumerate} \end{definition} Suppose $M$ is a submanifold of $\mathbb{R}^n$ with positive codimension. Denote $\mathrm{Proj}_{T_xM}$ the orthogonal projection to the tangent space at $x$, then the retraction can be defined as $\mathrm{Retr}_x(v)=\mathrm{Proj}_M(x+v)$. The GLA on a submanifold of $\mathbb{R}^n$ can be written as \begin{equation}\label{VGLA} x_{k+1}=\mathrm{Retr}_x\left(\mathrm{Proj}_{T_xM}(-\epsilon\nabla f(x_k)+\sqrt{2\epsilon}\xi_0)\right) \end{equation} If $M=S^{n-1}$ be the unit sphere in $\mathbb{R}^n$, then $\mathrm{Retr}_x(v)=\frac{x+v}{\norm{x+v}}$. \begin{figure} \centering \subfigure[Ideal distribution of $e^{-f}$]{\includegraphics[width=0.4\textwidth]{density_1Tx3d}} \\ \subfigure[$\mathrm{Exp}_x(v)$, iteration: 10k]{\label{fig:a}\includegraphics[width=0.4\textwidth]{exp_1Tx3d_10ksamples}} \hspace{0.1\textwidth} \subfigure[$\mathrm{Retr}_x(v)$, iteration: 10k]{\label{fig:b}\includegraphics[width=0.4\textwidth]{proj_1Tx3d_10ksamples}} \subfigure[$\mathrm{Exp}_x(v)$, iteration: 100k]{\includegraphics[width=0.4\textwidth]{exp_1Tx2d_100ksamples}} \hspace{0.1\textwidth} \subfigure[$\mathrm{Retr}_x(v)$, iteration: 100k]{\includegraphics[width=0.4\textwidth]{proj_1Tx2d_100ksamples}} \caption{$f(x)=x_1+x_2+x_3$, stepsize $\epsilon=0.1$.} \label{Fig2} \end{figure} \begin{figure} \centering \subfigure[Ideal distribution of $e^{-f}$]{\includegraphics[width=0.4\textwidth]{density_poly3d}} \\ \subfigure[$\mathrm{Exp}_x(v)$, iteration: 10k]{\label{fig:ax}\includegraphics[width=0.4\textwidth]{exp_poly3d}} \hspace{0.1\textwidth} \subfigure[$\mathrm{Retr}_x(v)$, iteration: 10k]{\label{fig:bx}\includegraphics[width=0.4\textwidth]{proj_poly3d}} \subfigure[$\mathrm{Exp}_x(v)$, iteration: 100k]{\includegraphics[width=0.4\textwidth]{exp_poly3d_100ksamples_0dot1stepsize}} \hspace{0.1\textwidth} \subfigure[$\mathrm{Retr}_x(v)$, iteration: 100k]{\includegraphics[width=0.4\textwidth]{proj_poly3d_100ksamples}} \caption{$f(x)=x_1^2+3.05x_2^2-0.9x_3^2+1.1x_1x_2+-1.02x_2x_3+2.1x_3x_1$, setpsize $\epsilon=0.1$.} \label{Fig3} \end{figure} \section{Introduction} We focus on the problem of sampling from a distribution $e^{-f(x)}$ supported on a Riemannian manifold $M$ with standard volume measure. Sampling is a fundamental and arguably very important task with numerous applications in machine learning and Langevin dynamics is a quite standard approach. There is a growing interest in Langevin algorithms, e.g. \cite{Welling, Wibisono18, ArnakD}, due to its simple structure and the good empirical behavior. The classic Riemannian Langevin algorithm, e.g. \cite{GC11, PattersonTeh, ZPFP}, is used to sample from distributions supported on $\mathbb{R}^n$ (or a subset $D$) by endowing $\mathbb{R}^n$ (or $D$) a Riemannian structure. Beyond the classic application of Riemannian Langevin Algorithm (RLA), recent progress in \cite{DJMRB, MoritaRisteski, LiErdogdu} shows that sampling from a distribution on a manifold has application in matrix factorization, principal component analysis, matrix completion, solving SDP, mean field and continuous games and GANs. Formally, a game with finite number of agents is called continuous if the strategy spaces are continuous, either a finite dimensional differential manifold or an infinite dimensional Banach manifold \cite{RBS13, RBS16, DJMRB}. The mixed strategy is then a probability distribution on the strategy manifold and mixed Nash equilibria can be approximated by Langevin dynamics. \paragraph{Geodesic Langevin Algorithm (GLA).} In order to sample from a distribution on $M$, geodesic based algorithms (e.g. Geodesic Monte Carlo and Geodesic MCMC) are considered in \cite{BG13, LZS16}, where a geodesic integrator is used in the implementation. We propose a Geodesic Langevin Algorithm (GLA) as a natural generalization of unadjusted Langevin algorithm (ULA) from the Euclidean space to manifold $M$. The benefit of GLA is to leverage sufficiently the geometric information (curvature, geodesic distance, isoperimetry) of $M$ while keeping the structure of the algorithm simple enough, so that we can obtain a non-asymptotic convergence guarantee of the algorithm. In local coordinate systems, the Riemannian metric is represented by a matrix $g=\{g_{ij}\}$, see Definition \ref{rmetric}. We denote $g^{ij}$ the $ij$-th entry of the inverse matrix $g^{-1}$ of $g$, and $\abs{g}=\det(g_{ij})$, the determinant of the matrix $\{g_{ij}\}$. Then GLA is the stochastic process on $M$ that is defined by \begin{equation}\label{GLA} x_{k+1}=\mathrm{Exp}_{x_k}(\epsilon F+\sqrt{2\epsilon g^{-1}}\xi_0) \end{equation} where $F=(F_1,...,F_n)$ with \begin{equation}\label{SDE:F} F_i=-\sum_jg^{ij}\frac{\partial f}{\partial x_j}+\frac{1}{\sqrt{\abs{g}}}\sum_j\frac{\partial}{\partial x_j}\left(\sqrt{\abs{g}}g^{ij}\right), \end{equation} $\epsilon>0$ is the stepsize, $\xi_0\sim \mathcal{N}(0,I)$ is the standard Gaussian noise, and $\mathrm{Exp}_x(\cdot):T_xM\rightarrow M$ is the exponential map (Definition \ref{exp map}). Clearly GLA is a two-step discretization scheme of the Riemannian Langevin equation \[ dX_t=F(X_t)dt+\sqrt{2g^{-1}}dB_t \] where $F$ is given by (\ref{SDE:F}). Suppose the position at time $k$ is $x_k$, then the next position $x_{k+1}$ can be obtained by the following tangent-geodesic composition: \begin{enumerate} \item Tangent step: Take a local coordinate chart $\varphi:U_{x_k}\rightarrow\mathbb{R}^n$ at $x_k$, this map induces the expression of $g_{ij}$ and $g^{ij}$, then compute the vector $v=\epsilon F+\sqrt{2\epsilon g^{-1}}\xi_0$ in tangent space $T_{x_k}M$; \item Geodesic step: Solve the geodesic equation (a second order ODE) whose solution is a curve $\gamma(t)\subset\varphi(U_{x_k})$, such that the initial conditions satisfy $\gamma(0)=\varphi(x_k)$ and $\gamma'(0)=v$. Then let $x_{k+1}=\gamma(1)$ be the updated point. \end{enumerate} The exponential map and ODE solver for geodesic equations is commonly used in sampling algorithms on manifold, e.g. \cite{VempalaLee17, BG13, LZS16}. We will discuss on other approximations of the exponential map without solving ODEs through illustrations in a later section. Figure \ref{fig1} gives an intuition of GLA on the unit sphere where the exponential map is $\mathrm{Exp}_x(v)=\cos(\norm{v})x+\sin(\norm{v})\frac{v}{\norm{v}}$. \begin{figure}[h] \centering \includegraphics[width=0.5\textwidth]{exp_poly3d_100ksamples_0dot1stepsize} \caption{$f(x_1,x_2,x_3)=x_1^2+3.05x_2^2-0.9x_3^2+1.1x_1x_2+-1.02x_2x_3+2.1x_3x_1$, $\epsilon=0.1$, Iterations: 100k.} \label{fig1} \end{figure} The main result on convergence is stated as follows. \begin{theorem}[Informal]\label{mtheoremintro} Let $M$ be a closed $n$-dimensional manifold (Definition \ref{closedM}). Suppose that $\nu=e^{-f(x)}$ is a distribution on $M$ with $\alpha>0$ the log-Sobolev constant. Then there exists a real number $K_2,K_3,K_4,C$, such that by choosing stepsize $\epsilon$ properly based on the Lipschitz constant of the Riemannian gradient of $f$, log-Sobolev constant of the target distribution $\nu$, dimension and curvature of $M$, the KL divergence $H(\rho_k|\nu)$ decreases along the GLA iterations rapidly in the sense that \[ H(p_k|\nu)\le e^{-\alpha k\epsilon}H(p_0|\nu)+\frac{16\epsilon}{3\alpha}(2nL^2+2n^3K_2C+nK_3K_4). \] \end{theorem} The same as unadjusted Langevin algorithm (ULA) in Euclidean space, GLA is a biased algorithm that converges to a distribution different from $e^{-f(x)}$. But from the above theorem, one can set up the error $\delta>0$ and take stepsize $\epsilon<\frac{\alpha\delta}{2CnL^2}$ while satisfying the standard from above theorem, and GLA will reach the error $H(\rho_k|\nu)<\delta$ after $k> \frac{2}{\alpha\epsilon}\log\frac{2H(\rho_0|\nu)}{\delta}$ iterations. Practically we need a lower bound estimate for $\alpha$. With additional condition on Ricci curvature, this lower bound can be chosen based on the diameter of $M$ by Theorem \ref{logsobconst}. Our main technical contributions are: \begin{itemize} \item A non-asymptotic convergence guarantee for Geodesic Langevin algorithm on closed manifold is provided, with the help of log-Sobolev inequality. \item The framework of this paper serves as the first step understanding to the rate of convergence in sampling from distributions on manifold with log-Sobolev inequality, and can be generalized to prove non-asymptotic convergence results for more general settings and more subtle algorithms, i.e., for open manifolds and unbiased algorithms. \end{itemize} \textbf{Comparison to literarture} The typical difference between algorithm (\ref{GLA}) and the classic RLA is the use of exponential map. As $\epsilon\rightarrow 0$, both GLA and RLA boil down to the same continuous time Langevin equation in the local coordinate system: \[ dX_t=F(X_t)dt+\sqrt{2g^{-1}}dB_t \] where $F$ is given by (\ref{SDE:F}) and $B_t$ is the standard Brownian motion in $\mathbb{R}^n$. The direct Euler-Maryuyama discretization iterates in the way that $x_{k+1}=x_t+\epsilon F(x_k)+\sqrt{2\epsilon g^{-1}(x_k)}\xi_0$. However, by adding the vector $\epsilon F(x_k)+\sqrt{2\epsilon g^{-1}(x_k)}\xi_0$ that is in the tangent space to a point $x_k$ that is on the manifold $M$ has no intrinsic geometric meaning, since the resulted point $x_{k+1}$ is indeed not in $M$. The exponential map just gives a way to pull $x_{k+1}$ back to $M$. On the other hand, since RLA is firstly used to sample from distributions on $\mathbb{R}^n$ (or its domain) with a Riemannian structure, \cite{RS02, GC11, PattersonTeh, SDRLS18}, this requires a global coordinate system of $M$, i.e. $M$ is covered by a single coordinate chart and the iterations do not transit between different charts. But this makes it difficult to use RLA when there are inevitably multiple coordinate charts on $M$. More sophisticated algorithms like Geodesic MCMC \cite{LZS16} is used to transit between different coordinate charts, but to the best knowledge of the authors, the rate of convergence is missing in the literature. Li and Erdogdu \cite{LiErdogdu} generalize the result of \cite{VW19} by implementing the Riemannian Langevin algorithm in two steps (gradient+Riemannian Brownian motion). \section{Related Works} Unadjusted Langevin algorithm (ULA) when sampling from a strongly logconcave density in Euclidean space has been studied extensively in the literature. The bounds for ULA is known in \cite{CB, ArnakD, DalalyanKara, DMM}. The case when $f$ is strongly convex and has Lipschitz gradient is studied by \cite{ArnakD17, DurmusMouline17, DurmusMouline19}. Since ULA is biased because of the discretization, i.e. it converges to a limit distribution that is different from that from continuous Langevin equation. the Metropolis-Hastings correction is widely used to correct this bias, e.g. \cite{RT96, DCWY18}. A simplified correction algorithm is proposed by \cite{Wibisono18} that is called symmetrized Langevin algorithm with a smaller bias than ULA. Convergence results is obtained for Proximal Langevin algorithm (PLA) in \cite{Wibisono19}. In the case where the target distribution is log-concave, there are other algorithms proven to converge rapidly, i.e., Langevin Monte Carlo by \cite{Bernton18}, ball walk and hit-and-run \cite{KLS97, LV06, LV07, LVempala06}, and Hamiltonian Monte Carlo by \cite{DMS17, VempalaLee18, MVishnoi18}. The underdamped version of the Langevin dynamics under log-Sobolev inequality is studied by \cite{MaCCFBJ}, where an iteration complexity for the discrete time algorithm that has better dependence on the dimension is provided. A coupling approach is used by \cite{EGZ18} to quantify convergence to equilibrium for Langevin dynamics that yields contractions in a particular Wasserstein distance and provides precise bounds for convergence to equilibrium. The case where the densities that are neither smooth nor log-concave is studied in \cite{LuuFC} and asymptotic consistency guarantees is provided. For the Wasserstein distance, \cite{CCYBJ, MMSz, RRT17} provide convergence bound. An earlier research on stochastic gradient Langevin dynamics with application in Bayesian learning is proposed by \cite{Welling}, The Langevin Monte Carlo with a weaker smoothness assumption is studied by \cite{CDJB19}. In order to improve sample quality, \cite{GMackey} develops a theory of weak convergence for kernel Stein discrepancy based on Stein's method. In general, sampling from non log-concave densities is hard, \cite{GeLR} gives an exponential lower bound on the number of queries required. The Riemannian Langevin algorithm has been studied in different extent. Related to volume computation of a convex body in Euclidean space, one can endow the interior of a convex body the structure of a Hessian manifold and run geodesic (with respect to the Hessian metric) random walk \cite{VempalaLee17} that is a discretization scheme of a stochastic process with uniform measure as the stationary distribution. The rigorous proof of the convergence of Riemannian Hamiltonian Monte Carlo for sampling Gibbs distribution and uniform distribution in a polytope is given by \cite{VempalaLee18}. In sampling non-uniform distribution, \cite{ZPFP} gives a discretization scheme related to mirror descent and a non-asymptotic upper bound on the sampling error of the Riemannian Langevin Monte Carlo algorithm in Hessian manifold. The mirrored Langevin is firstly considered by \cite{HKRC18} and a non-asymptotic rate is obtained and generalized to the case when only stochastic gradients (mini-batch) are available. An affine invariant perspective of continuous time Langevin dynamics for Bayesian inference is studied in \cite{INR19}. Positive curvature is used to show concentration results for Hamiltonian Monte Carlo in \cite{SRSH}. \cite{LZZ19} understand MCMC as gradient flows on Wasserstein spaces and HMC on implicitly defined manifolds is studied in \cite{BSU} \section{Conclusion} In this paper we focus on the problem of sampling from a distribution on a Riemannian manifold and propose the Geodesic Langevin Algorithm. GLA modifies the Riemannian Langevin algorithm by using exponential map so that the algorithm is defined globally. By leveraging the geometric meaning of GLA, we provide a non-asymptotic convergence guarantee in the sense that the KL divergence (as well as the Wasserstein distance) decreases fast along the iterations of GLA. By assuming that we have full access to the geometric data of the manifold, we can control the bias between the stationary distribution of GLA and the target distribution to be arbitrarily small through the choice of stepsize. The assumptions on the joint densities are not natural and there is no obvious way to determine the constants. Further work is expected to improve the results so that they do not depend on the assumption. \section*{Acknowledgement} We thank Mufan (Bill) Li and Murat A. Erdogdu for pointing out the mistakes in the original version and their helpful comments on revision and correction. Xiao Wang would like to acknowledge the NRF-NRFFAI1-2019-0003, SRG ISTD 2018 136 and NRF2019-NRF-ANR095 ALIAS grant. Qi Lei is supported by Computing Innovation Fellowship. \section{Preliminaries} For a complete introduction to Riemannian manifold and stochastic analysis on manifold, we recommend \cite{JLee} and \cite{Hsu} for references. \subsection{Riemannian geometry} \begin{definition}[Manifold] A $C^k$-differentiable, $n$-dimensional manifold is a topological space $M$, together with a collection of coordinate charts $\{(U_{\alpha},\varphi_{\alpha})\}$, where each $\varphi_{\alpha}$ is a $C^k$-diffeomorphism from an open subset $U_{\alpha}\subset M$ to $\mathbb{R}^n$. The charts are compatible in the sense that, whenever $U_{\alpha}\cap U_{\beta}\ne\emptyset$, the transition map $\varphi_{\alpha}\circ\varphi_{\beta}^{-1}(U_{\beta}\cap U_{\alpha})\rightarrow\mathbb{R}^n$ is of $C^k$. \end{definition} \begin{definition}[Closed manifold]\label{closedM} A manifold $M$ is called \emph{closed} if $M$ is compact and has no boundary. \end{definition} Typical examples of closed manifolds include sphere and torus. \begin{definition}[Riemannian metric]\label{rmetric} A Riemannian manifold $(M,g)$ is a differentiable manifold $M$ with a Riemannian metric $g$ defined as the inner product on the tangent space $T_xM$ for each point $x$, $g(\cdot,\cdot):T_xM\times T_xM\rightarrow\mathbb{R}$. Then length of a smooth path $\gamma:[0,1]\rightarrow M$ is $\abs{\gamma}=\int_0^1\sqrt{g(\gamma'(t),\gamma'(t))}dt$. In a local coordinate chart, $g$ is represented by a $n\times n$ symmetric positive definite matrix with entries $g_{ij}$. \end{definition} \begin{definition}[Geodesic]\label{geodesic} We call a curve $\gamma(t):[0,1]\rightarrow M$ a geodesic if it satisfies both of the following conditions: \begin{enumerate} \item The curve $\gamma(t)$ is parametrized with constant speed, i.e. $\norm{\frac{d}{dt}\gamma(t)}_{\gamma(t)}$ is constant for $t\in[0,1]$. \item The curve is the locally shortest length curve between $\gamma(0)$ and $\gamma(1)$, i.e. for any family of curve $c(t,s)$ with $c(t,0)=\gamma(t)$ and $c(0,s)=\gamma(0)$ and $c(1,s)=\gamma(1)$, we have $\frac{d}{ds}|_{s=0}\int_{0}^1\norm{\frac{d}{dt}c(t,s)}_{c(t,s)}dt=0$. \end{enumerate} \end{definition} We use $\gamma_{x\rightarrow y}$ to denote the geodesic from $x$ to $y$ ($\gamma_{x\rightarrow y}(0)=x$ and $\gamma_{x\rightarrow y}(1)=y$). The most important property of a geodesic $\gamma(t)$ is that the time derivative $\dot{\gamma}(t)$ as a vector field, has 0 covariant derivative, i.e. $\nabla_{\dot{\gamma}(t)}\dot{\gamma}(t)=0$. This property boils down to a second order ODE in local coordinate systems, \[ \ddot{\gamma}_i(t)+\sum_{j,k}\Gamma_{jk}^i\left(\gamma(t)\right)\dot{\gamma}_j(t)\dot{\gamma}_k(t)=0 \] for $i\in[n]$, where $\Gamma_{jk}^i$ are the Christoffel symbols. Given a initial position $\gamma(0)$ and initial velocity $\dot{\gamma}(0)$, by the fundamental theorem of ODE, there exists a unique solution satisfying the geodesic equation. This is the principle we can use the ODE solver in GLA. \begin{definition}[Exponential map]\label{exp map} The exponential map $\mathrm{Exp}_x(v)$ is maps $v\in T_xM$ to $y\in M$ such that there exists a geodesic $\gamma$ with $\gamma(0)=x$, $\gamma(1)=y$ and $\gamma'(0)=v$. \end{definition} The exponential map can be thought of moving a point along a vector in manifold in the sense that the exponential map in $\mathbb{R}^n$ is nothing but $\mathrm{Exp}_x(v)=x+v$. The exponential map on sphere at $x$ with direction $v$ is $\mathrm{Exp}_x(v)=\cos(\norm{v})x+\sin(\norm{v})\frac{v}{\norm{v}}$. \begin{definition}[Parallel transport]\label{paralleltransport} The parallel transport $\Gamma_x^y$ is a map that transport $v\in T_xM$ to $\Gamma_x^y\in T_xM$ along $\gamma_{x\rightarrow y}$ such that the vector stays constant by satisfying a zero-acceleration condition. \end{definition} Next, we refer the definition of Riemannian gradient and divergence only in local coordinate systems that is used in this paper. \begin{definition}[Gradient and Divergence] In local coordinate system, the gradient of $f$ and the divergence of a vector field $V=\sum_iV_i\frac{\partial}{\partial x_i}$ on a Riemannian manifold is given by \[ \mathrm{grad} f=\sum_{i,j}g^{ij}\frac{\partial f}{\partial x_i}\frac{\partial}{\partial x_i} \ \ \ \text{and}\ \ \ \mathrm{div} V=\frac{1}{\sqrt{\abs{g}}}\sum_{i}\frac{\partial}{\partial x_i}\left(\sqrt{\abs{g}}V_i\right) \] where $g^{ij}$ is the $ij$-th entry of the inverse matrix $g^{-1}$ of $g$, $\abs{g}=\det(g_{ij})$. \end{definition} \begin{definition}[Lipschitz gradient]\label{Lipschitz} $f$ is of Lipschitz gradient if there exists a constant $L>0$ such that \[ \norm{\mathrm{grad} f(y)-\Gamma_x^y\mathrm{grad} f(x)}\le Ld(x,y) \ \ \text{for all}\ \ x,y\in M \] where $d(x,y)$ is the geodesic distance between $x$ and $y$, and $\Gamma_x^y$ is the parallel transport from $x$ to $y$, see Definition \ref{paralleltransport}. \end{definition} \subsection{Stochastic differential equations} Let $\{X_t\}_{t\ge 0}$ be a stochastic process in $\mathbb{R}^n$ and $B_t$ be the standard Brownian motion in $\mathbb{R}^n$. \\ \\ \textbf{Fokker-Planck Equation} For any stochastic differential equation of the form \[ dX_t=F(X_t,t)dt+\sigma(X_t,t)dB_t, \] the probability density of the SDE is given by the PDE \[ \frac{\partial\rho(x,t)}{\partial t}=-\sum_{i=1}^n\frac{\partial}{\partial x_i}\left(F_i(x,t)\rho(x,t)\right)+\sum_{i=1}^n\sum_{j=1}^n\frac{\partial^2}{\partial x_i\partial x_j}\left(A_{ij}(x,t)\rho(x,t)\right) \] where $A=\frac{1}{2}\sigma\sigma^{\top}$, i.e. $A_{ij}=\frac{1}{2}\sum_{k=1}^n\sigma_{ik}(x,t)\sigma_{jk}(x,t)$ \begin{comment} \textbf{Langevin dynamics} The stochastic process $\{X_t\}_{t\ge 0}$ evolves according to the DE \[ dX_t=-\nabla f(X_t)dt+\sqrt{2}dB_t. \] The probability density function $\rho_t$ evolves according to the Fokker-Planck equation: \[ \frac{\partial \rho(x,t)}{\partial t}=\nabla\cdot(\rho(x,t)\nabla f)+\Delta\rho(x,t)=\nabla\cdot\left(\rho(x,t)\nabla\log\frac{\rho(x,t)}{\nu}\right) \] that converges to the stationary distribution $\nu=e^{-f}$. \end{comment} \subsection{Distributions on manifold} Let $\rho$ and $\nu$ be probability distribution on $M$ that is absolutely continuous with respect to the Riemannian volume measure (denoted by $dx$) on $M$. \begin{definition}[KL divergence] The Kullback-Leibler (KL) divergence of $\rho$ with respect to $\nu$ is \[ H(\rho|\nu)=\int_M\rho(x)\log\frac{\rho(x)}{\nu(x)}dx. \] \end{definition} \begin{definition}[Wasserstein distance] The Wasserstein distance between $\mu$ and $\nu$ is defined to be \[ W_2(\mu,\nu)=\inf\{\sqrt{\mathbb{E}[d(X,Y)^2]}:\text{law}(X)=\mu,\text{law}(Y)=\nu\}. \] \end{definition} \begin{definition}[Talagrand inequality]\label{Tala The probability measure $\nu$ satisfies a Talagrand inequality with constant $\alpha>0$ if for all probability measure $\rho$, absolutely continuous with respect to $\nu$, with finite moments of order 2, \[ W_2(\rho,\nu)^2\le\frac{2}{\alpha}H(\rho|\nu) \] \end{definition} \begin{definition}[Log-Sobolev inequality] A probability measure $\nu$ on $M$ is called to satisfy the logarithmic Sobolev inequality (LSI) if there exists a constant $\alpha>0$ such that \[ \int_Mg^2\log g^2d\nu-\left(\int_Mg^2d\nu\right)\log\left(\int_Mg^2d\nu\right)\le\frac{2}{\alpha}\int_M\norm{\mathrm{grad} g}^2d\nu, \] for all smooth functions $g:M\rightarrow\mathbb{R}$ with $\int_Mg^2\le\infty$. The largest possible constant $\alpha$ is called the logarithmic Sobolev constant (LSC). \end{definition} \paragraph{Estimate of the log-Sobolev constant} It is well known that a compact manifold always satisfies log-Sobolev inequality \cite{LGross, OV, Rothaus81, Rothaus86, Wang1997, Wang1997x}. Practically we need a specific lower bound $\alpha_0$ of the log-Sobolev constant $\alpha$, so that we can choose stepsize $\epsilon\le\frac{\alpha_0\delta}{2CnL^2}\le\frac{\alpha\delta}{2CnL^2}$ for a given error bound $\delta$ for the KL divergence, see the discussion next to Theorem \ref{mtheoremintro}. The estimate of $\alpha_0$ is closely related to the Ricci curvature of $M$ and the first eigenvalue $\lambda_1$ of the Laplace-Beltrami operator on $M$, see the definitions in Appendix. For the case where $M$ is compact and the Ricci curvature is non-negative, the lower bound estimate for $\alpha$ is clear from the following theorem. \begin{theorem}[Theorem 7.3, \cite{MichelLedoux}]\label{logsobconst} Let $M$ be a compact Riemannian manifold with diameter $D$ and non-negative Ricci curvature. Then the log-Sobolev constant $\alpha$ satisfies $ \alpha\ge\frac{\lambda_1}{1+2D\sqrt{\lambda_1}}$. In particular, $ \alpha\ge\frac{\pi^2}{(1+2\pi)D^2}$. \end{theorem} The last inequality shows that we can choose a lower bound $\alpha_0=\frac{\pi^2}{(1+2\pi)D^2}$ that only depends on the diameter of $M$. For more results on estimate of the log-Sobolev constant, we refer to \cite{Wang1997, Wang1997x}. \section{Main Results}\label{MainResults \subsection{Technical Overview \paragraph{Wasserstein gradient flow.} The equivalence between Langevin dynamics and optimization in the space of densities is based on the result of \cite{JKO, Wibisono18} that the Langevin dynamics captures the gradient flow of the relative entropy functional in the space of densities with the Wasserstein metric. As a result, running the Langevin dynamics is equivalent to sampling from the stationary distribution of the Wasserstein gradient flow asymptotically. To minimize $\int_Mf(x)\rho(x)dx$ with respect to $\rho\in\mathcal{P}(M)$, we consider the entropy regularized functional of $\rho$ defined as follows, \[ \mathcal{L}(\rho)=\mathcal{F}(\rho)+H(\rho) \] where $\mathcal{F}(\rho)=\int_Mf(x)\rho(x)dx$ and $H(\rho)=\int_M\rho(x)\log \rho(x)dx$ that is the negative Shannon entropy $h(\rho)=-\int_M\rho(x)\log \rho(x)dx$. According to \cite{FSant}, the Wasserstein gradient flow associated with functional $\mathcal{L}$ is the Fokker-Planck equation \begin{equation}\label{FP00} \frac{\partial\rho(x,t)}{\partial t}=\mathrm{div}\left(\rho(x,t)\mathrm{grad} f(x)+\mathrm{grad} \rho(x,t)\right)=\mathrm{div}\left(\rho(x,t)\mathrm{grad} f(x)\right)+\Delta_M\rho(x,t), \end{equation} where $\mathrm{grad}$ and $\mathrm{div}$ are gradient and divergence in Riemannian manifold, and $\Delta_M$ is the Laplace-Beltrami operator generalizing the Euclidean Laplacian $\Delta$ to Riemannian manifold. More details can be found in Appendix. The stationary solution of equation (\ref{FP00}) is $e^{-f(x)}$ that minimizes the entropy regularized functional $\mathcal{L}(\rho)$, and then the optimization problem over the space of densities boils down to track the evolution of $\rho(x,t)$ that is defined by equation (\ref{FP00}). \paragraph{Coordinate-independent Langevin equation.} In order to implement the aforementioned evolution of $\rho(x,t)$ in Euclidean space, one can simulate the stochastic process $\{X_t\}_{t\ge 0}$ defined by the Langevin equation: $dX_t=-\nabla f(X_t)dt+\sqrt{2}dB_t$, where $B_t$ is the standard Brownian motion and $X_t$ has $\rho(x,t)$ as its density function. In contrast to the Euclidean case, we need a coordinate-independent formulation of Langevin equation, e.g. \cite{BKR}. This is derived by expanding the Fokker-Planck equation (\ref{FP00}) in a local coordinate system and is written in the following form: \begin{equation}\label{FP:local} dX_t=F(X_t)dt+\sqrt{2g^{-1}}dB_t \end{equation} where $F(X_t)$ is a vector with $i$'th component $F_i=-\sum_jg^{ij}\frac{\partial f}{\partial x_j}+\frac{1}{\sqrt{\abs{g}}}\sum_j\frac{\partial}{\partial x_j}\left(\sqrt{\abs{g}}g^{ij}\right)$ and $\abs{g}$ is the determinant of metric matrix $g_{ij}$. Note that this local form indicate the fact from Fokker-Planck equation that the process $\{X_t\}_{t\ge 0}$ is the negative gradient of $f$ followed by a manifold Brownian motion. The rate of convergence we are interested in is the classic Euler-Maryuyama discretization scheme in manifold setting, i.e. compute the vector in tangent space and project it onto the base manifold through exponential map. So the discretization error consists of two parts: one is from considering $\mathrm{grad} f(x_t)$ as constant in a neighborhood of $x_t$, and the other is from the approximation of a curved neighborhood of $x_t$ with the tangent space at $x_t$. The main task in the proofs of Theorem \ref{convergence:discrete} and \ref{convergence:constant curvature} is to bound the aforementioned two parts of errors and compare with the density evolving along continuous time Langevin equation. \subsection{Convergence Analysis} We state some assumptions before presenting main theorems. \begin{assumption}\label{ass1} $M$ is a closed manifold. \end{assumption} It means $M$ is compact and has no boundary, Definition \ref{closedM}. This assumption is essentially used to make the boundary integral on $\partial M$, i.e. $\int_{\partial M}\log\frac{\rho_t}{\nu}\langle\rho_t\mathrm{grad} f+\mathrm{grad}\rho_t,\vec{n}\rangle dx$ in the proof of Lemma \ref{lemma:continuous1}, to vanish, see Appendix. This assumption can be relaxed to open manifold by assuming the integral decreases fast as $x$ approaches the infinity. \begin{assumption}\label{ass2} $f(x)$ is differentiable on $M$. \end{assumption} An immediate consequence by combining Assumption \ref{ass1} and \ref{ass2} is that there exists a number $L>0$, such that the Riemannian gradient $\mathrm{grad} f$ of $f$ is $L$-Lipschitz (Definition \ref{Lipschitz}) due to the compactness of $M$. Another crucial property used in the proof is that the target distribution $e^{-f}$ satisfies the log-Sobolev inequality, and this can also be derived by compactness of $M$. Since the prerequisite of convergence of GLA is the convergence of the continuous time Langevin equation, we show the KL divergence between $\rho_t$ and $\nu$ converges along the continuous time Riemannian Langevin equation. The proof is completed by the following lemma showing that $H(\rho_t|\nu)$ decreases since $\frac{d}{dt}H(\rho_t|\nu)< 0$ for all $\rho_t\ne\nu$. Based on the analysis of the previous section, it suffices to track the evolution of $\rho_t$ according to the Fokker-Planck equation (\ref{FP00}). \begin{lemma}\label{lemma:continuous1} Suppose $\rho_t$ evolves following the Fokker-Planck equation (\ref{FP00}), then \[ \frac{d}{dt}H(\rho_t|\nu)=-\int_M\rho_t(x)\norm{\mathrm{grad}\log\frac{\rho_t(x)}{\nu(x)}}^2dx \] where $dx$ is the Riemannian volume element. \end{lemma} The proof is a straightforward calculation of the time derivative of $H(\rho_t|\nu)$, followed by the expression of $\frac{\partial \rho_t}{\partial t}$ in equation (\ref{FP00}), i.e. \begin{align} \frac{d}{dt}H(\rho_t|\nu)&=\int_M\frac{\partial\rho_t}{\partial t}\log\frac{\rho_t}{\nu}dx=\int_M\mathrm{div}(\rho_t\mathrm{grad} f+\mathrm{grad}\rho_t)\log\frac{\rho_t}{\nu}dx \\ &=-\int_M\rho_t\norm{\mathrm{grad} \log\frac{\rho_t}{\nu}}^2dx+\int_{\partial M}\log\frac{\rho_t}{\nu}\langle\rho_t\mathrm{grad} f+\mathrm{grad}\rho_t,\vec{n}\rangle dx \end{align} The result follows from integration by parts and the Assumption \ref{ass1}. Details are left in Appendix. Since $M$ is compact, there exists a constant $\alpha>0$ such that the log-Sobolev inequality (LSI) holds. So we can get the following convergence of KL divergence for continuous Langevin dynamics immediately. \begin{theorem}\label{convergence:continuous} Suppose $\nu$ satisfies LSI with constant $\alpha>0$. Then along the Riemannian Langevin equation, i.e. the SDE (\ref{FP:local}) in local coordinate systems, the density $\rho_t$ satisfies \[ H(\rho_t|\nu)\le e^{-2\alpha t}H(\rho_0|\nu). \] \end{theorem} \begin{comment} \begin{proof} By LSI, we have \[ \frac{d}{dt}H(\rho_t|\nu)\le-2\alpha H(\rho_t|\nu), \] multiplying both sides by $e^{\alpha t}$, \[ e^{2\alpha t}\frac{d}{dt}H(\rho_t|\nu)\le-2\alpha e^{2\alpha t}H(\rho_t|\nu) \] and then \[ e^{2\alpha t}\frac{d}{dt}H(\rho_t|\nu)+2\alpha e^{2\alpha t}H(\rho_t|\nu)=\frac{d}{dt}e^{2\alpha t}H(\rho_t|\nu)\le 0. \] Integrating for $0\le t\le s$, the result holds as \[ e^{2\alpha s}H(\rho_s|\nu)-H(\rho_0|\nu)=\int_0^s\frac{d}{dt}e^{2\alpha t}H(\rho_t|\nu)\le 0. \] Rearranging and renaming $s$ by $t$, we conclude \[ H(\rho_t|\nu)\le e^{-2\alpha t}H(\rho_t|\nu) \] \end{proof} \end{comment} The following theorem shows that the KL divergence $H(\rho_k|\nu)$ decreases geometrically along the GLA dynamics. \begin{theorem}\label{convergence:discrete} Suppose $M$ is a compact manifold without boundary and $R$ is the Riemann curvature, $\nu=e^{-f}$ a density on $M$ with $\alpha>0$ the log-Sobolev constant. Then there exists a global constant $K_2,K_3,K_4,C$, such that for any $x_0\sim\rho_0$ with $H(\rho_0|\nu)\le\infty$, the iterates $x_k\sim\rho_k$ of GLA with stepsize $\epsilon\le\min\{\frac{\alpha}{4L\sqrt{L^2+n^2K_2C}},\frac{2nL^2+2n^3K_2C+nK_3K_4}{2(nL^3+n^3K_2CL)},\frac{1}{2L},\frac{1}{2\alpha}\}$ satisfty \[ H(p_k|\nu)\le e^{-\alpha k\epsilon}H(p_0|\nu)+\frac{16\epsilon}{3\alpha}(2nL^2+2n^3K_2C+nK_3K_4) \] \end{theorem} The convergence of KL divergence implies the convergence of Wasserstein distance. \begin{proposition} For the closed manifold $M$ with a density $\nu=e^{-f(x)}$, the iterates $x_k\sim\rho_k$ of GLA with a properly chosen stepsize satisfy \[ W_2(\rho_k,\nu)^2\le\frac{2}{\alpha}e^{-\alpha k\epsilon}H(p_0|\nu)+\frac{32\epsilon}{3\alpha^2}(2nL^2+2n^3K_2C+nK_3K_4). \] \end{proposition} \begin{comment} \begin{proof} It is an immediate consequence from the convergence of KL divergence that the Wasserstein distance $W_2(\rho_k,\nu)$ converges rabidly since log-Sobolev inequality implies Talagrand inequality (\cite{Talagrand, OV}). Since $\nu$ satisfies log-Sobolev inequality, then we have \begin{align} W_2(\rho_k|\nu)^2&\le\frac{2}{\alpha}H(\rho_k|\nu) \\ &\le\frac{2}{\alpha}(e^{-\frac{k}{2}\alpha\epsilon}H(\rho_0|\nu)+\frac{C\epsilon nL^2}{\alpha}) \\ &=\frac{2}{\alpha}e^{-\frac{k}{2}\alpha\epsilon}H(\rho_0|\nu)+\frac{2C\epsilon nL^2}{\alpha^2} \end{align} and the proof completes. \end{proof} \end{comment} \begin{proof} It is an immediate consequence from the convergence of KL divergence that the Wasserstein distance $W_2(\rho_k,\nu)$ converges rabidly since log-Sobolev inequality implies Talagrand inequality (\cite{Talagrand, OV}). Since $\nu$ satisfies log-Sobolev inequality, then we have \begin{align} W_2(\rho_k|\nu)^2&\le\frac{2}{\alpha}H(\rho_k|\nu) \\ &\le\frac{2}{\alpha}\left(e^{-\alpha k\epsilon}H(p_0|\nu)+\frac{16\epsilon}{3\alpha}(2nL^2+2n^3K_2C+nK_3K_4)\right) \\ &=\frac{2}{\alpha}e^{-\alpha k\epsilon}H(p_0|\nu)+\frac{32\epsilon}{3\alpha^2}(2nL^2+2n^3K_2C+nK_3K_4) \end{align} and the proof completes. \end{proof} \begin{comment} \subsection{Estimate of the log-Sobolev constant} Practically we need a lower bound $\alpha_0$ of the log-Sobolev constant $\alpha$, so that we can choose $\epsilon\le\frac{\alpha_0\delta}{2CnL^2}\le\frac{\alpha\delta}{2CnL^2}$ for a given error bound $\delta$ for the KL divergence, see the discussion after Theorem \ref{mtheoremintro}. The estimate of $\alpha_0$ is closely related to the Ricci curvature of $M$ and the first eigenvalue of the Laplace-Beltrami operator on $M$, see Definition \ref{ricci} and \ref{eigenLaplacian} in Appendix. For the case where $M$ is compact and the Ricci curvature is non-negative, the lower bound estimate for $\alpha$ is clear from the following theorem. \begin{theorem}[Theorem 7.3, \cite{MichelLedoux}] Let $M$ be a compact Riemannian manifold with diameter $D$ and non-negative Ricci curvature. Then the log-Sobolev constant $\alpha$ satisfies \[ \alpha\ge\frac{\lambda_1}{1+2D\sqrt{\lambda_1}}. \] In particular, \[ \alpha\ge\frac{\pi^2}{(1+2\pi)D^2}. \] \end{theorem} The last inequality shows that we can choose a lower bound $\alpha_0=\frac{\pi^2}{(1+2\pi)D^2}$ that only depends on the diameter of $M$. \end{comment} \begin{comment} \subsection{Experiments} As mentioned before, for simplicity, we can implement GLA without using the exponential map where a geodesic ODE solver is required, especially for the case when $M$ is a submanifold of $\mathbb{R}^n$. In general, the retraction map from $T_xM$ to $M$ is used in optimization on Riemannian manifold \cite{Boumal1}, as a replacement of exponential map. In this section, we give experiments on sampling from distributions on the unit sphere in comparison of exponential map and orthogonal projection as a retraction in the geodesic step of GLA. \begin{definition}[Retraction] A retraction on a manifold $M$ is a smooth mapping $\mathrm{Retr}$ from the tangent bundle $TM$ to $M$ satisfying properties 1 and 2 below: Let $\mathrm{Retr}_x:T_xM\rightarrow M$ denote the restriction of $Retr$ to $T_xM$. \begin{enumerate} \item $\mathrm{Retr}_x(0)=x$, where $0$ is the zero vector in $T_xM$. \item The differential of $\mathrm{Retr}_x$ at $0$ is the identity map. \end{enumerate} \end{definition} Suppose $M$ is a submanifold of $\mathbb{R}^n$ with positive codimension. Denote $\mathrm{Proj}_{T_xM}$ the orthogonal projection to the tangent space at $x$, then the retraction can be defined as $\mathrm{Retr}_x(v)=\mathrm{Proj}_M(x+v)$. The GLA on a submanifold of $\mathbb{R}^n$ can be written as \begin{equation}\label{VGLA} x_{k+1}=\mathrm{Retr}_x\left(\mathrm{Proj}_{T_xM}(-\epsilon\nabla f(x_k)+\sqrt{2\epsilon}\xi_0)\right) \end{equation} If $M=S^{n-1}$ be the unit sphere in $\mathbb{R}^n$, then $\mathrm{Retr}_x(v)=\frac{x+v}{\norm{x+v}}$. The Figure \ref{Fig2} shows the effect when replacing GLA with algorithm (\ref{VGLA}). \begin{figure} \subfigure[$\mathrm{Exp}_x(v)=\cos(\norm{v})x+\sin(\norm{v})\frac{v}{\norm{v}}$]{\label{fig:a}\includegraphics[width=0.4\textwidth]{exp_1Tx3d_10ksamples}} \hspace{0.1\textwidth} \subfigure[$\mathrm{Retr}_x(v)=\frac{x+v}{\norm{x+v}}$]{\label{fig:b}\includegraphics[width=0.4\textwidth]{proj_1Tx3d_10ksamples}} \caption{$f(x)=x_1+x_2+x_3$, stepsize $\epsilon=0.2$ and iterations =10,000} \label{Fig2} \end{figure} \end{comment} \begin{comment} \begin{figure} \subfigure[Figure A]{\label{fig:a}\includegraphics[width=0.4\textwidth]{exp_1Tx3d}} \hspace{0.1\textwidth} \subfigure[Figure B]{\label{fig:b}\includegraphics[width=0.4\textwidth]{proj_1Tx3d}} \end{figure} \begin{figure} \subfigure[Figure A]{\label{fig:a}\includegraphics[width=0.4\textwidth]{exp_crossterms3d}} \hspace{0.1\textwidth} \subfigure[Figure B]{\label{fig:b}\includegraphics[width=0.4\textwidth]{proj_crossterms3d}} \end{figure} \end{comment} \begin{comment} \section{Discussion} In this section we denote $\rho_i(t,x)$ the density on $M_i$, or $\rho_i(t)$ for short if omitting the space variable $x$ would not cause any ambiguity. In this section we use the bolded text $ \vec{\rho}_{-i}:=\frac{\prod_{j=1}^d\rho_j}{\rho_i} $ to denote the product of densities from $\rho_1$ to $\rho_d$ except for $\rho_i$. Using densities on $M_1\times...\times M_d$, we can write the entropy regularized loss functional $\mathcal{L}$ as follows, \[ \mathcal{L}(\rho_1,...,\rho_d)=\int_{M_1\times...\times M_d}\ell(x_1,...,x_d)\rho_1dx_1...\rho_ddx_d+\sum_{i=1}^dH(\rho_i) \] where $dx_i=dx(M_i)$ is the volume element on $M_i$ and \[ H(\rho_i)=\int_{M_i}\rho_i\log\rho_idx_i. \] The regularized dynamics with the entropy regularizer is given by the system of PDEs, \begin{equation}\label{PDE} \begin{cases} \frac{\partial\rho_1(t)}{\partial t}&=\mathrm{div}_{x_1}\left(\rho_1(t)\mathrm{grad}_{x_1}F_1(\rho_{-1},x_1)+\mathrm{grad}_{x_1}\rho_1(t)\right) \\ &\vdots \\ \frac{\partial\rho_d(t)}{\partial t}&=\mathrm{div}_{x_d}\left(\rho_d(t)\mathrm{grad}_{x_d}F_d(\rho_{-d},x_d)+\mathrm{grad}_{x_d}\rho_d(t)\right) \end{cases} \end{equation} where \[ F_i(\rho_{-i},x_i)=\frac{\delta\mathcal{L}}{\delta\rho_i}(\rho_1,...,\rho_d)(x_i)=\int_{M_{-i}}\ell(x_i,x_{-i})\vec{\rho}_{-i}dx_{-i} \] These PDEs induce the interacting Langevin algorithm. For the two-agent zero-sum games, see \cite{DJMRB}. \begin{theorem}\label{multiagent:existence} Suppose $M_i$ for $i\in[d]$ are compact polish spaces with canonical Borel measures, $\ell$ is a continuous function on $M_1\times...\times M_d$. The fixed point problem \[ \rho_i(x_i)=\frac{1}{Z_{-i}}e^{-\int_{M_{-i}}\ell(x_i,x_{-i})d\mu_{-i}} \] has a unique solution $\vec{\nu}=(\nu_1,...,\nu_d)$ that is the unique Nash equilibrium of the game defined by $\mathcal{L}(\mu_1,...,\mu_d)$. \end{theorem} \begin{theorem}\label{multiagent:convergence} There exists only one stationary solution of (\ref{PDE}) that is one solution of the fixed point problem defined by \begin{equation}\label{fixed point} \rho_i(x_i)=\frac{1}{Z_{-i}}e^{-\int_{M_{-i}}\ell(x_i,x_{-i})\vec{\rho}_{-i}dx_{-i}}. \end{equation} \end{theorem} \end{comment}
{'timestamp': '2020-12-08T02:24:50', 'yymm': '2010', 'arxiv_id': '2010.05263', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05263'}
arxiv
\section{Introduction} Physics-based representation learning is a key emerging tool for analyzing high-dimensional nonlinear systems~\cite{Will20a,Brun20a}, and one with a long history in dynamical systems \cite{Crut87a}. Nonlinear systems often require additional tools beyond computer simulation to extract actionable insight from the complex behaviors they exhibit. There are two main aspects to physics-based representation learning. The first is \emph{dimensionality-reduction}: Learn a low-dimensional representation of a behavior---such as coherent structures in fluid flows~\cite{Holm12a,Peac13a}---that provide a more human-interpretable accounting for the full system's behavior. The second is \emph{generative modeling}: Provide a modeling alternative to numerical simulation of the equations of motion that can be applied directly to data. This is particularly helpful if the proper equations of motion are unknown. For high-dimensional systems the data-driven models are typically computationally less expensive than direct numerical simulation. For learning representations of high-dimensional nonlinear dynamics, several approaches have been introduced. \emph{Proper Orthogonal Decomposition} (POD)---rather similar to \emph{Principle Component Analysis} (PCA)---is a canonical method for fluid flows \cite{Holm12a,Rowl17a}. POD modes provide a low-dimensional latent representation that can give interpretable insights into a flow's large-scale organization. Flow equations of motion may also incorporate a set of POD modes, through Galerkin projection, giving a truncated set of ODEs as a generative model that is less expensive to simulate than the full Navier-Stokes PDE. Like PCA, the POD modes are linear latent representations. For that matter, PCA is equivalent to a linear autoencoder~\cite{Bald89a}. Representation linearity substantially restricts the complexity of flow structures that can be modeled appropriately. Addressing this, the Perron-Frobenius and Koopman operators recently gained popularity as nonlinear generalizations for spectral (modal) analysis of high-dimensional dynamical systems~\cite{Froy09a,Mezi13a,Klus19a}. As with nonlinear autoencoders, these operators' modes are typically used for nonlinear dimensionality-reduction. Similarly, the Koopman operator~\cite{Alex20a} and autoencoders~\cite{Hern18a} are now used for generative modeling which, in the dynamical systems setting, is a form of \emph{predictive forecasting}. As an aside, reservoir computing was shown to be effective for predictive modeling~\cite{Path18a}. It is somewhat analogous to Koopman operator approaches, as the system dynamics are learned in a higher-dimensional latent space. Success with operator-approximation methods turns on a fortuitous matching of their chosen (or inherent) function-basis dictionary and a system's emergent structures. The reality, though, is that spatially-extended nonlinear systems generate a diverse set of complicated organizations---vortices, target patterns, dislocations, and the like. In short, these emergent structures are not easily or naturally modeled in terms of known or numerically-approximated spatially-global function bases. Recent work employs nonlinear autoencoders~\cite{Lusc18a,Mard18a,Otto19a} as a means to bypass explicit dictionary choices. Issues still persist with these methods, however; finding the ``best'' finite-dimensional operator approximations for a given application remains an open problem. Local causal states are yet another tool for physics-based representation learning. They start from a markedly different conceptualization of latent space, however, with the promise of learning the more complex emergent patterns generated by nonlinear pattern-forming systems. Recall that reducing dimension through spectral decomposition implicitly assumes algebraic representations that are spatially global and spatially coherent. In contrast, local causal states are spatially-local latent representations that are learned at each point in spacetime. As such, they are better adapted to capture structures that self-organize from local interactions governing the dynamics---structures that consist of many localized or ``coherent'' substructures \cite{Rupe18a,Rupe19a}. Crucially, since the representations are learned locally, the latent space shares the same coordinate geometry as the observable spacetime fields. This adds, among other benefits, a helpful visual interpretability. The following formally connects local causal states and spacetime autoencoders and presents preliminary results for predictive forecasting using them. \section{Local Causal States} The local causal states are part of the \emph{computational mechanics} framework~\cite{Crut12a}, which learns nonparametric models of dynamical systems in an unsupervised fashion using the \emph{causal equivalence relation}: \begin{align*} \mathrm{p}_t \sim_\epsilon \mathrm{p}_{t^\prime} \iff \Pr(\mathrm{Future_t} | \mathrm{p}_t) = \Pr(\mathrm{Future_{t^\prime}} | \mathrm{p}_{t^\prime}) ~. \end{align*} The induced equivalence classes over pasts $\{\mathrm{p}_t\}$ are a system's \emph{causal states}---the unique minimal sufficient statistic of the past for optimally predicting the future. For spatiotemporal systems, \emph{lightcones} are local features that represent pasts and futures; see Fig.~\ref{lightcones}. Lightcones capture the history and propagation of local interactions in the system through space and time. A lightcone \emph{configuration} is an assignment of observable values to the lightcone templates shown in Fig.~\ref{lightcones}. Two past lightcone configurations $\ell^-_i$ and $\ell^-_j$ are causally equivalent if they have the same conditional distribution over future lightcones $\mathrm{L}^+$: \begin{align*} \ell^-_i \sim_\epsilon \ell^-_j \iff \Pr(\mathrm{L}^+ | \ell^-_i) = \Pr(\mathrm{L}^+ | \ell^-_j) ~. \end{align*} The resulting equivalence classes are the system's \emph{local causal states} \cite{Shal03a}. They are the unique minimal sufficient statistic of past lightcones for optimally predicting future lightcones. \begin{figure}[ht!] \centering \includegraphics[width=0.5 \textwidth]{figure_01} \caption{Lightcones: past lightcone $\mathtt{L}^-(r_0, t_0)$ (red) and future lightcone $\mathtt{L}^+(r_0, t_0)$ (blue) shown for spacetime point $X(r_0, t_0)$ (green) for a system with radius $\radius=1$ interactions, such as the map lattice example shown below. } \label{lightcones} \end{figure} \subsection{Encoding} The lightcone equivalence relation can be recast as a function that generates the causal equivalence classes---the \emph{$\epsilon$-function} $\epsilon : \ell^- \mapsto \xi$ maps from past lightcone configurations $\ell^-$ to local causal states $\xi$. This local mapping from observables to their corresponding latent local causal state representation is central to using and interpreting our method. Specifically, $\epsilon\bigr(\ell^-)$ is applied in parallel to all points $(\vec{r}, t)$ in a spacetime field $X$, mapping the entire field to its associated \emph{local causal state field} $S = \epsilon(X)$. Every feature $X(\vec{r},t)$ is mapped to its latent variable (local causal state) via its past lightcone $\xi = S(\vec{r}, t) = \epsilon\bigr(\ell^-(\vec{r}, t)\bigl)$. One result is that the global latent spacetime field $S$ maintains $X$'s coordinate geometry such that $S(\vec{r}, t)$ is the local latent variable corresponding to the local observable $X(\vec{r}, t)$. (This is markedly unlike neural network autoencoders.) The shared geometry of the observable space $X$ and the latent space $S$ facilitates extracting physical features of $X$ from special (e.g., algebraic) properties in the corresponding spacetime region in $S$. For real-valued systems, such as the map lattice analyzed shortly, local causal state inference requires a discretization to empirically estimate $\Pr(\mathrm{L}^+ | \ell^-)$~\cite{Goer12a}. Rather than discretize observable space, we discretize in the lightcone feature space using K-Means to cluster lightcones using distance metric: \begin{align} \mathrm{D}_{\mathrm{lc}}(\mathbf{a}, \mathbf{b}) \!\equiv\! \sqrt{(a_1 \!-\! b_1)^2 + \ldots + \mathrm{e}^{-\tau d(n)}(a_n \!-\! b_n)^2} , \label{lcdist} \end{align} where $\mathbf{a}$ and $\mathbf{b}$ are flattened lightcone vectors, $d(n)$ is the temporal depth of the lightcone vector at index $n$, and $\tau$ is the temporal decay rate ($1/\tau$ can be thought of as a coherence time). Two past lightcones are considered $\gamma^-$-equivalent if they are placed into the same cluster $C^-$ by the distance-based clustering: \begin{align}\gamma^-(\ell^-_i) \!=\! \gamma^-(\ell^-_j) \!\iff\! \ell^-_i \!\in C^- \; \mathrm{and} \; \ell^-_j \!\in C^- ~. \end{align} Similarly for future lightcones. This allows us to build empirical distributions over lightcone-clusters from simple counting. Two past lightcone clusters are considered $\psi$-equivalent if they have (approximately) the same empirical predictive distributions: \begin{align} \psi(C^-_i) = \psi(C^-_j) \! \iff \! \Pr(C^+ | C^-_i) \! \approx\! \Pr(C^+ | C^-_j) ~. \end{align} This approximates the $\epsilon$-function as: \begin{align} \epsilon(\ell^-) \approx \psi\bigl( \gamma^-(\ell^-) \bigr) ~. \end{align} \subsection{Decoding} Previously, when performing coherent-structure segmentation the $\epsilon$-function \emph{encoded} observable spacetime fields $X$ to a corresponding latent local causal state field $S$~\cite{Rupe18a,Rupe19a}. Such dimensionality-reduction identifies coherent structures pointwise in observable spacetime fields. We now introduce, for the first time, the $\epsilon^{-1}$-function---a stochastic \emph{decoding} that maps from latent spacetime fields $S$ to \emph{reconstructed} observable fields $\overline{X}$. Each local causal state $\ensuremath{\xi}\xspace$ in $S$ is defined by its predictive distribution $\Pr(\mathtt{L}^+ | \ensuremath{\xi}\xspace)$, since every past lightcone configuration $\ell^-_i$ in $\ensuremath{\xi}\xspace$ has, by definition, the same predictive distribution: $\Pr(\mathtt{L}^+ | \ell^-_i) = \Pr(\mathtt{L}^+ | \ensuremath{\xi}\xspace)$, for all $\ell^-_i \in \ensuremath{\xi}\xspace$. The decoding $\overline{X} = \epsilon^{-1}(S)$ is performed by sampling the distributions $\Pr(\mathtt{L}^+ | \ensuremath{\xi}\xspace)$ for each $\ensuremath{\xi}\xspace$ in $S$ as follows. For each spacetime coordinate $\point$: \begin{enumerate} \setlength{\topsep}{-2pt} \setlength{\itemsep}{-2pt} \setlength{\itemindent}{4pt} \item Retrieve the local causal state $\ensuremath{\xi}\xspace = S\point$; \item Sample a future cluster $C^+$ from $\Pr(C^+ | \ensuremath{\xi}\xspace)$; \item Retrieve the centroid $\overline{\ell^+}$ of $C^+$; and then \item Place $\overline{\ell^+}$ in $\overline{X}$, with base at $\point$. \end{enumerate} Since we use K-Means to cluster both past and future lightcones, we take the centroid $\overline{\ell^+}$ as a representative real-valued future lightcone for cluster $C^+$. Due to the spacetime extent of nontrivial future lightcones, each point $\overline{X}\point \in \overline{X}$ makes predictions from several local causal states. In fact, for future-lightcone depth $h^+$ a prediction will be made from each point in its $h^+$-depth past lightcone. The ultimate prediction for $\overline{X}\point$ averages these predictions, with the same time-exponential weighting used in the lightcone metric of Eq.~(\ref{lcdist}). That is, predictions made further out in time are discounted exponentially compared to more recent predictions. Combining the $\epsilon$-function encoding with the $\epsilon^{-1}$-function decoding, the local causal states form a \emph{spacetime autoencoder}. As shown in the top portion of Fig.~\ref{lcs-autoencoder}, the $\epsilon$-function encodes an observable spacetime field $X$ to the compressed latent field $S$ and $\epsilon^{-1}$ decodes to a reconstructed observable field $\overline{X} = \epsilon^{-1}(S)$. Said another way, the identity $I \approx \epsilon \circ \epsilon^{-1}$ is learned through the causal state bottleneck $S$. \begin{figure*}[ht!] \centering \includegraphics[width=1.0 \textwidth]{figure_02} \caption{Spacetime local causal state autoencoder: (Top-left) Observable spacetime field $X[0,T]$ of the circle map lattice used for training. A $250$-site portion of the $20,000$ spatial sites are shown (horizontal), which are evolved for an initial $200$ time steps (vertical) for training. (Top-middle) Encoded latent local causal state field $S=\epsilon\bigl(X[0,T]\bigr)$. Each unique color represents a unique local causal state. This compressed latent space provides a compressed representation of $X[0,T]$ for dimensionality-reduction. (Top-right) Reconstructed observable field $\overline{X} = \epsilon^{-1}(S)$, decoded from $S$. (Bottom-middle) Forecasted local causal state field, evolved forward in time after inference, starting at $T=199$, using $\widetilde{S} = \Phi(S)$ as described above. (Bottom-right) Forecasted observable field $\widetilde{\overline{X}}$, decoded from the evolved local causal state field $\widetilde{\overline{X}} = \epsilon^{-1}(\widetilde{S})$. (Bottom-left) Ground-truth observable field $X[T,300]$, evolved using the circle map lattice equation of motion. } \label{lcs-autoencoder} \end{figure*} There are several points to emphasize. First, unlike neural network autoencoders, the local causal states are nonparametric models. And so, rather than using the encoding and decoding together to train parameters as in neural network autoencoders, the $\epsilon$-map and its inverse are learned directly by approximating the local causal equivalence relation from data. Second, as already noted, a crucial distinction is that the $\epsilon$-map encoding is done locally so that the latent space and observable space share spacetime coordinate geometry. The latent space of neural network autoencoders, in contrast, does not share geometry with its inputs due to how their bottleneck is created. For local causal states approximated from real-valued spacetime data, the bottleneck comes from having a finite number of latent local causal states and the latter are determined by the inherent structural dynamics. However, this alone is a rather weak notion of autoencoder. Last, along these lines, accounting for temporal evolution is critical for capturing pattern and structure that is spontaneously generated by complex spatiotemporal systems. Accounting for dynamics leads to a more powerful view of a causal state autoencoder. \subsection{Latent Space Dynamics} In fact, a stochastic dynamic can be defined over the local causal states. This combined with $\epsilon^{-1}$ decoding gives spacetime forecasting: infer the local causal states and their dynamics up to the present time, evolve the states forward in time, then decode to a forecasted observable field. This view of the local causal states as \emph{predictive spacetime autoencoders} is much more useful than the weak notion above. It synthesizes the two main aspects of representation learning in physics---dimensionality-reduction and generative modeling. For nonlinear dynamical systems the generative modeling of interest is predictive forecasting, which generates sequential states and captures how they are correlated and organized in time. The local causal state field exhibits \emph{Markov shielding} \cite{Shal03a}. The $\epsilon$-function uniquely determines a local causal state $\ensuremath{\xi}\xspace = S\point$ from a full past lightcone $\ell^-\point$ of observables. If the local causal states are known for each point in $\ell^-\point$, only the states in the immediately preceding time step are required to determine $\ensuremath{\xi}\xspace$. That is, $S\point$ is independent of the local causal states in $\ell^-\point$, given the local causal states in its depth-$1$ past lightcone---the \emph{local neighborhood} $\neighborhood \bigl(S(\site, t-1)\bigr)$ of $S(\site, t-1)$. Markov shielding was derived in the setting of stochastic field theories, where the observable field $X$ is \emph{not} from a deterministic dynamical system. The stochasticity inherent in the system, along with Markov shielding, implies the temporal dynamics over the local causal states is a \emph{stochastic cellular automaton} (SCA), where $S\point$ is given by a stochastic function $\phi$ of the local neighborhood $\neighborhood\bigl(S(\site, t-1) \bigr)$. While our ultimate interests lie in deterministic systems (e.g., those governed by partial differential equations), the local causal state dynamics is still an SCA in this case. For systems with finite-range local interactions, which \emph{define} a system's lightcones, a site value $X\point$ in $X$ is uniquely determined by the past lightcone of $X\point$. In fact, for deterministic, non-delay dynamics $X\point$ is uniquely determined by $\neighborhood \bigl(X(\site, t-1) \bigr)$. In this way, Markov shielding in the local causal states is inherited from the dynamics of the observable field. Since the local causal states are compressed (local) representations, the local causal states alone are not sufficient for deterministic evolution and, in general, the information loss in the bottleneck implies the dynamic $\Phi$ over the local causal states must be stochastic. Note that this argument is agnostic to the functional form of the observable dynamics (i.e., the equations of motion). In this way, the local causal states and their SCA dynamic $\Phi$ provide a universal probabilistic model for spatially-extended dynamical systems. Consider a finite set $\ensuremath{\mathbf{\Xi}}\xspace$ of symbols (e.g., local causal state labels). A radius-$\radius$ \emph{deterministic} cellular automata (CA) over $\ensuremath{\mathbf{\Xi}}\xspace$ is specified by a \emph{local update rule} $\phi: \neighborhood \mapsto \ensuremath{\xi}\xspace$ that is a deterministic function of radius-$\radius$ neighborhoods $\neighborhood$. In $1+1$-dimensions (one space, one time), the neighborhoods are tuples of symbols from $\ensuremath{\mathbf{\Xi}}\xspace$. For example, in a radius-1 CA in $1+1$-dimensions: $\ensuremath{\xi}\xspace(\site, t+1) = \phi \bigl(\neighborhood (\ensuremath{\xi}\xspace\point) \bigr) = \phi \bigl(\ensuremath{\xi}\xspace(\site-1, t), \ensuremath{\xi}\xspace(\site, t) \ensuremath{\xi}\xspace(\site +1, t) \bigr)$. The global CA dynamic $\Phi$, that evolves spatial configurations over a time step, applies the local update $\phi$ synchronously and in parallel across a configuration. For the more general stochastic CAs, the local update $\phi$ is still a function of local neighborhoods $\neighborhood$. However, instead of outputting a single symbol $\ensuremath{\xi}\xspace$, it outputs a \emph{probability mass function} (PMF) over symbols from $\ensuremath{\mathbf{\Xi}}\xspace$. Deterministic CAs then are the special case when the PMFs assign unity mass to and only one symbol. For a given observable spacetime field $X$, once the associated local causal state field $S = \epsilon(X)$ has been inferred, the state dynamic $\Phi$ can be estimated from $S$, again by simple counting. Empty histograms are initialized for all possible neighborhoods $\neighborhood$ of local causal states. For a particular neighborhood $\neighborhood_i$ found at $S\point$, the histogram of $\phi(\neighborhood_i)$ is incremented at $\ensuremath{\xi}\xspace$ for $\ensuremath{\xi}\xspace = S(\site, t+1)$. Since real-valued systems require approximation schemes and models are always inferred from finite data, using $\Phi$ estimated in this way to evolve the local causal states forward in time may yield a neighborhood $\neighborhood$ not seen in the original inferred field $S$. The local dynamic $\phi$ outputs an empty histogram in this case. In practice, to circumvent this issue we keep and update a separate PMF over local causal states that is the spatial distribution over the local causal states. At each $t$ we estimate a histogram over the local causal states according to the spatial configuration $S(t)$ of the local causal state field. If an empty histogram is encountered during the evolution $S(t+1) = \Phi \bigl( S(t) \bigr)$, a local causal state for that point is chosen from the spatial PMF instead. This heuristic leaves room for variation, and we use a running-estimate spatial distribution since the distribution over local causal states generally is not temporally stationary. \section{Forecasting Spacetime Fields} To demonstrate that local causal states are spacetime autoencoders, along with their predictive forecasting, the following presents preliminary results for a nonlinear map lattice system based on the \emph{circle map}. While the choice is somewhat arbitrary, we selected the circle map lattice due to the complexity of the self-organized patterns and structures it generates. Map lattices are also markedly simpler to simulate than PDEs, such as the Kuramoto-Sivashinsky equation popular in data-driven forecasting explorations~\cite{Path18a,Otto19a}, that require elaborate numerical integration schemes. A one-dimensional \emph{map lattice} \cite{Crut87b} is a spatially-extended dynamical system that evolves configurations on a discrete spatial lattice $\mathbb{Z}$ in discrete time steps according to the local dynamics: \begin{align} \begin{split} x(\site, t+1) & = (1 - \alpha)f\bigl(x\point \bigr) + \\ &\frac{\alpha}{2} \bigl[f\bigl(x(\site+1, t) \bigr) + f\bigl(x(\site-1, t) \bigr) \bigr] ~, \end{split} \label{eqn:map-lattice} \end{align} where $\site$ is the spatial index, $t$ is the time index, $\alpha$ is the coupling strength, and $f$ is an iterated map of the unit interval: $x(t+1) = f\bigl(x(t)\bigr), ~ x \in [0,1]$. We use the circle map: \begin{align*} f(x) = x + \omega - \frac{K}{2\pi} \sin(2 \pi x) \; \mathrm{mod} \; 1 ~, \end{align*} where $\omega$ is a phase shift and $K$ is the strength of the nonlinearity. Following \cite{Grav18a}, Fig.~\ref{lcs-autoencoder} uses $\omega = 0.5$, $K = 1.0$, and $\alpha = 1.0$. The map lattice's complex behaviors seen there in the observable spacetime field $X$ in the left panels arise from two competing background \emph{domains}. One is spatial period-$2$ (vertical stripes) and the other is temporal period-$2$ (horizontal stripes). Interfaces between these domains (also know as \emph{dislocations} in the statistical mechanics literature) diffuse through space over time and sometimes pairwise annihilate upon collision. Due to pairwise annihilation, the macroscopic behavior of domains and the interactions of their interfaces is not stationary in time. When evolved from random initial conditions, as done here, there are initially many domain interfaces that quickly annihilate. These pairwise interactions decrease over time until the system's spacetime behavior is mostly comprised of domain regions. We are interested here in intermediate times that have a balance between dislocation dynamics and (meta-)stable domain regions. To this end, we let the map lattice evolve for $300$ time steps before starting local causal state inference. Note that time $t=0$ in Fig.~\ref{lcs-autoencoder} starts after this initial transient time. We use a lattice size of $N=20,000$ (only a portion of which is shown in Fig.~\ref{lcs-autoencoder}) and periodic boundary conditions for our map lattice. After the initial $300$-step transient time, the map lattice is evolved for another $T=200$ time steps to produce the training observable field $X[0,T]$ that is used for local causal state inference. For inference we use past lightcone depth $h^- = 6$, future lightcone depth $h^+ = 1$, and propagation speed $c = 1$ (determined by the radius $\radius = 1$ local interactions of the map lattice). In the lightcone clustering step, i.e. $\gamma$-equivalence, we use $K = 10$ for past lightcone clustering and $K = 40$ for future lightcone clustering. For $\psi$-equivalence, we use hierarchical agglomerative clustering, using a $\chi^2$ test with $\alpha = 0.05$ for distribution comparison. After inference, the training observable field $X[0,T]$ is encoded using the approximated $\epsilon$-map, $\epsilon(\ell^-) \approx \psi\bigl( \gamma^-(\ell^-) \bigr)$, to produce the associated local causal state field $S = \epsilon \bigl(X[0,T]\bigr)$, shown in the top-middle panel of Fig.~\ref{lcs-autoencoder}. Each unique local causal state is assigned an arbitrary integer label during inference, and these integer labels are then assigned arbitrary colors for the latent field visualizations in Fig.~\ref{lcs-autoencoder}. Each unique color seen in $S$ identifies a unique local causal state at that point. As the two domains in $X$ are period-$2$, each is described by two local causal states in $S = \epsilon(X)$. The result is that only four local causal states capture the majority of the observed spacetime behavior, with additional local causal states capturing particular interactions at the domain interfaces. From the dimensionality-reduction perspective, these are the structures that one would like to capture and in terms of which we would then re-express the system's evolution. Note that at the ``microscopic'' level, in terms of the full spatial lattice, the dynamics of the system are deterministic, following Eq.~(\ref{eqn:map-lattice}), while the evolution of the reduced ``macroscopic'' description is probabilistic, following the stochastic diffusion and annihilation of domain interfaces. Recall that the $\epsilon^{-1}$-function is also learned during inference, and it is then used to create the reconstruction $\overline{X} = \epsilon^{-1}(S)$ of $X[0,T]$, shown in the top-right panel of Fig.~\ref{lcs-autoencoder}. The reconstructed observable field $\overline{X}$ qualitatively reproduces the macroscopic behavior observed in $X[0,T]$, even though the microscopic details are noisy due to the stochasticity of the decoding. Given that the latent space $S$ is comprised of just $10$ local causal states, the reconstructed observable field $\overline{X} = \epsilon^{-1}(S)$ is surprisingly faithful to the original observable field $X[0,T]$. Once the local causal state field $S$ has been inferred, the stochastic latent space dynamic $\Phi$ can be estimated, as described above. Using the estimated dynamic, the latent space is evolved forward in time to produce a forecasted local causal state field $\widetilde{S} = \Phi(S)$. In the bottom-middle of Fig.~\ref{lcs-autoencoder} the local causal state field is predicted forward in time another $100$ time steps. Note that in the original inferred latent space field $S = \epsilon\bigl(X[0,T]\bigr)$ no local causal states are placed in regions that do not have full past or future lightcones of the chosen depths. These points are known collectively as the \emph{margin} of the latent space field $S$. Due to the periodic boundaries in space, there are only time margins. Margin points are assigned a unique label in $S$, rather than just being omitted, so that $S$ is the same shape as the observable field it is trained on. Since we use future lightcone depth $h^+ = 1$ here, there are no local causal states assigned at time step $199$. Thus, as can be seen in the bottom panels of Fig.~\ref{lcs-autoencoder}, the forecast starts at $T = 199$. There are several points to note for the forecasted local causal state field $\widetilde{S} = \Phi(S)$ in the bottom-middle panel. We again emphasize that the following analysis is enabled and enhanced by the visual interpretability afforded by the shared coordinate geometry of the observable and latent spaces. From visual inspection, we can see that the most stable and well-predicted regions are the periodic domains. By relying on the previous-time spatial distribution when null PMFs are encountered applying $\Phi$, the domain regions are stable to incorrect predictions, to some degree. We can see this, for instance, in the predicted domain region around site $r = 140$. There is noise present in the prediction of this domain, as there are local causal states present other than the two states that identify this domain in the same region in the inferred field $S = \epsilon \bigl(X[0,T]\bigr)$ just before the forecast starts. The domain persists in the prediction, despite this noise. However, resilience to incorrect predictions does not hold generally. As can be seen, for instance on the right-hand side of $\widetilde{S}$ after $t \approx 220$, prediction errors can sometimes cause cascading failures in the forecast, which typically travel around the propagation speed of $c = 1$. Once a cascading failure starts, it is generally not recoverable due to instability in the inferred dynamic and the forecast breaks down. Again using the $\epsilon^{-1}$-function, we decode $\widetilde{S}$ to produce a forecasted observable field $\widetilde{\overline{X}} = \epsilon^{-1}(\widetilde{S})$. As with the reconstructed field $\overline{X}$, the small-scale details are noisy, but the large-scale behavior predicted by the local causal state field $\widetilde{S}$ is reproduced in the observable forecast. Comparing to the ground-truth observable field $X[T, 300]$, provided by evolving the map lattice forward another $100$ time steps after creating the training field, we see that the domain regions are forecasted well. Several interfaces remain stable for the full duration without breaking down into a cascading failure, such as those near $r = 140$. Ideally, the forecast should not produce the kind of cascading failures seen in $\widetilde{S}$ and $\widetilde{\overline{X}}$. These are likely due to empty PMFs encountered when applying the estimated latent space dynamic $\Phi$. Clearly, there is room for improvement in the algorithms, heuristics, and training protocols. These preliminary results nonetheless demonstrate the two-fold benefit of the local causal states for physics-based representation learning: dimensionality-reduction and generative modeling---predictive forecasting, in this case. However the method is improved, we suspect there will ultimately be a trade-off between these two aspects of local causal states. Allowing for more local causal states to be learned during inference (the hyperparameter choice of $K$ in K-Means cluster over past lightcones sets an upper bound to the possible number of states that can be learned) will generally increase forecasting performance, but at the same time detract from with visual interpretability of the latent space for dimensionality-reduction. Python source code and a Jupiter notebook that produces the results shown in Fig.~\ref{lcs-autoencoder} is available at \url{https://github.com/adamrupe/spacetime_autoencoders}. \paragraph*{Acknowledgments} AR and JPC acknowledge Intel's support for the IPCC at UC Davis and thank the Telluride Science Research Center for its hospitality during visits. This research is based upon work supported by, or in part by, the U. S. Army Research Laboratory and the U. S. Army Research Office under contract W911NF-18-1-0028. Part of this research was performed while AR was visiting the Institute for Pure and Applied Mathematics (IPAM), which is supported by the National Science Foundation (Grant No. DMS-1440415). \bibliographystyle{aaai}
{'timestamp': '2020-10-13T02:28:36', 'yymm': '2010', 'arxiv_id': '2010.05451', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05451'}
arxiv
\section{Introduction} Hierarchical clustering is one of the widely used clustering methods~\citep{jainDataClusteringReview1999,gilpin2013formalizing,cohen2019hierarchical}. Given a set of data points, the goal of hierarchical clustering is not to find a single partitioning of the data, but a hierarchy of subclusters in a dendrogram. Because its clustering output of a dendrogram is easy to interpret, hierarchical clustering has been used in a wide range of applications, e.g., social networks analysis~\citep{rajaramanMiningMassiveDatasets2011}, bioinformatics~\citep{diezpalacioNovelBrainPartition2015}, text classification~\citep{Malik2010,Zhao2005} and financial market analysis~\citep{tumminelloCorrelationHierarchiesNetworks2010}. The most widely used hierarchical clustering approach is agglomerative hierarchical clustering (AHC)~\citep{jainDataClusteringReview1999}. It starts with subclusters of individual points, and then iteratively merges two most similar subclusters, based on a \textit{linkage function} which measures the similarity of two subclusters, until all points belong to a single cluster. AHC has been studied in the theoretical community and used by practitioners~\citep{wu2009towards,heller2005bayesian,Dasgupta2016CostFunction,cohen2019hierarchical}. The linkage function used in an AHC relies on a distance (or similarity) measure. Many distanced-based linkage functions have been proposed for hierarchical clustering, such as complete linkage~\citep{kingStepwiseClusteringProcedures1967} and average linkage~\citep{sokal1958u}. In addition, in order to capture complex structures in the data, the graph-structural agglomerative clustering algorithms such as GDL~\citep{zhang2012graph} and PIC~\citep{zhang2013agglomerative} have used a linkage function based on a $k$-nearest-neighbour graph. This research is motivated by the current state of two partitioning clustering research fronts. First, the impact of varied densities of clusters on density-based partitioning clustering algorithms has been well studied (e.g. \cite{ankerst1999optics,ertoz2003finding,campello2013density,zhu2016density,ting2019lowest,qin2019nearest}). But its impact on the traditional AHC algorithms (T-AHC) has not been investigated in the literature thus far. We think its impact has been overlooked because the dendrogram is said to have a `complete' set of subclusters, assuming that some of these subclusters will be a good match for the true clusters. Yet, we show that this `complete' set of subclusters often does not include ones which are a good match to the ground truth clusters in a given dataset. Our investigation uncovers a specific bias of T-AHC: using the distance-based linkage function, T-AHC tends to merge high-density subclusters first, before low-density subclusters in the merging process. While there is a hint of this bias in the literature \cite{klemela2009smoothing}, no analysis of its cause has been conducted, as far as we know. Another possible reason for its lack of attention in this matter is that this bias only becomes an issue if clusters are not well separated (see our definition in Section \ref{why}.) In many real-world datasets in which clusters are not well separated, we have observed that this bias often leads to a dendrogram of poor quality. The impact of the bias on T-AHC is most revealing in a dataset, having clusters of varied densities and not well separated, as shown in Figure \ref{fig:hard2}. Clusters extracted from this dendrogram either lost many of their (true) members or they have (false) members of other clusters or both. \begin{figure} [!htb] \centering \begin{subfigure}[b]{0.43\textwidth} \centering \includegraphics[width=\textwidth]{figure/Image/hard2.png} \caption{Dataset: 4 clusters of different densities} \label{fig:hard21} \end{subfigure} \begin{subfigure}[b]{0.43\textwidth} \centering \includegraphics[width=\textwidth]{figure/Image/hard3.png} \caption{Dendrogram produced by T-AHC} \label{fig:hard122} \end{subfigure} \caption{A dendrogram produced by T-AHC with the distance-based single-linkage function on a dataset with four clusters of varied densities. The colours at the bottom of the dendrogram correspond to the true cluster labels of all points shown in Figure (a). The arrow in Figure (b) indicates the subtrees containing points from different clusters.} \label{fig:hard2} \end{figure} Second, in the context of density-based partitioning clustering, the root cause of the bias has been established, i.e., the use of data-independent kernel/distance \cite{ertoz2003finding,ting2019lowest,qin2019nearest}. In addition, in the context of kernel/spectral (partitioning) clustering, the density bias has been recognised to be an issue \cite{huang2015density,8166757}. Stop short of declaring that the use of data-independent kernel is the root cause, a kernel which adapts to local density to replace a data-independent kernel has been proposed as a remedy, e.g., Adaptive Gaussian Kernel \cite{zelnik2005self}. To the best of our knowledge, using the data-dependent kernel function to reduce the density bias in hierarchical clustering is still unexplored. Here, we contend that the same root cause yields the bias in T-AHC. We then provide the formal analysis and explanation as to why a well-defined data-dependent kernel called Isolation Kernel \cite{ting2018IsolationKernel,qin2019nearest} is an effective remedy. The contributions of this paper are summarised as follows: \begin{enumerate} \item Providing the formal condition under which an AHC, that employs an existing kernel/distance, does not extract clusters of a dataset effectively. \item Introducing a new concept called \textbf{entanglement} as a way to explain the merging process that leads to a poor quality dendrogram. Two indicators, i.e., the number of entanglements and the average entanglement level, are shown to be highly correlated to an objective measure of goodness of dendrogram called dendrogram purity. \item Identifying the root cause of a density bias of T-AHC. The bias merges points in dense region first, before merging points in the sparse region; and its root cause is due to the use of data-independent distance/kernel. Though this analysis is mainly based on T-AHC, the same root cause also applies to existing AHC algorithms as well. \item Proposing a generic approach to improve existing distance-based AHC algorithms: simply replace the distance function with a data-dependent kernel, without modifying the algorithms. We also provide the reason why a data-dependent kernel can significantly reduce the above-mentioned bias; \item Presenting the empirical evaluation results using four algorithms, i.e., T-AHC~\citep{jainDataClusteringReview1999}, HDBSCAN~\citep{campello2013density}, GDL~\citep{zhang2012graph} and PHA~\citep{lu2013pha} that: (i) kernels produce better clustering results than distance, and (ii) a recently introduced Isolation Kernel \citep{ting2018IsolationKernel,qin2019nearest} performs better than Gaussian Kernel and Adaptive Gaussian Kernel \citep{zelnik2005self}. \end{enumerate} Our approach is distinguished from those used in existing AHC algorithms in two ways: \begin{itemize} \item Rather than creating new linkage functions that still employ distance measure \citep{ackerman2016characterization,pmlr19}, we propose to use a data-dependent kernel to replace the distance function in existing linkage functions. \item The methodology is generic which can be applied to different hierarchical clustering algorithms. Many existing linkage functions are tailored made for a specific algorithm. We show that our approach can be applied to four existing methods, T-AHC, HDBSCAN \citep{campello2013density}, GDL~\citep{zhang2012graph} and PHA~\citep{lu2013pha}, even though each algorithm has its own specific linkage function(s). \end{itemize} The rest of the paper is organised as follows. We first describe the related work on AHC and kernels in Section 2. Then we define the Kernel-based AHC and the condition under which it fails to identify clusters in Section 3. Section 4 investigates the effectiveness of the use of a data-dependent kernel in addressing the density bias in Kernel-based AHC. An extensive empirical evaluation is reported in Section 5, followed by the conclusions in the last section. \section{Related Work}~\label{sec:relatedwork} \subsection{Agglomerative Hierarchical Clustering} Hierarchical clustering can be categorised into agglomerative (bottom-up) and divisive (top-down) methods~\citep{murtagh1983survey}, depending on the direction in which the hierarchy in a dendrogram is created. Many research focuses on improving the hierarchical clustering on algorithm-level~\citep{heller2005bayesian,krishnamurthy2012efficient} and understanding hierarchical clustering~\citep{wu2009towards,Dasgupta2016CostFunction,cohen2019hierarchical}. In this paper, we focus on AHC. An agglomerative method needs two functions: a distance function measures the dissimilarity of two points; and the linkage function $h(C_i,C_j)$ measures the dissimilarity of subclusters $C_i$ and $C_j$~\citep{pmlr19}. Treating individual points in a given dataset as subclusters, it iteratively merges two most similar subclusters based on $h(\cdot,\cdot)$ at each step to form a tree-based structure (dendrogram) until a single cluster is formed at the root of the tree. When using a hierarchical clustering algorithm, it is important to choose a proper linkage function for the dendrogram construction because different linkage functions have different properties \citep{aggarwal2013data}. For example, the complete-linkage function is sensitive to noise and outliers; and the average linkage function finds mainly globular clusters only \citep{aggarwal2013data}. We found that four commonly used linkage functions in T-AHC have difficulty in handling clusters with varied densities (see Section \ref{why}). To improve the performance of T-AHC, many variants of these common linkage functions have been introduced, attempting to address their limitations. HDBSCAN~\citep{campello2013density} uses a density-based linkage function to find clusters of varied densities.\footnote{HDBSCAN can be interpreted as a kind of AHC algorithm which relies on a single linkage function and a particular dissimilarity measure, see the details in~\ref{appendA}.} PHA~\citep{lu2013pha}, a potential-based hierarchical agglomerative clustering method based on a potential theory~\citep{shuming2002potential}, uses a potential field produced by the distance of all the data points to measure the similarity between clusters. The potential field is interpreted to represent the global data distribution information. PHA is claimed to be robust to different types of data distribution in a dataset. In order to capture the complex structure of a dataset, several graph-structural agglomerative clustering algorithms are proposed. Those algorithms first create a $k$-nearest-neighbour graph to obtain a set of small initial clusters. Then it iteratively merges two most similar clusters until the target number of clusters is obtained. Chameleon~\citep{karypis1999chameleon} measures the similarity between two clusters based on relative interconnectivity and relative closeness, both of which are defined on the graph. Zell~\citep{zhao2009cyclizing} describes the structure of a cluster and defines the similarity between two clusters based on the structural changes after merging. GDL~\citep{zhang2012graph} uses the product of average indegree and average outdegree in graphs to measure the similarity between two clusters. These algorithms typically use the pairwise distance to build the neighbourhood graph. Although they could handle clusters with varied densities to some degree, we show that simply replacing the distance with Isolation Kernel is able to significantly improve their clustering performance. All the above hierarchical clustering algorithms are based on a distance function to construct their linkage functions. As existing kernels like Gaussian kernel are data-independent, just as the distance function, the baseline of our investigation is AHC using kernel-based linkage functions, where the kernel is the commonly used Gaussian kernel. We will see later that both distance-based and this kernel-based linkage functions lead to the same bias we have mentioned in the introduction. \subsection{Kernels} Various kernel-based clustering algorithms have been developed to improve the performance of existing distance-based machine learning and data mining algorithms, including kernel k-means~\citep{scholkopf1998nonlinear,shawe2004kernel}, density-based clustering~\citep{hinneburg2007denclue,qin2019nearest}, spectral clustering~\citep{dhillon2004kernel,zelnik2005self,kang2018unified}, NMF~\citep{xu2003document}, kernel SOM~\citep{macdonald2000kernel} and kernel neural gas~\citep{qin2004kernel}. However, the study on the impact of a kernel on hierarchical clustering remains unexplored in the literature. In this paper, we focus on a commonly used data-independent kernel, i.e., Gaussian Kernel, and two data-dependent kernels, i.e., Adaptive Gaussian Kernel \citep{zelnik2005self} and Isolation Kernel \citep{ting2018IsolationKernel,qin2019nearest}; and examine their impacts on AHC. The former has been applied to spectral clustering, and the latter has been applied to SVM classifiers and DBSCAN \cite{ester1996density}. A brief description of each of these kernels is provided in the following. For any two points ${ x}, { y} \in \mathbb{R}^d$, \begin{description} \item[\textbf{Gaussian Kernel}:] The Gaussian Kernel defines the similarity between $x$ and $y$ as follows: \[ \mathcal{K}(x,y) = exp(\frac{-\parallel x - y \parallel^2}{2\sigma^2}) \] \noindent where $\sigma$ is the bandwidth of the kernel. Gaussian Kernel is a commonly used kernel, e.g., SVM for classification \citep{scholkopf2002learning} and t-SNE \citep{maaten2008visualizing} for visualisation. \item[\textbf{Adaptive Gaussian Kernel}:] In order to make the similarity adaptive to local density, Adaptive Gaussian Kernel \citep{zelnik2005self} is defined as: \begin{eqnarray} K_{AG}({ x},{ y}) & = & exp(\frac{-|| x- y||^2}{\sigma_{ x} \sigma_{ y}}) \label{Eqn_AG} \end{eqnarray} \noindent where $\sigma_{ x}$ is the Euclidean distance between $ x$ and $ x$'s $k$-th nearest neighbour. Adaptive Gaussian Kernel was introduced in spectral clustering to adjust the similarity locally to perform dimensionality reduction before clustering \citep{zelnik2005self}. \item[\textbf{Isolation Kernel}:] Isolation Kernel is a recently introduced data-dependent kernel, which adapts to local distribution. The pertinent details of Isolation Kernel \citep{ting2018IsolationKernel,qin2019nearest} are provided below. Let $\mathds{H}_\psi(D)$ denote the set of all partitions $H$ that are admissible under the dataset $D$, where each $H$ covers the entire space of $\mathbb{R}^d$; and each of the $\psi$ isolating partitions, $\theta[{z}] \in H$, isolates one data point ${z}$ from the rest of the points in a random subset $\mathcal D \subset D$, and $|\mathcal D|=\psi$. Here we use the Voronoi diagram \cite{aurenhammer1991voronoi} to partition the space, i.e., each $H \in \mathds{H}_\psi(D)$ is a Voronoi diagram and each sample point $z\in \mathcal D$ is a cell centre. \begin{definition} Isolation Kernel of ${ x}$ and ${ y}$ wrt $D$ is defined to be the expectation taken over the probability distribution on all partitions $H \in \mathds{H}_\psi(D)$ that both ${ x}$ and ${ y}$ fall into the same isolating partition $\theta[{ z}] \in H, { z} \in \mathcal{D}$: \begin{eqnarray} K_\psi({ x},{ y}\ |\ D) &=& {\mathbb E}_{\mathds{H}_\psi(D)} [\mathds{1}({ x},{ y} \in \theta[{ z}]\ | \ \theta[{ z}] \in H)] \nonumber \\ &=& {\mathbb E}_{\mathcal{D} \subset D} [\mathds{1}({ x},{ y}\in \theta[{ z}]\ | \ { z}\in \mathcal{D})] \nonumber \\ &=& P({ x},{ y}\in \theta[{ z}]\ | \ { z}\in \mathcal{D} \subset D) \label{eqn_kernel} \end{eqnarray} where $\mathds{1}(\cdot)$ is an indicator function. \end{definition} In practice, Isolation Kernel $K_\psi$ is constructed using a finite number of partitions $H_i, i=1,\dots,t$, where each $H_i$ is created using $\mathcal{D}_i \subset D$: \begin{eqnarray} K_\psi({ x},{ y}\ |\ D) & = & \frac{1}{t} \sum_{i=1}^t \mathds{1}({ x},{ y} \in \theta\ | \ \theta \in H_i) \nonumber\\ & = & \frac{1}{t} \sum_{i=1}^t \sum_{\theta \in H_i} \mathds{1}({ x}\in \theta)\mathds{1}({ y}\in \theta) \label{Eqn_IK} \end{eqnarray} \noindent where $\theta$ is a shorthand for $\theta[{ z}]$, and $\psi$ is the sharpness parameter\footnote{This parameter corresponds to the $\sigma$ parameter in the Gaussian kernel, i.e., the smaller $\sigma$ is, the more concentrated its kernel distribution.}, i.e., the larger $\psi$ is, the sharper its kernel distribution. As Equation (\ref{Eqn_IK}) is quadratic, $K_\psi$ is a valid kernel. The larger the $\psi$, the sharper the kernel distribution. $\psi$ is a parameter having a similar function to $\sigma$ in the Gaussian Kernel, i.e., the smaller $\sigma$ is, the narrower the kernel distribution. \end{description} \subsection{Dendrogram evaluation} An AHC algorithm produces a dendrogram or cluster tree. To evaluate the goodness of a dendrogram, \textit{Dendrogram Purity} has been created to measure the hierarchical clustering result \citep{heller2005bayesian,kobren2017hierarchical,monath2019scalable}. Given a dendrogram, the procedure finds the smallest subtree containing two leave nodes belonging to the same ground-truth cluster; and measures the fraction of leave nodes in that subtree which belongs to the same cluster. The dendrogram purity is the expected value of this fraction. It is 1 if and only if all leave nodes belonging to the same cluster are rooted in the same subtree. The dendrogram purity \citep{heller2005bayesian} is calculated as follows. Given a dendrogram $\mathcal{T}$ produced from a dataset $D=\{x_1,\dots,x_n\}$. Let $C^{\star} = \left\{ C_{t}^{\star}\right\}_{t=1}^{\kappa}$ be the true labels in $\kappa$ clusters, and $\mathcal{P}^{\star}=\left\{\left(x, x^{\prime}\right) | x, x^{\prime} \in \mathcal{X}, C^{\star}(x)=C^{\star}\left(x^{\prime}\right)\right\}$ be the set of pairs of points that are in the same ground-truth cluster. Then the dendrogram purity of $\mathcal{T}$ is \begin{equation}~ \mathrm{Purity}(\mathcal{T})=\frac{1}{\left|\mathcal{P}^{\star}\right|} \sum_{t=1}^{\kappa} \sum_{x_{i}, x_{j} \in C_{t}^{\star}} \operatorname{pur}\left(\operatorname{lvs}\left(\operatorname{LCA}\left(x_{i}, x_{j}\right)\right), C_{t}^{\star}\right) \label{eqn_dpurity} \end{equation} where $\operatorname{LCA}\left(x_{i}, x_{j}\right)$ is the least common ancestor of $x_i$ and $x_j$ in $\mathcal{T}$; $\operatorname{lvs}(z)\subset D$ is this the set of points in all the descendant leaves of $z$ in $\mathcal{T}$; and $\operatorname{pur}(S, C_{t}^{\star})=\frac{|S \cap C_{t}^{\star}|}{S}$ computes the fraction of $S$ that matches the ground-truth label of $C_{t}^{\star}$. We use dendrogram purity as an objective measure to assess the quality of the dendrograms produced by different clustering algorithms. \section{Kernel-based hierarchical clustering} An agglomerative method creates a dendrogram and extracts clusters from it. To build a dendrogram, it iteratively merges two most similar subclusters (as measured by a linkage function based on a similarity measure) until all points in a dataset are grouped into one cluster. A dendrogram contains a complete set of all possible subclusters grouped by the linkage function. It is richer than a flat clustering result produced by a partitioning clustering algorithm; and it shows the hierarchical relationship between subclusters. To extract the most meaningful clusters from a dendrogram, a cluster extraction algorithm applies cuts in the dendrogram to produce subtrees, where each subtree represents a cluster. Many kernel methods have been proposed to improve the performance of existing distance-based machine learning and data mining algorithms. For clustering, the use of kernel enables a method to capture the nonlinear relationship inherent in the data distribution and to separate non-convex clusters that would otherwise be impossible for distance-based methods. For example, kernel $k$-means \citep{scholkopf1998nonlinear} and spectral clustering \citep{zelnik2005self} have been shown to enrich the types of clusters that can be detected by distance-based k-means. An existing distance-based agglomerative clustering algorithm can be easily kernelised by replacing the distance matrix with the kernel similarity matrix, leaving the rest of the procedure unchanged. The procedure is shown in Algorithm~\ref{alg:khc} which employs $\hslash$ as a kernel linkage function.\footnote{When using a dissimilarity linkage function such as a Euclidean distance function, the Equation under the line 6 in Algorithm~\ref{alg:khc} should be $\argmin_{C_{\imath}\ne C_{\jmath} \in \mathbbm{C}} h(C_{\imath},C_{\jmath})$.} By setting $\kappa$ to 1, it produces a dendrogram. Table \ref{Kernel} shows the kernel versions of the four commonly used linkage functions in T-AHC. \begin{table*}[!htb] \renewcommand{\arraystretch}{1} \setlength{\tabcolsep}{0pt} \centering \caption{Kernel-based linkage functions $\hslash$ used in T-AHC. $C$ is a cluster which consists of data points; and $K$ is a kernel function.} \begin{tabular}{cc} \toprule Single-linkage & $\hslash(C_i,C_j)= \max_{x\in C_i y\in C_j} K(x,y) $ \\ Complete-linkage & $\hslash(C_i,C_j)= \min_{x\in C_i y\in C_j} K(x,y) $ \\ Average-linkage & $\hslash(C_i,C_j)= \frac{1}{|C_i||C_j|} \sum_{x\in C_i y\in C_j} K(x,y) $ \\ Weighted-linkage & \begin{minipage}{8cm}\begin{equation} \hslash(C_i,C_j) = \left\{ \begin{array}{l} \frac{ \hslash(C_p,C_j)+\hslash(C_q,C_j)}{2}, \text{ if } C_i=C_q \cup C_p\\ K(C_i, C_j), \text{ if } |C_i|=|C_j|=1 \end{array} \right. \nonumber \end{equation} \end{minipage} \\ \bottomrule \end{tabular}% \label{Kernel}% \end{table*}% \begin{algorithm}[!!htb] \SetAlgoLined \SetKwInOut{Input}{Input}\SetKwInOut{Output}{Output} \Input{$M$ - pairwise similarity matrix ($n \times n$ matrix); $\kappa$ - target number of clusters} \Output{$\mathbbm{C} = \{C_1,C_2,\dots,C_\kappa\}$} \BlankLine \For{ $j = 1,2,\dots,n$ \KwTo } { $C_j=\{x_j\}$;} $\mathbbm{C}=\{C_1, C_2, ..., C_n\}$ \; \While{$|\mathbbm{C}|>\kappa$ \KwTo} {Find the most similar pair $C_{p}$ and $C_{q}$ based on linkage function $\hslash$: $\argmax_{C_{\imath}\ne C_{\jmath} \in \mathbbm{C}} \hslash(C_{\imath},C_{\jmath})$\; Merge $C_{p}$ and $C_{q}$ in $\mathbbm{C}$\; } \caption{ AHC - Agglomerative hierarchical clustering} \label{alg:khc} \end{algorithm} \newpage Here we provide the definitions associated with Algorithm \ref{alg:khc} and its resultant dendrogram; and a theorem stating the condition under which two ground-truth clusters can be successfully extracted from the dendrogram. \begin{definition} Given a set of points $D=\{x_1,\dots,x_n\}$, a set of subclusters are initialised as $\mathbbm{C}_1 = \{C_1,C_2,\dots,C_n\}$, where $C_i=\{x_i\}$. The kernel agglomerative clustering algorithm recursively merges the two most similar subclusters $C_p$ and $C_q$ at each step $s$ and updates the set of subclusters to $\mathbbm{C}_s=\{\mathbbm{C}'_{s-1} \cup C_{pq} \}$, where $\mathbbm{C}'_{s-1} = \mathbbm{C}_{s-1} \setminus \{ C_p, C_q\}$ and $C_{pq}=C_p \cup C_q$, as measured by a kernel-based linkage function $\hslash$, i.e., $\{C_p,C_q\}=\argmax_{C_{i}\ne C_{j} \in \mathbbm{C}_{S-1}} \hslash(C_{i},C_{j})$, until all subclusters are merged into one final cluster. \label{kerAHC} \end{definition} \begin{definition} A dendrogram is a tree structure representing the order of the subcluster merging process. The height at the root of a subtree indicates the value of the kernel-based linkage function which is used to merge the two subclusters to form the subtree. \end{definition} \begin{definition} A cluster extracted by a cut $\eta$ on the dendrogram is a subtree from which its next merged height is more than $\eta$. \end{definition} \begin{theorem} Given two non-overlapping ground-truth clusters $\zeta_i$ and $\zeta_j$ in a dataset, to correctly identify them from the dendrogram produced by the agglomerative clustering algorithm with a kernel linkage function $\hslash$, both clusters must satisfy the following condition: \begin{equation} \forall_{\imath \leq I,\jmath \leq J}\ \min(\hat{\hslash}(\mathbbm{C}_\imath^i),\hat{\hslash}(\mathbbm{C}_\jmath^j)) \ge \hat{\hslash}(\mathbbm{C}_\imath^i,\mathbbm{C}_\jmath^j) \label{eqn:condition} \end{equation} where $\mathbbm{C}_\imath^i$ is the set of subclusters at step $\imath$ of the process in merging members in $\zeta_i$; so as $\mathbbm{C}_\jmath^j$ in $\zeta_j$ (as defined in Definition 3); $\hat{\hslash}(\mathbbm{C}_\imath^i)=max_{C_{p} \neq C_{q} \in \mathbbm{C}_\imath^i} \hslash(C_{p},C_{q})$ and $\hat{\hslash}(\mathbbm{C}_\imath^i,\mathbbm{C}_\imath^j)=max_{C_{p}\in \mathbbm{C}_\imath^i, C_{q} \in \mathbbm{C}_\imath^j} \hslash(C_{p},C_{q})$; and $I$ and $J$ are the maximum numbers of steps required to merge all points in $\zeta_i$ and $\zeta_j$, respectively. \label{Theorem1} \end{theorem} \begin{proof} Given two clusters $\zeta_i$ and $\zeta_j$, an violation of Equation \ref{eqn:condition} means $\exists_{s \leq I, t \leq J}\ \min(\hat{\hslash}(\mathbbm{C}_\imath^s),\hat{\hslash}(\mathbbm{C}_\jmath^t)) < \hat{\hslash}(\mathbbm{C}_\imath^s,\mathbbm{C}_\jmath^t)$, i.e., $\exists_{C_p\in \mathbbm{C}_\imath^s,C_q\in \mathbbm{C}_\imath^t} \forall_{C_a\neq C_b \neq C_q \neq C_p \in \{ \mathbbm{C}_\imath^s \cup \mathbbm{C}_\imath^t \}} \hslash(C_{p},C_{q})\ge \hslash(C_{a},C_{b})$. Using the a linkage function, subclusters $C_p$ and $C_q$ from $\zeta_i$ and $\zeta_j$ will be merged before each cluster merges its all own subclusters. Thus, the clusters which can be extracted from the dendrogram are subtrees containing points from two clusters or partial points from one cluster. \end{proof} Equation \ref{eqn:condition} stipulates the condition that the linkage function shall enable each subtree to merge all members of the same cluster first, before merging with the subtree of the other cluster to form the final tree of the dendrogram. Otherwise, an entanglement has occurred. \begin{corollary} An entanglement between two clusters $\zeta_i$ and $\zeta_j$ is said to have occurred in the dendrogram, produced by the agglomerative clustering algorithm with a kernel linkage function $\hslash$, when there is a violation of Equation \ref{eqn:condition} at $\imath=s,\jmath=t$ such that \begin{equation} \exists_{s \leq I, t \leq J}\ \min(\hat{\hslash}(\mathbbm{C}^i_s),\hat{\hslash}(\mathbbm{C}^j_t)) < \hat{\hslash}(\mathbbm{C}^i_s,\mathbbm{C}^j_t) \label{eqn_entanglement} \end{equation} \end{corollary} If one or more entanglements have occurred, then the set of all possible subclusters in the dendrogram does not contain clusters $\zeta_i$ and $\zeta_j$, but their corrupted or partial versions. Thus, if entanglements could not be avoided (e.g., in a dataset where clusters are very close to each other or even overlapping), an hierarchical clustering algorithm shall seek to achieve (i) an entanglement at $\imath,\jmath$ as high values as possible; and (ii) the least number of entanglements, in order to reduce the impact of incorrect membership assignment. We use the following two indicators to assess the severity of the entanglement in a dendrogram. The {\em number of entanglements} in a dendrogram can be counted as follows: At every merge, the node is labelled with either a cluster label (if the two subclusters before merging have the same cluster labe ) or neutral (if the two subclusters have different labels or one of them has neutral label). Every time a neutral label is used in a node, an entanglement has occurred; and the number of entanglements is incremented by 1. The entanglement level is the sum of $s$ and $t$ (in Equation \ref{eqn_entanglement}) when an entanglement occurs. The {\em average level of entanglements} is the ratio of the total level of all entanglements and the number of entanglements, where the level of entanglement at a merge is the number of steps used to reach that merge in the process. \section{Why using data-dependent kernel?} \label{why} Here we discuss the density bias of T-AHC when a data-independent kernel is used and the reason why a data-dependent kernel can deal with clusters of varied densities better than data-independent kernel in the following two subsections. \subsection{T-AHC has density bias when a data-independent kernel/distance is used} Our investigation leads to the following observation: \begin{observation} T-AHC has a bias which links points in a dense region ahead of points in a sparse region in general. This bias is due to the use of a data-independent kernel/distance. \end{observation} Single-linkage clustering builds the dendrogram where the heights is related to the 1-nearest neighbour density estimate, i.e., the points with higher heights (are merged later on the dendrogram) tend to be in low-density regions \cite{klemela2009smoothing}. This linking bias often lead to poor clustering outcomes when adjacent clusters have different densities, i.e., the boundary points from a sparse cluster may link to its neighbouring dense cluster before linking back to the sparse cluster. Note that this bias has no issue if the clusters are clearly separated. Although other linkage function could be less sensitive to the density distribution and may eliminate the issue in the cluster boundary regions, we have the following observation: \begin{definition} Two clusters $C_a$ and $C_b$ are said to be well separated if any points in the valley $V$ between these clusters have the density less than any points in either cluster, i.e., $\rho'(z) < \rho(x)$, \noindent where $\rho$ is the density of individual distribution of either $C_a$ or $C_b$; $\rho'$ is the density of the joint distribution of $C_a \cup C_b$; $z \in V$ which is part of the joint distribution of $C_a \cup C_b$; and $x \in C$ of individual cluster $C_a$ or $C_b$. \end{definition} \begin{observation} With a data-independent kernel-based linkage function, the bias of T-AHC creates entanglements if the clusters are not well separated. \end{observation} For example, the single-linkage function relies on the nearest neighbour similarity/distance calculation. Given two adjacent clusters $C_d$ and $C_s$, if $\exists_{x\in C_d, y\in C_s} \forall_{z\neq y \in C_s} K(x,y)>K(y,z)$, then $y$ will engage in an entanglement using this linkage function. In other words, every entanglement involves a boundary point from $C_s$ which is more similar to a boundary point from $C_d$ than other points from $C_s$. \begin{observation} Different linkage functions produce different degrees of entanglements but the bias remains: T-AHC links points in a dense region ahead of points in a sparse region. \end{observation} This can be seen from the example in Table 2, where four commonly used linkage functions shown in Table \ref{Kernel} are examined. When Gaussian kernel is used, independent of the linkage functions used, each dendrogram has low linkage $\hslash$ values in dense regions (three dense clusters) and high $\hslash$ values in sparse regions (one sparse cluster (brown)). We contend that the root cause of this bias is the use of data-independent similarity/distance.\\ To reduce/eliminate this bias, we need a similarity which is data-dependent. \begin{table} [!htbp] \scriptsize \centering \begin{tabular}{cccc} \hline & Gaussian Kernel & Isolation Kernel \\ \hline & Dendrogram purity=0.77 & Dendrogram purity=0.97 \\ \begin{turn}{90} \qquad \quad Single-linkage \end{turn}& \includegraphics[width=1.8in]{figure/Image/DeGK.png} & \includegraphics[width=1.8in]{figure/Image/ANNEhard1.png} \\ & No. entanglements= 242 & No. entanglements=170 \\ & Avg. entanglement level=1411 &Avg. entanglement level=1477 \\ \hdashline &Dendrogram purity=0.95 & Dendrogram purity=0.98 \\ \begin{turn}{90} \quad \quad Average-linkage \end{turn}& \includegraphics[width=1.8in]{figure/Image/DeGKA.png} & \includegraphics[width=1.8in]{figure/Image/AveAnn.png} \\ & No. entanglements=103 & No. entanglements=100 \\ & Avg. entanglement level=1350 &Avg. entanglement level=1445 \\ \hdashline &Dendrogram purity=0.88 & Dendrogram purity=0.97 \\ \begin{turn}{90}\quad \quad Complete-linkage \end{turn}& \includegraphics[width=1.8in]{figure/Image/DeGKC.png} & \includegraphics[width=1.8in]{figure/Image/ComAnn.png} \\ & No. entanglements=105 & No. entanglements=98 \\ & Avg. entanglement level=1394 &Avg. entanglement level=1490 \\ \hdashline &Dendrogram purity=0.91 & Dendrogram purity=0.97 \\ \begin{turn}{90}\qquad \qquad Weighted \end{turn}& \includegraphics[width=1.8in]{figure/Image/DeGKW.png} & \includegraphics[width=1.8in]{figure/Image/WightAnn.png} \\ & No. entanglements=106 & No. entanglements=102 \\ & Avg. entanglement level=1360 &Avg. entanglement level=1504 \\ \\ \hline \end{tabular} \caption{Comparison of dendrograms produced by T-AHC with four linkage functions using Gaussian Kernel and Isolation Kernel on the dataset shown in Figure \ref{fig:hard21}. The colours at the bottom row in each dendrogram correspond to the true cluster labels of all points shown in Figure \ref{fig:hard21}.} \label{fig:CompareDen} \end{table} \subsection{How data-dependent kernel helps} Here we show that a data-dependent kernel called Isolation Kernel (IK) \citep{ting2018IsolationKernel,qin2019nearest}, which adapts its similarity measurement to the local density, significantly reduces the density bias posed by distance and data-independent kernel. The unique characteristic of Isolation Kernel~\citep{ting2018IsolationKernel,qin2019nearest} is: \textbf{two points in a sparse region are more similar than two points of equal inter-point distance in a dense region}, i.e, $\forall x,y \in \mathcal{X}_{s}$, $\forall x^{\prime}, y^{\prime} \in \mathcal{X}_{d}$ if $\parallel x - y \parallel = \parallel x^{\prime} - y^{\prime}\parallel$ then \begin{equation} K_{\psi}(x, y)>K_{\psi}\left(x^{\prime}, y^{\prime}\right) \label{ike} \end{equation} where $\mathcal{X}_{s}$ and $\mathcal{X}_{d}$ are two subsets of points in sparse and dense regions of $\mathbb{R}^d$, respectively; and $\parallel x - y \parallel$ is the distance between $x$ and $y$.\footnote{The proof of this characteristic is in the paper \cite{qin2019nearest}.} Isolation Kernel deals more effectively with clusters with hugely different densities than data-independent kernels. This is because the isolation mechanism produces large partitions in a sparse region and small partitions in a dense region. Thus, the probability of two points from the dense cluster falling into the same isolating partition is higher than two points of equal inter-point distance from the sparse cluster. This gives rise to the data-dependent kernel characteristic mentioned above. As a consequence of the above adaptation, the boundary points from a sparse cluster become less similar to the boundary points from a dense cluster. Thus, IK reduces the number of entanglements, and increases $s$ and $t$ in Equation \ref{eqn_entanglement} if an entanglement do occur in comparison with using a data-independent Kernel in T-AHC. Note that the condition in Equation \ref{eqn:condition} also applies when Isolation Kernel is used. However, the influence of its data dependency is significant, as described below. The isolation partitioning mechanism used to create IK is based on random samples from a given dataset. It yields two effects. First, the mechanism produces small partitions in dense clusters and large partitions in sparse clusters \citep{ting2018IsolationKernel,qin2019nearest}. The net effect is that every cluster has almost the same uniform distribution when transformed using MDS\footnote{Multidimensional scaling (MDS) is used for visualising the information contained in a similarity matrix \citep{borg2012applied}. It placed each data point in a $2$-dimensional space, while preserving as well as possible the pairwise similarities between points.} into a Euclidean space. This is shown in Figure \ref{fig:hard22}. This effect was also observed in another data-dependent dissimilarity measure using a similar isolation mechanism, though it is not a kernel (see \cite{ting2019lowest} for details.) Second, since data points in the valleys between clusters are less likely to include (than those within each cluster) in the sample used to create IK, each partition has a tiny or no chance to cover more than one cluster. As a result, the gaps/valleys between clusters become more pronounced in the transformed MDS space. Figure \ref{fig:hard22} shows a comparison between the MDS plots of GK and IK when they are used to transform the same dataset shown in Figure \ref{fig:hard22}(a). \begin{figure} [!htb] \centering \begin{subfigure}[b]{0.43\textwidth} \centering \includegraphics[width=\textwidth]{figure/Image/hard2.png} \caption{Dataset: 4 clusters of different densities} \label{fig:hard221} \end{subfigure}\\ \begin{subfigure}[b]{0.43\textwidth} \centering \includegraphics[width=\textwidth]{figure/Image/mdsGK.png} \caption{MDS plot using GK} \label{fig:hard222} \end{subfigure} \begin{subfigure}[b]{0.43\textwidth} \centering \includegraphics[width=\textwidth]{figure/Image/mdsIK.png} \caption{MDS plot using IK} \label{fig:hard223} \end{subfigure} \caption{MDS plot using Gaussian Kernel and Isolation Kernel on the dataset in (a).} \label{fig:hard22} \end{figure} These two net effects lead to the following observation: \begin{observation} T-AHC using a linkage function derived from Isolation Kernel has little or no bias towards points in dense regions, regardless of the relative density between clusters. \end{observation} In other words, the distribution of merges in the dendrogram produced by T-AHC becomes more uniform over all clusters, as a result of the first effect. Yet, the entanglements (i.e., merges between two different clusters) becomes less, as a consequence of the second effect. This can be seen from all four dendrograms showed in Table \ref{fig:CompareDen} using four different linkage functions. The $\hslash$ values of every Isolation kernel-based linkage function are more uniformly distributed than those of the corresponding Gaussian kernel-based linkage function. Yet, the number of entanglements due to IK is less, and the average entanglement level is higher. In summary, with Isolation Kernel: (a) an entanglement is less likely to occur since T-AHC always seeks to merge two subclusters which are most similar at each step; and (b) if an entanglement occurs, it will happen at higher values of $s$ and $t$ (in Equation \ref{eqn_entanglement}) than those due to Gaussian kernel. As a result, the impact of incorrect membership assignment will be smaller than that when a data-independent kernel linkage function is used. This is verified using dendrogram purity in Equation \ref{eqn_dpurity} \citep{heller2005bayesian} which is an objective measure assessing the goodness of a dendrogram produced by an AHC algorithm. As shown in Table \ref{fig:CompareDen}, Isolation Kernel always has higher dendrogram purity than the Gaussian kernel in every linkage function. This result is also reflected in terms of the number of entanglements (the lower the better) and the average entanglement level (the higher the better), as stipulated in relation to Corollary \ref{eqn_entanglement}. \subsection{Demonstration on an image segmentation task} Here we use an image segmentation task to demonstrate the density bias of T-AHC on a real-world image, as shown in Figure \ref{image}. The scatter plot of this image in the LAB space \citep{szeliski2010computer} shows that there is a clear gap between a dense cluster (representing the sky object) which is in close proximity to a sparse cluster (representing the building object) in the LAB space, although the sparse cluster has some dense areas. The dendrogram produced by IK is much better than that by GK, judging from the dendrogram purity results. When using the single-linkage AHC with Gaussian Kernel, the dendrogram produces a result that the building object is partially merged to the sky object if the best cut is applied, as shown in the first row of Table \ref{seg2}. This is the effect of varied cluster densities in the LAB space. In contrast, using the Isolation Kernel, the building and sky are well separated, as shown in the second row in Table \ref{seg2}. \begin{figure}[!htb] \centering \begin{subfigure}[b]{0.4\textwidth} \centering\captionsetup{width=0.8\linewidth}% \includegraphics[width=\textwidth]{figure/Image/s2.png} \caption{Image} \label{hard1:a} \end{subfigure} % \begin{subfigure}[b]{0.4\textwidth} \centering\captionsetup{width=0.8\linewidth}% \includegraphics[width=\textwidth]{figure/Image/S2P.png} \caption{Pixels in LAB space} \label{hard1:d} \end{subfigure} \caption{An example dataset of an image} \label{image} \end{figure} \begin{table}[!htb] \setlength{\tabcolsep}{1.8pt} \scriptsize \centering \caption{Image segmentation results on the image using the LAB space shown in Figure \ref{image}, produced from the AHC algorithm with either Gaussian Kernel or Isolation Kernel. Each scatter plot in the `LAB Space' column illustrates the top two clusters identified (indicated by different colours) where the building (mainly green and sparse) is separated from the sky (mainly blue and dense). Columns `Cluster 1' and `Cluster 2' show the segmentation results on the image. The colours at the bottom row in each dendrogram correspond to the true cluster labels of all points, i.e, blue for sky and green for building. } \begin{tabular}{ccccc} \hline & LAB Space & Dendrogram & Cluster 1 & Cluster 2 \\ \hline \begin{turn}{90} GK single-linkage \end{turn}& \includegraphics[width=1.5in]{figure/Image/DIS.png} & \includegraphics[width=1.6in]{figure/Image/SigGK.png} & \includegraphics[width=1.2in]{figure/Image/DIS1.png} & \includegraphics[width=1.2in]{figure/Image/DIS2.png} \\ & Dendrogram purity=0.87 & No. entanglements=210 & Avg. entanglement level=7640 \\ \hdashline \begin{turn}{90} IK single-linkage \end{turn}& \includegraphics[width=1.5in]{figure/Image/IKS.png} & \includegraphics[width=1.6in]{figure/Image/SigIK.png} & \includegraphics[width=1.2in]{figure/Image/IKS2.png} & \includegraphics[width=1.2in]{figure/Image/IKS1.png} \\ & Dendrogram purity=0.99 & No. entanglements=16 & Avg. entanglement level=8091 \\ \hline \end{tabular} \label{seg2} \end{table} \subsection{Section summary} We found that T-AHC using Gaussian Kernel has density bias, a known bias for T-AHC using distance. This bias heightens the severity of entanglements between clusters. As a result, T-AHC using Gaussian kernel will have difficulty separating the clusters successfully on a dataset with clusters of varied densities. This phenomenon can be explained with the condition specified in Equation \ref{eqn:condition}. We contend that the root cause of this bias is the use of a data-independent kernel. We show that using Isolation Kernel---because it adapts its similarity to local density---the resultant T-AHC has less density bias which reduces the severity and the number of entanglements. As a result, T-AHC using Isolation Kernel usually produces a better dendrogram than that using Gaussian Kernel. We show in the next section that the same approach we suggested here, i.e., using Isolation Kernel instead of a data-dependent kernel/distance, can be applied to other hierarchical clustering algorithms, apart from T-AHC. We also show that not all data-dependent kernels are the same. \section{Empirical evaluation}~\label{sec:experiments} We provide the experimental settings and report the evaluation results in this section. In the experiment, we compared kernel-based hierarchical clustering with traditional hierarchical clustering algorithms including T-AHC with single-linkage and complete-linkage, the potential-based hierarchical agglomerative method PHA~\citep{lu2013pha}, the graph-based agglomerative method GDL~\citep{zhang2012graph} and the density-based method HDBSCAN~\citep{campello2013density}. All algorithms used in our experiments are implemented in Matlab. \subsection{Parameter settings}~\label{subsec:parameter} Each parameter of an algorithm is searched within a certain range. Table~\ref{para} shows the search ranges for all parameters; and we report the best performance on each dataset. The $k$ is the number of nearest neighbours for constructing the KNN graph and Adaptive Gaussian Kernel from Equation~\ref{Eqn_AG}. The $s$ in PHA is the scale factor for calculating the potential introduced \citep{lu2013pha}. $l$ and $c$ in HDBSCAN are minimum cluster sizes and minimum samples, respectively.\footnote{The guide for parameter selection for HDBSCAN (so as its source code) is from https://hdbscan.readthedocs.io/ \citep{mcinnes2017accelerated}. All other codes used in empirical evaluations are published by the original authors. It is worth noting that not all parameters are valid for GDL in all datasets because the based $k$-nearest neighbours graph methods are sensitive for the parameter and similarity measure. Here we only record the available results. In addition, GDL source code does not output the dendrogram, thus we have to omit it in the dendrogram purity evaluation.} \begin{table}[!htb] \centering \footnotesize \caption{Parameters and their search ranges for each algorithm. For AGK and IK, we searched all integer values within $[2,\lceil n/2 \rceil]$. T-AHC is an AHC using one of the four linkage functions in Table \ref{Kernel}.} \begin{tabular}{|c|c|} \hline Algorithm/Kernel & Parameter search range \\ \hline T-AHC & $\kappa \in \{2,\dots,30\}$ \\ HDBSCAN & $l \in [2,100]$, $c \in [2,100] $ \\ PHA & $s \in \{5,10,15,20,25,30\}$ \\ GDL & $k \in \{5,10,15,20,25,30,70,100\}$ \\ \hdashline Gaussian Kernel & $\sigma = 2^m$, \newline{} $m \in [-5,5]$ \\ Adaptive Gaussian Kernel & $k \in [2, \lceil n/2 \rceil]$ \\ Isolation Kernel & $\psi \in [2, \lceil n/2 \rceil]$, $t=200$ \\ \hline \end{tabular}% \label{para}% \end{table}% The experiments use 19 real-world datasets with different data sizes and dimensions from UCI Machine Learning Repository \citep{Dua:2019}. The data properties are shown in the first four columns in Table~\ref{tab:dataset}. All datasets were normalised using the Min-Max normalisation to yield each attribute to be in [0,1] before the experiments began. Some of these datasets have been shown to have clusters with varied densities, e.g., thyroid, seeds, wine, WDBC and Segment~\citep{zhu2016density}. \begin{table}[!htb] \renewcommand{\arraystretch}{0.8} \setlength{\tabcolsep}{2pt} \centering \caption{Properties of the datasets used in the experiments} \begin{tabular}{|c|ccc|} \hline Name & \#instance & \#Dim. & \#Clusters \\ \hline banknote & 1372 & 4 & 2 \\ thyroid & 215 & 5 & 3 \\ seeds & 210 & 7 & 3 \\ diabetes & 768 & 8 & 2 \\ vowel & 990 & 10 & 11 \\ wine & 178 & 13 & 3 \\ shape & 160 & 17 & 9 \\ Segment & 2310 & 19 & 7 \\ WDBC & 569 & 30 & 2 \\ spam & 4601 & 57 & 2 \\ control & 600 & 60 & 6 \\ hill & 1212 & 100 & 2 \\ LandCover & 675 & 147 & 9 \\ musk & 476 & 166 & 2 \\ LSVT & 126 & 310 & 2 \\ Isolet & 1560 & 617 & 26 \\ COIL20 & 1440 & 1024 & 20 \\ lung & 203 & 3312 & 5 \\ ALLAML & 72 & 7129 & 2 \\ \hline \end{tabular}% \label{tab:dataset}% \end{table}% \subsection{Hierarchical clustering evaluation} We evaluate cluster trees using \textit{Dendrogram Purity} shown in Equation~\ref{eqn_dpurity}. In words, to compute \textit{Dendrogram Purity} of a dendrogram $\mathcal{T}$ with ground-truth clusters $C^{\star}$, for all pairs of points $\left(x_i, x_j \right)$ which belong to the same ground-truth cluster, find the smallest subdendrogram containing $x_i$ and $x_j$, and compute the fraction of leaves in that subdendrogram which are in the same ground-truth cluster as $x_i$ and $x_j$. For large-scale dataset, we use Monte Carlo to approximated the \textit{Dendrogram Purity}. In Table~\ref{tab:purity}, we report the dendrogram purity for the two T-AHC algorithms (single-linkage, average-linkage), PHA, HDBSCAN and their kernerlise with three kernel functions (G,AG and IK). The best result on each dataset is boldfaced. We observe that kernel method consistently produces dendrogram with the highest \textit{dendrogram purity} amongst all algorithms. \begin{landscape} \begin{table}[!htb] \small \renewcommand{\arraystretch}{1} \setlength{\tabcolsep}{1pt} \centering \caption{Clustering results in \textit{Dendrogram Purity}. The best result on each dataset is boldfaced. $n$, $d$, $\kappa$ are \#Point, \#Dimension and \#Clusters, respectively.} \begin{tabular}{|c|cccc|cccc|cccc|cccc|cccc|cccc|} \hline \multicolumn{1}{|c|}{\multirow{2}[4]{*}{Dataset}} & \multicolumn{4}{c|}{Single-linkage AHC} & \multicolumn{4}{c|}{Complete-linkage AHC} & \multicolumn{4}{c|}{Average-linkage AHC} & \multicolumn{4}{c|}{Weight-linkage AHC} & \multicolumn{4}{c|}{PHA} & \multicolumn{4}{c|}{HDBSCAN} \\ \cline{2-25} & Dis & G & AG & IK & Dis & G & AG & IK & Dis & G & AG & IK & Dis & G & AG & IK & Dis & G & AG & IK & Dis & G & AG & IK \\ \hline \multicolumn{1}{|c|}{banknote} & 0.92 & 0.92 & \textbf{0.99} & \textbf{0.99} & 0.63 & 0.63 & 0.80 & \textbf{0.82} & 0.68 & 0.96 & 0.78 & \textbf{0.98} & 0.64 & 0.78 & 0.73 & \textbf{0.94} & 0.62 & 0.71 & 0.68 & \textbf{0.76} & 0.92 & 0.92 & 0.96 & \textbf{0.99} \\ \multicolumn{1}{|c|}{thyroid} & 0.92 & 0.92 & 0.93 & \textbf{0.93} & 0.89 & 0.89 & 0.95 & \textbf{0.97} & 0.93 & 0.92 & 0.94 & \textbf{0.96} & 0.86 & 0.92 & 0.95 & \textbf{0.97} & 0.91 & 0.92 & 0.92 & \textbf{0.93} & 0.92 & 0.93 & 0.92 & \textbf{0.96} \\ \multicolumn{1}{|c|}{seeds} & 0.69 & 0.69 & 0.81 & \textbf{0.85} & 0.75 & 0.75 & 0.84 & \textbf{0.86} & 0.85 & 0.85 & 0.88 & \textbf{0.89} & 0.76 & 0.74 & 0.85 & \textbf{0.88} & 0.84 & 0.84 & \textbf{0.89} & 0.88 & 0.65 & 0.73 & 0.79 & \textbf{0.84} \\ \multicolumn{1}{|c|}{diabetes} & 0.67 & 0.67 & 0.67 & \textbf{0.70} & 0.66 & 0.66 & 0.67 & \textbf{0.68} & 0.67 & 0.67 & 0.67 & \textbf{0.70} & 0.63 & 0.64 & 0.66 & \textbf{0.67} & 0.67 & 0.68 & 0.68 & \textbf{0.69} & 0.68 & 0.68 & 0.67 & \textbf{0.69} \\ \multicolumn{1}{|c|}{vowel} & 0.20 & 0.20 & 0.24 & \textbf{0.26} & 0.22 & 0.22 & 0.25 & \textbf{0.27} & 0.22 & 0.22 & 0.24 & \textbf{0.28} & 0.23 & 0.25 & 0.27 & \textbf{0.30} & 0.20 & 0.22 & 0.23 & \textbf{0.24} & 0.19 & 0.19 & 0.23 & \textbf{0.24} \\ \multicolumn{1}{|c|}{wine} & 0.68 & 0.68 & 0.84 & \textbf{0.90} & 0.92 & 0.92 & 0.96 & \textbf{0.98} & 0.89 & 0.92 & 0.94 & \textbf{0.96} & 0.81 & 0.82 & 0.93 & \textbf{0.94} & 0.73 & 0.74 & 0.91 & \textbf{0.94} & 0.63 & 0.79 & 0.75 & \textbf{0.89} \\ \multicolumn{1}{|c|}{shape} & 0.69 & 0.69 & \textbf{0.70} & \textbf{0.70} & 0.65 & 0.65 & 0.68 & \textbf{0.69} & 0.65 & 0.65 & \textbf{0.72} & \textbf{0.72} & 0.68 & 0.68 & 0.73 & \textbf{0.74} & 0.67 & 0.67 & 0.70 & \textbf{0.74} & 0.68 & 0.70 & 0.70 & \textbf{0.75} \\ \multicolumn{1}{|c|}{Segment} & 0.60 & 0.60 & 0.64 & \textbf{0.67} & 0.62 & 0.62 & 0.65 & \textbf{0.67} & 0.65 & 0.67 & 0.69 & \textbf{0.72} & 0.59 & 0.61 & 0.66 & \textbf{0.71} & 0.65 & 0.70 & 0.72 & \textbf{0.74} & 0.59 & 0.59 & 0.64 & \textbf{0.67} \\ \multicolumn{1}{|c|}{WDBC} & 0.71 & 0.72 & 0.74 & \textbf{0.90} & 0.79 & 0.79 & 0.89 & \textbf{0.91} & 0.86 & 0.89 & 0.89 & \textbf{0.93} & 0.83 & 0.86 & 0.90 & \textbf{0.94} & 0.73 & 0.79 & 0.87 & \textbf{0.95} & 0.73 & 0.73 & 0.71 & \textbf{0.90} \\ \multicolumn{1}{|c|}{spam} & 0.59 & 0.56 & 0.57 & \textbf{0.64} & 0.57 & 0.56 & 0.60 & \textbf{0.69} & 0.58 & 0.56 & 0.64 & \textbf{0.69} & 0.58 & 0.59 & 0.66 & \textbf{0.69} & 0.55 & 0.57 & 0.65 & \textbf{0.68} & 0.55 & 0.56 & 0.57 & \textbf{0.94} \\ \multicolumn{1}{|c|}{control} & 0.73 & 0.73 & 0.80 & \textbf{0.87} & 0.81 & 0.81 & 0.82 & \textbf{0.85} & 0.81 & 0.81 & 0.91 & \textbf{0.94} & 0.77 & 0.75 & 0.89 & \textbf{0.90} & 0.66 & 0.67 & 0.79 & \textbf{0.82} & 0.71 & 0.71 & 0.75 & \textbf{0.83} \\ \multicolumn{1}{|c|}{hill} & 0.50 & 0.50 & \textbf{0.51} & \textbf{0.51} & 0.50 & 0.50 & \textbf{0.51} & \textbf{0.51} & 0.50 & 0.50 & \textbf{0.51} & \textbf{0.51} & 0.50 & 0.50 & \textbf{0.51} & \textbf{0.51} & 0.50 & 0.50 & \textbf{0.51} & \textbf{0.51} & 0.50 & 0.50 & \textbf{0.51} & \textbf{0.51} \\ \multicolumn{1}{|c|}{LandCover} & 0.30 & 0.30 & 0.39 & \textbf{0.55} & 0.52 & 0.52 & 0.58 & \textbf{0.60} & 0.56 & 0.59 & 0.63 & \textbf{0.64} & 0.48 & 0.56 & 0.59 & \textbf{0.60} & 0.44 & 0.48 & 0.53 & \textbf{0.61} & 0.27 & 0.27 & 0.35 & \textbf{0.48} \\ \multicolumn{1}{|c|}{musk} & 0.54 & \textbf{0.64} & 0.54 & 0.55 & 0.56 & \textbf{0.65} & 0.56 & 0.57 & 0.55 & \textbf{0.65} & 0.56 & 0.57 & 0.55 & \textbf{0.65} & 0.56 & 0.57 & 0.54 & \textbf{0.65} & 0.56 & 0.56 & 0.54 & \textbf{0.94} & 0.56 & 0.93 \\ \multicolumn{1}{|c|}{LSVT} & 0.58 & 0.60 & 0.63 & \textbf{0.67} & 0.62 & 0.62 & 0.65 & \textbf{0.71} & 0.63 & 0.63 & 0.65 & \textbf{0.67} & 0.61 & 0.64 & 0.66 & \textbf{0.69} & 0.59 & 0.60 & 0.67 & \textbf{0.71} & 0.58 & 0.61 & 0.62 & \textbf{0.64} \\ \multicolumn{1}{|c|}{Isolet} & 0.27 & 0.27 & 0.36 & \textbf{0.58} & 0.48 & 0.48 & 0.56 & \textbf{0.57} & 0.57 & 0.60 & 0.62 & \textbf{0.68} & 0.54 & 0.59 & 0.59 & \textbf{0.66} & 0.39 & 0.48 & 0.50 & \textbf{0.64} & 0.21 & 0.57 & 0.29 & \textbf{0.61} \\ \multicolumn{1}{|c|}{COIL20} & 0.91 & 0.91 & 0.99 & \textbf{1.00} & 0.66 & 0.67 & 0.66 & \textbf{0.70} & 0.72 & \textbf{0.93} & 0.79 & \textbf{0.93} & 0.72 & 0.97 & 0.82 & \textbf{0.98} & 0.70 & 0.76 & 0.76 & \textbf{0.79} & 0.89 & 0.90 & 0.99 & \textbf{1.00} \\ \multicolumn{1}{|c|}{lung} & 0.76 & 0.91 & 0.82 & \textbf{0.95} & 0.89 & 0.92 & 0.93 & \textbf{0.96} & 0.94 & 0.94 & \textbf{0.96} & \textbf{0.96} & 0.94 & 0.95 & 0.95 & \textbf{0.96} & 0.77 & 0.95 & 0.86 & \textbf{0.98} & 0.87 & 0.87 & 0.90 & \textbf{0.97} \\ \multicolumn{1}{|c|}{ALLAML} & 0.68 & 0.68 & 0.68 & \textbf{0.72} & 0.67 & 0.68 & 0.73 & \textbf{0.74} & 0.68 & 0.69 & 0.72 & \textbf{0.74} & 0.67 & 0.70 & 0.72 & \textbf{0.79} & 0.68 & 0.72 & 0.72 & \textbf{0.77} & 0.66 & \textbf{0.74} & 0.70 & \textbf{0.74} \\ \hline Average & 0.63 & 0.64 & 0.68 & 0.73 & 0.65 & 0.66 & 0.70 & 0.72 & 0.68 & 0.72 & 0.72 & 0.76 & 0.65 & 0.70 & 0.72 & 0.76 & 0.62 & 0.67 & 0.69 & 0.73 & 0.62 & 0.68 & 0.66 & 0.77 \\ \hline \end{tabular}% \label{tab:purity}% \end{table}% \end{landscape} We conduct a Friedman test with the post-hoc Nemenyi test~\citep{demvsar2006statistical} to examine whether the difference in \textit{Dendrogram Purity} of any two measures is significant. Those four measures (used in an algorithm) are ranked based on their \textit{Dendrogram Purity} on each dataset, where the best one is rank $1$ and so on. Then the critical difference (CD) is computed using the post-hoc Nemenyi test. Two measures are significantly different if the difference in their average ranks is larger than CD. Figure \ref{fig:NemenyitestP} shows that IK is significantly better than all other measures for every algorithm. \begin{figure}[t] \centering \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/Psingle.pdf} \caption{Single-linkage AHC} \label{NemenyitestP:single} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/Pcomplete.pdf} \caption{Complete-linkage AHC} \label{NemenyitestP:complete} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/Paverage.pdf} \caption{Average-linkage AHC} \label{NemenyitestP:average} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/Pweight.pdf} \caption{Weighted-linkage AHC} \label{NemenyitestP:weighted} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/Phdbsan.pdf} \caption{HDBSCAN} \label{NemenyitestP:hdbscan} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/Ppha.pdf} \caption{PHA} \label{NemenyitestP:pha} \end{subfigure} \caption{Critical difference (CD) diagram of the post-hoc Nemenyi test ($\alpha=0.10$) for dendrogram purity. Two measures are not significantly different if there is a line linking them.} \label{fig:NemenyitestP} \end{figure} \subsection{Flat Clustering Evaluation} To evaluate the flat clustering results, we use the original cluster extraction method in each algorithm, and compare the extracted clusters with ground truth cluster using $F1$ score which is a trade-off between the \textit{Precision} and \textit{Recall}~\citep{Rijsbergen1979,larsen1999fast,aliguliyev2009performance}. Note that we use a global cut for T-AHC to extract the $k$ subclusters on the dendrogram. Given a clustering result, the \textit{precision} score $P_{i}$ and the \textit{recall} score $R_{i}$ for each cluster $C_{i}$ are calculated based on the confusion matrix, and the $F1$ score of $C_{i}$ is the harmonic mean of $P_{i}$ and $R_{i}$. The Hungarian algorithm~\citep{kuhn1955hungarian} is used to search the optimal match be between the clustering results and ground-truth clusters. The overall $F1$ score is the unweighted average overall matched clusters as: \begin{equation}\label{eq:f1} F1 = \frac{1}{k}\sum_{i=1}^{k}\frac{2 \times P_i \times R_i}{P_i+R_i} \end{equation} Note that other evaluation measures such as Purity \citep{manning2010introduction} and Adjusted Mutual Information \citep{vinh2010information} do not take into account noise points identified by a clustering algorithm. They are not suitable for HDBSCAN in the evaluation section because these scores can provide a misleadingly good clustering result when HDBSCAN assigns many points to noise. Table~\ref{tab:perf} reports the experimental results of traditional AHC and other three algorithms. The key observations are: \begin{itemize} \item \textbf{Kernel improves the flat clustering performance of distance measure}. Every clustering algorithm which employs a kernel has better or equivalent clustering performance than that using distance in terms of average $F1$ score shown in the last row in Table~\ref{tab:perf}. The only exception is GDL, where Gaussian Kernel is marginally worse than distance. Even in GDL, IK and AGK are always better than distance (except on thyroid and lung only). \item \textbf{Among three kernels, Isolation Kernel (IK) produces the best $F1$ Score}. This occurs on all datasets, and on every algorithm. The only exception is with complete-linkage AHC on musk where IK is better than AGK but worse than GK). IK has the best $F1$ on 17-18 out of the 19 datasets for every clustering algorithm. The best contender is AGK which has the best $F1$ on 1-3 datasets on four algorithms, but it produced no best $F1$ on complete-linkage AHC \item \textbf{IK produced a huge performance gap in $F1$ on some datasets}, even compared with other kernels. For example, (i) tyroid, WDBC, LSVT, Isolet and lung using single-linkage AHC; (ii) thyroid, spam, control, musk and ALLAML using HDBSCAN; (iii) LandCover and Isolet using PHA. \end{itemize} It is interesting to note that Isolation Kernel achieves the largest performance improvement over distance on almost all datasets for all algorithms. In addition, using IK in Complete-linkage AHC, PHA and GDL allow all these algorithms to produce similar average $F1$ score. In contrast, using AGK only allows Complete-linkage and GDL to produce similar average $F1$ score; and using GK in these two algorithms makes little difference or worse average $F1$ score than those using distance. \begin{landscape} \begin{table}[!htb] \small \renewcommand{\arraystretch}{1} \setlength{\tabcolsep}{1.2pt} \centering \caption{Clustering results in $F1$ score. A larger $F1$ score indicates a better clustering result. The best result on each dataset is boldfaced.} \begin{tabular}{|c|cccc|cccc|cccc|cccc|cccc|cccc|cccc|} \hline \multirow{2}[0]{*}{Dataset} & \multicolumn{4}{c|}{Single-linkage AHC} & \multicolumn{4}{c|}{Complete-linkage AHC} & \multicolumn{4}{c|}{Average-l AHC} & \multicolumn{4}{c|}{Weighted-l AHC} & \multicolumn{4}{c|}{PHA} & \multicolumn{4}{c|}{HDBSCAN} & \multicolumn{4}{c|}{GDL} \\ \cline{2-29} & Dis & G & AG & IK & Dis & G & AG & IK & Dis & G & AG & IK & Dis & G & AG & IK & Dis & G & AG & IK & Dis & G & AG & IK & Dis & G & AG & IK \\ \hline \multicolumn{1}{|c|}{banknote} & 0.95 & 0.95 & \textbf{0.99} & \textbf{0.99} & 0.60 & 0.60 & 0.79 & \textbf{0.81} & 0.61 & 0.97 & 0.77 & \textbf{0.99} & 0.62 & 0.86 & 0.73 & \textbf{0.94} & 0.68 & 0.74 & 0.78 & \textbf{0.96} & 0.69 & 0.69 & 0.94 & \textbf{0.95} & 0.98 & 0.91 & \textbf{0.99} & \textbf{0.99} \\ \multicolumn{1}{|c|}{thyroid} & 0.58 & 0.58 & 0.76 & \textbf{0.91} & 0.80 & 0.80 & 0.95 & \textbf{0.96} & 0.73 & 0.73 & \textbf{0.95} & 0.91 & 0.75 & 0.75 & 0.93 & \textbf{0.95} & 0.55 & 0.59 & 0.85 & \textbf{0.86} & 0.57 & 0.59 & 0.58 & \textbf{0.78} & \textbf{0.91} & 0.73 & 0.71 & 0.84 \\ \multicolumn{1}{|c|}{seeds} & 0.54 & 0.54 & 0.90 & \textbf{0.91} & 0.85 & 0.85 & 0.89 & \textbf{0.94} & 0.89 & 0.89 & 0.93 & \textbf{0.94} & 0.81 & 0.85 & 0.91 & \textbf{0.92} & 0.90 & 0.90 & 0.92 & \textbf{0.93} & 0.61 & 0.58 & 0.82 & \textbf{0.83} & 0.88 & 0.88 & 0.92 & \textbf{0.93} \\ \multicolumn{1}{|c|}{diabetes} & 0.40 & 0.40 & 0.44 & \textbf{0.50} & 0.53 & 0.53 & 0.68 & \textbf{0.70} & 0.61 & 0.61 & 0.64 & \textbf{0.65} & 0.49 & 0.59 & 0.69 & \textbf{0.65} & 0.44 & 0.59 & 0.58 & \textbf{0.63} & 0.42 & 0.47 & 0.43 & \textbf{0.52} & 0.53 & 0.52 & 0.59 & \textbf{0.63} \\ \multicolumn{1}{|c|}{vowel} & 0.08 & 0.12 & 0.27 & \textbf{0.31} & 0.29 & 0.29 & 0.33 & \textbf{0.34} & 0.28 & 0.31 & 0.33 & \textbf{0.37} & 0.27 & 0.32 & 0.35 & \textbf{0.37} & 0.12 & 0.25 & 0.33 & \textbf{0.35} & 0.24 & 0.27 & 0.32 & \textbf{0.33} & 0.31 & 0.30 & 0.31 & \textbf{0.36} \\ \multicolumn{1}{|c|}{wine} & 0.56 & 0.57 & \textbf{0.92} & \textbf{0.92} & 0.94 & 0.94 & 0.95 & \textbf{0.98} & 0.93 & 0.96 & 0.96 & \textbf{0.97} & 0.87 & 0.92 & 0.96 & \textbf{0.98} & 0.58 & 0.59 & 0.93 & \textbf{0.95} & 0.51 & 0.55 & 0.82 & \textbf{0.91} & 0.92 & 0.92 & \textbf{0.97} & \textbf{0.97} \\ \multicolumn{1}{|c|}{shape} & 0.44 & 0.52 & 0.75 & \textbf{0.77} & 0.64 & 0.66 & 0.74 & \textbf{0.78} & 0.63 & 0.68 & \textbf{0.76} & \textbf{0.76} & 0.67 & 0.68 & 0.74 & \textbf{0.77} & 0.64 & 0.65 & \textbf{0.76} & \textbf{0.76} & 0.68 & 0.68 & \textbf{0.71} & \textbf{0.71} & 0.70 & 0.66 & 0.71 & \textbf{0.74} \\ \multicolumn{1}{|c|}{Segment} & 0.34 & 0.36 & 0.55 & \textbf{0.66} & 0.65 & 0.65 & 0.73 & \textbf{0.75} & 0.53 & 0.58 & 0.73 & \textbf{0.79} & 0.55 & 0.60 & 0.72 & \textbf{0.76} & 0.39 & 0.71 & 0.73 & \textbf{0.75} & 0.61 & 0.60 & \textbf{0.69} & 0.63 & 0.42 & 0.45 & 0.78 & \textbf{0.82} \\ \multicolumn{1}{|c|}{WDBC} & 0.40 & 0.67 & 0.40 & \textbf{0.93} & 0.77 & 0.77 & 0.92 & \textbf{0.95} & 0.87 & 0.91 & 0.91 & \textbf{0.95} & 0.79 & 0.88 & 0.92 & \textbf{0.96} & 0.40 & 0.41 & 0.88 & \textbf{0.94} & 0.41 & 0.54 & 0.71 & \textbf{0.91} & 0.94 & 0.94 & 0.95 & \textbf{0.96} \\ \multicolumn{1}{|c|}{spam} & 0.38 & 0.38 & 0.38 & \textbf{0.42} & 0.42 & 0.51 & 0.64 & \textbf{0.73} & 0.38 & 0.38 & 0.66 & \textbf{0.77} & 0.39 & 0.52 & 0.74 & \textbf{0.80} & 0.38 & 0.38 & 0.70 & \textbf{0.71} & 0.28 & 0.35 & 0.48 & \textbf{0.87} & 0.38 & 0.38 & 0.69 & \textbf{0.74} \\ \multicolumn{1}{|c|}{control} & 0.23 & 0.23 & 0.60 & \textbf{0.79} & 0.75 & 0.75 & 0.84 & \textbf{0.86} & 0.71 & 0.73 & 0.86 & \textbf{0.87} & 0.72 & 0.74 & 0.82 & \textbf{0.84} & 0.46 & 0.63 & 0.73 & \textbf{0.81} & 0.32 & 0.57 & 0.58 & \textbf{0.76} & 0.76 & 0.76 & \textbf{0.95} & \textbf{0.95} \\ \multicolumn{1}{|c|}{hill} & 0.34 & 0.37 & \textbf{0.51} & 0.46 & 0.37 & 0.40 & 0.50 & \textbf{0.51} & 0.37 & 0.41 & \textbf{0.51} & \textbf{0.51} & 0.39 & 0.40 & 0.51 & \textbf{0.52} & 0.37 & 0.39 & 0.54 & \textbf{0.56} & 0.33 & 0.36 & 0.47 & \textbf{0.48} & 0.46 & 0.35 & 0.50 & \textbf{0.62} \\ \multicolumn{1}{|c|}{LandCover} & 0.16 & 0.08 & 0.18 & \textbf{0.36} & 0.59 & 0.60 & 0.64 & \textbf{0.65} & 0.36 & 0.55 & 0.72 & \textbf{0.74} & 0.58 & 0.67 & 0.67 & \textbf{0.72} & 0.08 & 0.41 & 0.49 & \textbf{0.70} & 0.18 & 0.28 & 0.39 & \textbf{0.55} & 0.62 & 0.61 & 0.74 & \textbf{0.75} \\ \multicolumn{1}{|c|}{musk} & 0.36 & \textbf{0.64} & 0.50 & 0.53 & \textbf{0.58} & \textbf{0.58} & 0.55 & 0.57 & 0.36 & 0.53 & 0.53 & \textbf{0.56} & 0.48 & \textbf{0.54} & \textbf{0.54} & \textbf{0.54} & 0.51 & 0.51 & 0.55 & \textbf{0.57} & 0.50 & 0.52 & 0.50 & \textbf{0.75} & 0.48 & 0.48 & 0.50 & \textbf{0.56} \\ \multicolumn{1}{|c|}{LSVT} & 0.40 & 0.49 & 0.44 & \textbf{0.67} & 0.40 & 0.55 & 0.58 & \textbf{0.65} & 0.40 & 0.60 & 0.58 & \textbf{0.62} & 0.40 & 0.61 & 0.60 & \textbf{0.62} & 0.40 & 0.42 & 0.67 & \textbf{0.68} & 0.15 & 0.42 & 0.42 & \textbf{0.59} & 0.51 & 0.51 & 0.60 & \textbf{0.63} \\ \multicolumn{1}{|c|}{Isolet} & 0.03 & 0.03 & 0.07 & \textbf{0.28} & 0.33 & 0.39 & 0.59 & \textbf{0.68} & 0.12 & 0.30 & 0.60 & \textbf{0.68} & 0.24 & 0.40 & 0.59 & \textbf{0.66} & 0.03 & 0.24 & 0.31 & \textbf{0.66} & 0.09 & 0.35 & 0.38 & \textbf{0.55} & 0.61 & 0.61 & 0.67 & \textbf{0.73} \\ \multicolumn{1}{|c|}{COIL20} & 0.28 & 0.33 & 0.96 & \textbf{0.97} & 0.39 & 0.46 & 0.71 & \textbf{0.73} & 0.24 & 0.56 & 0.77 & \textbf{0.90} & 0.27 & 0.71 & 0.80 & \textbf{0.92} & 0.44 & 0.49 & 0.73 & \textbf{0.76} & 0.84 & 0.84 & \textbf{0.95} & \textbf{0.95} & 0.86 & 0.86 & \textbf{0.87} & \textbf{0.87} \\ \multicolumn{1}{|c|}{lung} & 0.43 & 0.43 & 0.52 & \textbf{0.88} & 0.81 & 0.81 & 0.85 & \textbf{0.86} & 0.87 & 0.87 & 0.87 & \textbf{0.90} & 0.87 & 0.91 & 0.88 & \textbf{0.94} & 0.42 & 0.61 & 0.78 & \textbf{0.96} & 0.23 & 0.58 & 0.68 & \textbf{0.76} & 0.91 & 0.91 & 0.90 & \textbf{0.94} \\ \multicolumn{1}{|c|}{ALLAML} & 0.46 & 0.47 & 0.61 & \textbf{0.75} & 0.62 & 0.62 & 0.74 & \textbf{0.75} & 0.57 & 0.61 & 0.74 & \textbf{0.75} & 0.53 & 0.63 & 0.72 & \textbf{0.82} & 0.46 & 0.49 & 0.72 & \textbf{0.75} & 0.36 & 0.49 & 0.53 & \textbf{0.73} & 0.60 & 0.60 & 0.72 & \textbf{0.78} \\ \hline Average & 0.39 & 0.43 & 0.57 & 0.69 & 0.60 & 0.62 & 0.72 & 0.75 & 0.55 & 0.64 & 0.73 & 0.77 & 0.56 & 0.66 & 0.73 & 0.77 & 0.43 & 0.53 & 0.68 & 0.75 & 0.42 & 0.51 & 0.60 & 0.71 & 0.67 & 0.65 & 0.74 & 0.78 \\ \hline \end{tabular}% \label{tab:perf}% \end{table}% \end{landscape} \begin{figure}[t] \centering \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/single.pdf} \caption{Single-linkage AHC} \label{fig:single} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/Compelte.pdf} \caption{Complete-linkage AHC} \label{fig:complete} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/average.pdf} \caption{Average-linkage AHC} \label{fig:average} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/Weight.pdf} \caption{Weighted-linkage AHC} \label{fig:weighted} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/DBscan.pdf} \caption{HDBSCAN} \label{fig:hdbscan} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/GDL.pdf} \caption{GDL} \label{fig:gdl} \end{subfigure} \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{figure/Catedata/Nemenyi/pha.pdf} \caption{PHA} \label{fig:pha} \end{subfigure} \caption{Critical difference (CD) diagram of the post-hoc Nemenyi test ($\alpha=0.10$) for $F1$ scores. Two measures are not significantly different if there is a line linking them.} \label{fig:Nemenyitest} \end{figure} We also conduct a Friedman test with the post-hoc Nemenyi test to examine whether the difference in $F1$ scores of any two measures is significant. As shown in Figure~\ref{fig:Nemenyitest}, IK is significantly better than all other measures for every algorithm. This result provides further evidence of the superiority of IK wrt the clustering performance reported in the previous study where IK improves DBSCAN clustering results on datasets with varied densities \citep{qin2019nearest}. \subsection{Computational complexity comparison} Table \ref{tab:complexity} compares the time and space complexities of different clustering algorithms and similarity measures.\footnote{Here we use the distance matrix as the input for each algorithm to save running time. When data points are available, the space complexity of all algorithms can be reduced to $\mathcal{O}(n)$. } Basically, all four measures have similar computational complexities. The runtime comparison on four datasets is shown in Table \ref{tab:runtime}. Note that the runtime of IK is slightly higher than the other two kernels because it is an ensemble method. However, this is not an issue because the Voronoi diagram implementation of IK is amenable to GPU acceleration \citep{qin2019nearest}. \begin{table}[!htb] \centering \caption{Time and space complexities of AHC algorithms and distance/kernel functions. $t$ and $\psi$ in IK are the ensemble size and subsample size, respectively. } \begin{tabular}{|c|c|c|} \hline Algorithm & Time complexity & Space complexity\\ \hline Single-linkage AHC & $\mathcal{O}\left(n^{2}\right)$ & $\mathcal{O}\left(n^{2}\right)$ \\ Complete-linkage AHC & $\mathcal{O}\left(n^{2}\log n\right)$ & $\mathcal{O}\left(n^{2}\right)$ \\ GDL & $\mathcal{O}\left(n^{3}\right)$ & $\mathcal{O}\left(n^{2}\right)$\\ PHA & $\mathcal{O}\left(n^{2}\right)$ & $\mathcal{O}\left(n^{2}\right)$ \\ Average & $\mathcal{O}\left(n^{2}\log n\right)$ & $\mathcal{O}\left(n^{2}\right)$ \\ Weighted & $\mathcal{O}\left(n^{2}\log n\right)$ & $\mathcal{O}\left(n^{2}\right)$ \\ HDBSCAN & $\mathcal{O}\left( n^{2}\right)$ & $\mathcal{O}\left( n^{2}\right)$\\ \hdashline Distance or GK & $\mathcal{O}\left(n^{2}\right)$ & $\mathcal{O}\left(n^{2}\right)$ \\ AGK & $\mathcal{O}\left(n^{2}\right)$ & $\mathcal{O}\left(n^{2}\right)$ \\ IK & $\mathcal{O}\left( tn\psi+n^{2}\right)$ & $\mathcal{O}\left(t \psi+ n^{2}\right)$ \\ \hline \end{tabular}% \label{tab:complexity}% \end{table}% \begin{table}[!htb] \centering \caption{Execution time (in CPU seconds) on a machine with an i7-7820X 3.60GHz processor and 32GB RAM} \begin{tabular}{|c|rrrr|rrrr|} \hline \multirow{2}[4]{*}{Dataset} & \multicolumn{4}{c|}{Single-linkage AHC} & \multicolumn{4}{c|}{HDBSCAN} \\ \cline{2-9} & \multicolumn{1}{c}{Dis} & \multicolumn{1}{c}{GK} & \multicolumn{1}{c}{AGK} & \multicolumn{1}{c|}{IK} & \multicolumn{1}{c}{Dis} & \multicolumn{1}{c}{GK} & \multicolumn{1}{c}{AGK} & \multicolumn{1}{c|}{IK} \\ \hline WDBC & .00 & .01 & .01 & .08 & .03 & .04 & .04 & .07 \\ Banknote & .02 & .05 & .06 & .30 & .13 & .15 & .20 & .32 \\ Segment & .06 & .13 & .20 & .93 & .44 & .48 & .61 & .98 \\ Spam & .28 & .59 & .86 & 3.57 & 1.76 & 1.86 & 2.45 & 3.87 \\ \hline \end{tabular}% \label{tab:runtime}% \end{table}% \newpage \section{Conclusions}~\label{sec:conclusion} We formally establish the condition with which a linkage function must comply before it would allow an AHC to successfully separate clusters in a dataset. We also formally define a concept called {\em entanglement} in a dendrogram to explain the severity of linking across different clusters during the merging process in the AHC. Two indicators, i.e., the number of entanglements and the average entanglement level, are shown to be highly correlated to an objective measure of goodness of dendrogram called dendrogram purity. These formal definitions have allowed us to analyse an often overlooked/ignored bias in T-AHC: existing T-AHC to have a bias towards linking points in dense cluster first, before linking points in the sparse cluster. As we contend that the root cause of this bias is due to the distance/similarity used being data-independent, the use of a well-defined \emph{data-dependent kernel called Isolation Kernel} has been shown to reduce this bias significantly. While the analysis was conducted with respect to T-AHC only, we propose to use Isolation Kernel to replace distance in existing distance-based AHC algorithms as a generic approach to improve their dendrograms. This approach differs from existing approaches which focus on a tailored-made linkage function for a specific algorithm. We show that the proposed approach works for four existing clustering algorithms without the need to modify their linkage functions or algorithms, except the replacement of distance with Isolation Kernel. Our empirical evaluation verifies that Isolation Kernel is a better measure than distance and two existing popular kernels, Gaussian Kernel and adaptive Gaussian Kernel, on four AHC algorithms, i.e., T-AHC, HDBSCAN \citep{campello2013density}, GDL~\citep{zhang2012graph} and PHA~\citep{lu2013pha}. \clearpage \bibliographystyle{elsarticle-num}
{'timestamp': '2020-10-13T02:29:07', 'yymm': '2010', 'arxiv_id': '2010.05473', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05473'}
arxiv
\section{Introduction} Orthodontic tooth movement is the result of alveolar bone remodeling caused by the applied forces and deformations in the periodontium. Finite element models (FEMs) is widely used to assess stress/strain in the alveolar bone and periodontal ligament (PDL), the fibrous connective tissue between tooth and bone, in the orthodontic treatments \cite{cattaneo2005finite,chen2014periodontal,savignano2016nonlinear,likitmongkolsakul2018development,hamanaka2017numeric,kawamura2019biomechanical}. Moreover, the initial and long-term tooth movements can be investigated using these models. In this work, we use an FEM to provide a biomechanical model of the full mandibular dentition focusing on initial teeth displacements caused by the applied load on the teeth (see \Cref{fig:population_mesh} and \Cref{fig:Tooth_PDE}). We generate patient-specific FEMs for three patients by segmenting the cone-beam computed tomography (CBCT) scans of the patients. The models are provided by using the same boundary conditions under the same scenarios. In each scenario, an identical force magnitude is applied perpendicular to the surface of each tooth to mimic an uncontrolled tipping movement. Besides, the load magnitude can change from \SIrange{0.3}{1}{\newton} with \SIlist{0.1}{\newton} increments, and teeth transformations are recorded for all teeth of each patient. Finally, the results are compared with the corresponding teeth of other patients. \begin{figure*}[t] \centering \includegraphics[width=0.92\textwidth]{images_jpg/Population_mesh.jpg} \vspace{-0.15cm} \caption{FEMs and meshes for three patients, and mesh quality histograms for the PDL of the left canine. \textbf{A:} The volume-edge ratio, \textbf{B:} The radius ratio, \textbf{C:} The radius-edge ratio, \textbf{D:} A metric introduced in \cite{freitag1997tetrahedral}.} \label{fig:population_mesh} \vspace{-0.3cm} \end{figure*} Our hypothesis is that variations in the teeth anatomy of different patients and the load magnitudes can affect the resulting tooth displacement. Therefore, in this study, tooth movements (i.e., rotation and translation) are estimated as nonlinear functions of both load and the ratio of crown height to root volume using the obtained biomechanical models. \section{Related Work} The performance of the orthodontic treatments can be improved if the movement of the teeth could be predicted in a reliable way. Therefore, many studies have focused on predicting tooth movements in orthodontic treatments using FEMs. In general, the tooth movement occurs in two phases \cite{hamanaka2017numeric}. In the first phase \cite{liang2009torque,cattaneo2008moment,cattaneo2005finite,savignano2016nonlinear}, which is the main focus of this study, tooth moves within the PDL space in few seconds after applying a force \cite{li2018orthodontic}. This movement is substantially due to the deformation of the PDL tissue caused by the applied load. In the second phase \cite{likitmongkolsakul2018development,hamanaka2017numeric,kawamura2019biomechanical,likitmongkolsakul2018development,chen2014periodontal}, the resulting stress in the PDL and bone tissue causes a bone remodeling process, where the bone is resorbed and formed in the compressed and stretched regions of the PDL, respectively. In the context of FE-based modeling of the initial tooth movement, some studies \cite{cattaneo2008moment,savignano2016nonlinear} have investigated different types of movements individually including bodily movement, controlled tipping, and uncontrolled tipping. Some others have explored the teeth mesialization, distalization, or retraction scenarios \cite{liang2009torque,kawamura2019biomechanical,likitmongkolsakul2018development,park2017biomechanical}. These studies have considered the effect of the force direction \cite{savignano2016nonlinear,kawamura2019biomechanical}, moment-to-force \cite{cattaneo2008moment,savignano2016nonlinear}, and force magnitude \cite{melsen2007importance,cattaneo2008moment} on tooth transformation \cite{cattaneo2008moment,kawamura2019biomechanical,park2017biomechanical} or location of the center of rotation \cite{cattaneo2008moment,savignano2016nonlinear}. However, the jaw model, force system, and number of teeth used in the analyses are not consistent. For example, \cite{cattaneo2008moment,savignano2016nonlinear} used a small portion of jaw, while \cite{huang2020mandible} worked on a fully segmented jaw model. Likewise, different studies have examined different number of teeth, e.g., using a single tooth \cite{savignano2016nonlinear}, two \cite{cattaneo2008moment,liang2009torque} or more \cite{kawamura2019biomechanical,park2017biomechanical}. The force and/or moments have also been applied to different parts including the surface of tooth \cite{cattaneo2008moment,liang2009torque}, center of the resistance \cite{savignano2016nonlinear}, and orthodontic appliances \cite{kawamura2019biomechanical,likitmongkolsakul2018development}. The abovementioned biomechanical models, however, might not be applicable for analyzing different teeth motions obtained from multiple patients. In other words, the obtained tooth displacement results represented only by visualizing the displacement fields \cite{liang2009torque,park2017biomechanical}, measuring the displacement of the selected landmarks \cite{cattaneo2008moment,park2017biomechanical}, or acquiring the translations/rotations using some predefined measurement points \cite{kawamura2019biomechanical} lack useful information about different tooth motion tendencies for full dentition of multiple patients and, hence, are less interpretable when it comes to the across patients modeling analyses. Moreover, existing FEMs applied in computational orthodontics are mostly limited to a single patient \cite{cattaneo2008moment,liang2009torque,savignano2016nonlinear,kawamura2019biomechanical,huang2020mandible,park2017biomechanical}. Although Likitmongkolsakul et al. \cite{likitmongkolsakul2018development} propose a stress-movement function of a canine for two orthodontic patients under an identical scenario, to the best of our knowledge, there are no other studies considering multiple patients for tooth movement modeling. In this work, by considering the biomechanical models of human mandible acquired from CBCT scans of three patients, we investigate the tooth movement variations in multiple patients using rigid body transformations under different load magnitudes. To the best of our knowledge, this is the first computational model in orthodontics applied to three different patients. Our experiments consist of both intra- and inter-patient analyses. Considering teeth motions under an identical scenario, both in intra-patient and inter-patient analyses, helps us to obtain a general pattern for the movement of different teeth using patient-specific teeth and bone geometries. \section{Setting up the Finite Element Model} This section describes different consecutive steps that are conducted to generate a patient-specific FEM of the human mandible. First, the geometry reconstruction takes place by segmenting the CBCT scan of the patient. Second, the surface mesh of the obtained geometries are re-meshed and a volumetric mesh is generated for each geometry. Next, the resulting volumetric meshes are imported into a finite element (FE) framework to set up the FE problem. The details of the biomechanical model, e.g., boundary conditions, contact definitions, and utilized material models are presented in this section. Finally, the model is numerically verified by using mesh convergence study and parameter sensitivity analysis. Segmentation is performed using 3D Slicer \cite{fedorov20123d} based on a semi-automatic watershed algorithm applied to the bone and teeth. Next, the wrongly segmented regions are modified to obtain the final segmentation result. Since the resolution of the orthodontic scans with a voxel size of \SI[product-units=single]{0.3 x 0.3 x 0.3}{mm^3} is not high enough for segmenting the thin PDL tissue ($\approx$ \SIlist{0.2}{\milli\metre} width) from the scans, the PDL layer is generated with a uniform width of \SIlist{0.2}{\milli\metre} around each tooth root as shown in \Cref{fig:population_mesh}. We select three patients' scans of various crown height, root length, and teeth sizes, to ensure having enough geometrical variations. Each segmentation result is later verified by an orthodontic expert. The segmented geometries are exported as surface meshes in STL files. These meshes are decimated and re-meshed using Meshmixer \cite{Meshmixer} to provide high-quality surface meshes. Uniform meshes are used for teeth and PDL geometries. \Cref{table:model_params} presents the edge length of the triangular meshes for each component. For bone geometry, an adaptive mesh is generated in which the edge length of the surface mesh triangles varies between \SIlist{0.4}{\milli\metre} and \SIlist{2}{\milli\metre} from the neighboring regions to the PDL and the bottom region of the mandible. Utilizing an adaptive mesh helps us to obtain a finer mesh in the regions of interest, and consequently, an accurate result in the FE analysis, yet reducing the total number of elements. \begin{table}[!b] \centering \renewcommand{\arraystretch}{1.5} \caption{Summary of the materials and mesh properties.} \label{table:model_params} \resizebox{\textwidth}{!}{% \begin{tabular}{l|l|cc|lclrl} \hline & \multirow{2}{*}{Material model} & \multicolumn{2}{c|}{Material properties} & & Mesh Properties & & \multicolumn{1}{l}{} & \textbf{} \\ \cline{3-4} \cline{5-9} & & \begin{tabular}[c]{@{}c@{}}Young's Modulus\\ (MPa)\end{tabular} & \begin{tabular}[c]{@{}c@{}}Poisson's Ratio\\ (-)\end{tabular} & & \begin{tabular}[c]{@{}c@{}}Surface mesh \\ edge length (mm)\end{tabular} & & \multicolumn{1}{l}{\begin{tabular}[c]{@{}l@{}}Number of\\ tetrahedra\end{tabular}} & \textbf{} \\ \hline Tooth & Rigid Body & - & - & & 0.4 & & 8,000 & \multirow{4}{*}{} \\ Bone & Isotropic elastic & $1.5\times10^{3}$ & 0.3 & & \begin{tabular}[c]{@{}c@{}}Adaptive mesh\\ (from 0.4 to 2)\end{tabular} & & 3,255,000 & \\ \cline{3-4} & & $C_1$ (\SIlist{}{\mega\pascal}) & $C_2$ (\SIlist{}{\mega\pascal}) & & & \multicolumn{1}{l}{} & & \\ \cline{3-4} PDL & Mooney-Rivlin $^*$ & 0.011875 & 0 & & 0.1 & & 90,700 & \\ \hline \end{tabular}% } \begin{tablenotes} \item{\footnotesize $^{*}$ $C_2 = 0$ reduces the Mooney-Rivlin material to uncoupled Neo-hookean. The values assigned for $C_1$ and $C_2$ correspond to the Young’s modulus and Poisson's ratio of \SIlist{0.0689}{\mega\pascal} and $0.45$, respectively.} \end{tablenotes} \vspace{-0.2cm} \end{table} \begin{figure}[t] \centering \includegraphics[width=0.98\linewidth]{images_jpg/ToothComplex_PDE.jpg} \vspace{-0.1cm} \caption{A closeup view of the tooth supporting complex. The contacts between different domains and boundary conditions are presented. Tooth ($\Omega_{T}$), Periodontal ligament ($\Omega_{P}$), Alveolar bone ($\Omega_{B}$), Tooth-PDL contact ($\Gamma_{T,P}$), PDL-Bone contact ($\Gamma_{P,B}$) and a Dirichlet boundary condition ($\Gamma_{D}$) are shown.} \label{fig:Tooth_PDE} \vspace{-0.4cm} \end{figure} High quality volumetric meshes are generated for each surface mesh using TetGen \cite{TetGen}, by defining an upper limit for the radius-edge ratio of to-be-generated tetrahedra. This mesh quality constraint controls the ratio between the radius of the circumscribed sphere and the shortest edge of each tetrahedron, which prevents the production of low-quality (badly shaped) tetrahedra. Later, four different mesh quality measurements presented in \cite{shewchuk2002good}, i.e., the volume-edge ratio \cite{misztal2013multiphase,liu1994relationship}, the radius-edge ratio \cite{baker1989element}, and the radius ratio \cite{caendish1985apporach,freitag1997tetrahedral} are chosen to verify the quality of the generated 4-noded tetrahedral meshes (TET4) (see the quality histograms in \Cref{fig:population_mesh}). Finally, the obtained meshes are used to set up and solve the FE problem. For reproducibility, we generate and solve the computational biomechanical models in FEBio software package \cite{FEBio} which is an open-source software for nonlinear FEA in biomechanics. A nonlinear quasi-static simulation is performed to analyze the teeth displacements in each FE model. The different domains of the FEM, material properties, contact types, boundary conditions and the applied load are summarized in \Cref{fig:Tooth_PDE}. To simplify the proposed model, the tooth domain is assumed as rigid-body with 6 degrees of freedom. The center of mass for each tooth is calculated automatically using FEBio based on a predefined density parameter \cite{FEBioUserManual}. Furthermore, since the deformation of the bone tissue is negligible under the orthodontic forces, no distinction is made for the cortical and trabecular bone \cite{ziegler2005numerical,qian2009deformation}, and an isotropic elastic material model is used for the homogeneous bone geometry. The importance of the PDL tissue in transferring loads from the tooth to the alveolar bone has been shown in the literature \cite{mccormack2014biomechanical,ortun2018approach,cattaneo2005finite}. Accordingly, the PDL tissue is included in our model as a thin layer of finite elements \cite{ortun2018approach,hohmann2011influence,cattaneo2005finite,savignano2016nonlinear}. This allows for investigating the stress/strain field in the PDL, e.g., using data-driven models, that can later be used in the bone remodeling process \cite{chen2014periodontal}. Moreover, several studies have characterized the biomechanical behavior of the PDL tissue \cite{dorow2003determination,uhlir2016biomechanical,qian2009deformation}, some of which have suggested the Mooney-Rivlin Hyperelastic (MRH) model for the PDL \cite{qian2009deformation,uhlir2016biomechanical}. In this study, an MRH material model is used for the PDL domain based on the parameter values reported in \Cref{table:model_params}. The Tooth-PDL interface and PDL-Bone interface are fixed in both normal and tangent directions using a Neuman condition (see \Cref{fig:Tooth_PDE}). In addition, all elements at the bottom surface of the bone ($\Gamma_{D}$) are fixed in all directions by applying a Dirichlet boundary condition. To mimic the uncontrolled tipping scenario, a pressure load is applied perpendicular to the labial/buccal surface of the tooth crown, as shown in \Cref{fig:Tooth_PDE}. The area under the load, which represents the area under the orthodontic bracket, is set to the center of the teeth crowns. To ensure that the same force magnitude is applied to the teeth, the area under the load is measured separately for each tooth. Next, the corresponding pressure value for the desired force magnitude is calculated and used as the \textit{pressure load} in FEBio. An identical force magnitude is exerted to all teeth simultaneously in order to investigate the tooth movement variations of the mandibular teeth across the three patients. The model is then verified by studying the mesh convergence and parameters sensitivities. The final resolution of the mesh is defined in the mesh convergence study process where the total number of elements, except for the rigid body teeth, is iteratively increased by a factor of 2 until the relative error is less than 4\% of the maximum stress (see \Cref{fig:Conv_study_models}). The number of tetrahedra in the refined mesh is presented in \Cref{table:model_params}. The parameter sensitivity study, summarized in \Cref{table:sensitivity}, is done on the material parameters of different tissues and the parameters used for the tied contact in the PDL-bone interface. \begin{figure}[t] \centering \includegraphics[width= 0.8\linewidth]{images_jpg/MeshConv_models.jpg} \vspace{-0.1cm} \caption{Mesh convergence study showing the Von Mises stress in the bone geometry under the same boundary conditions. \textbf{A to D:} The model with $N$ (coarse), $2N$, $4N$, and $8N$ elements. The stress fields are consistent in the finer models.} \label{fig:Conv_study_models} \end{figure} \begin{table}[!t] \renewcommand{\arraystretch}{1.4} \centering \caption{Summary of parameter sensitivity analysis conducted on the model.} \label{table:sensitivity} \resizebox{\textwidth}{!}{% \begin{tabular}{c|c|c|c|c|c|c} \hline \multirow{2}{*}{} & \multicolumn{2}{c|}{PDL} & \multicolumn{2}{c|}{Bone} & \multicolumn{2}{c}{PDL-Bone Tied Contact} \\ \cline{2-7} & Young's Modulus & Poisson's Ratio & Young's Modulus & Poisson's Ratio & \begin{tabular}[c]{@{}c@{}}Augmented\\ Lagrangian\end{tabular} & Penalty Factor \\ \hline \multicolumn{1}{l|}{\begin{tabular}[c]{@{}c@{}}Interval of \\ parameter change\end{tabular}} & 0.044 - 0.0938 & 0.45 - 0.49 & 1200 - 13700 & 0.2 - 0.4 & 0.2 - 0.1 & 0.25 - 1.75 \\ \hline \begin{tabular}[c]{@{}c@{}}Relative difference in\\ Von Mises stress (\%)\end{tabular} & 2.127 & 2.127 & 0.709 & 3.900 & 1.418 & 3.900 \\ \hline \end{tabular}% } \end{table} \section{Experiments and Results} This section describes the experimental setup under the uncontrolled tipping scenario among the three patients. First, the obtained results are presented and discussed. Next, we propose two functions that describe the translation and rotation of different tooth types of the patients based on tooth IDs and selected clinical biomarkers, i.e., crown height and root volume. In order to have a comprehensive inter-patient analysis, we select the patients with roughly the same number of teeth. We use the intraoral scan of each patient, captured by the 3Shape Trios scanner \cite{3ShapeTrios}, to obtain the crown height of each tooth. Therefore, we ensure that the intraoral optical scans are available for all patients, and the CBCT scans have sufficient quality for performing the segmentation. \Cref{fig:trios} shows an intraoral scan of a patient and illustrates how the crown height is obtained for a tooth. \begin{figure}[!t] \vspace{-0.4cm} \centering \includegraphics[width=0.45\linewidth]{images_jpg/Trios.jpg} \vspace{-0.2cm} \caption{An intraoral scan of a patient and the obtained crown height for a tooth.} \label{fig:trios} \vspace{-0.3cm} \end{figure} In each scenario, an identical force magnitude is applied perpendicular to the surface of each tooth. The load magnitude ($l$) varies from \SIrange{0.3}{1}{\newton} with \SIlist{0.1}{\newton} intervals. The displacement of each tooth is measured as the translation of center of the mass ($\vec t$) and rotation of the rigid body teeth (with angle $\theta$ and axis $\vec n$). Besides, in each simulation, we record the tooth ID ($k$), load magnitude, and the relevant biomarkers. \textit{Universal Numbering (UNN)} system is used for the tooth ID, where $k$ changes between $17$ and $32$ from the left third molar to the right third molar, respectively. \Cref{fig:result_regs} illustrates relation between the translation/rotation and applied load for different teeth of each patient. As can be seen, the translation magnitude of the mandibular incisors for an applied load of \SIlist{0.4}{\newton} changes from \SIrange{0.07}{0.11}{\milli\metre}, \SIrange{0.13}{0.18}{\milli\metre}, and \SIrange{0.24}{0.51}{\milli\metre}, for patient 1 through 3, respectively. These values are similar to the results of the clinical study done by Jones et al. \cite{jones2001validated}, where the obtained initial tooth movements ranged from \SIrange{0.012}{0.133}{\milli\metre} for maxillary incisors of ten patients under a constant load of \SIlist{0.39}{\newton} over one-minute cycles. The translation magnitude and rotation angle of the teeth can be described as the square root functions of the applied load, i.e., $t_{j,k} = \alpha_{t_{j,k}} \sqrt{l \,} + \beta_{t_{j,k}}$ and $\theta_{j,k} = \alpha_{\theta_{j,k}} \sqrt{l \,} + \beta_{\theta_{j,k}}$, where $\alpha_{t_{j,k}}$ and $\alpha_{\theta_{j,k}}$ are the translation/rotation function coefficients for the $k$-th tooth of the $j$-th patient, and $\beta_{t_{j,k}}$ and $\beta_{\theta_{j,k}}$ are the corresponding function intercepts which are nearly zero. This nonlinear relation between the displacement and load is in line with the experimental findings of the clinical study of \cite{christiansen1969centers} and numerical results of the biomechanical model of \cite{cattaneo2008moment}. However, the function coefficients vary across different patients' teeth, i.e., the values increase when moving from the molars to central incisors. \begin{figure}[t] \centering \includegraphics[width=0.99\linewidth]{images_jpg/trans_rot_p123.jpg} \vspace{-0.15cm} \caption{The translation magnitudes and rotation angles versus the applied load. A nonlinear square root regression model is applied to fit the data from each patient's tooth. \textbf{Top-row:} Translation magnitude, \textbf{Bottom-row:} Rotation angle, \textbf{Left to Right:} Patient 1 through 3.} \label{fig:result_regs} \vspace{-0.1cm} \end{figure} It can be deduced from \Cref{fig:result_regs} that the estimated coefficients of the nonlinear functions vary across different patients for the same tooth types. This finding is due to the fact that the initial tooth movement can be influenced by different factors such as tooth anatomical variations and surrounding alveolar bone and PDL layer. Additionally, the root length of tooth and its surrounding alveolar bone can affect the initial tooth movement, center of rotation, and center of the resistance \cite{tanne1991patterns}. The same behavior applies for the crown height. In other words, a specific tooth with a longer crown (or a shorter root) would experience more displacements than the same tooth with a shorter crown (or a longer root). However, the exact relationship between the crown/root size and tooth displacement is missing. Our hypothesis is that the intra- and inter-patient variations in crown and root size can influence the teeth movements of different patients. Therefore, we propose the ratio of crown height to root volume as the biomarker causing tooth movement variations together with the applied load. To investigate the abovementioned assumption, first, we analyze the estimated coefficients of the fit functions ($\alpha_{t_{j,k}}$ and $\alpha_{\theta_{j,k}}$) for each tooth type. We observe that the teeth on the right side of the mandible show the same movement patterns as the corresponding teeth on the left side, where the UNN of the left side teeth can be calculated by subtracting the UNN of the corresponding teeth on the right side from 49. This provides us with more data points for the fitting purpose. The estimated coefficients of the nonlinear translation-load functions of the different patients are shown per tooth ID in \Cref{fig:slopes}. Note that the right teeth IDs are reflected in the same plot using the corresponding left teeth IDs. \begin{figure}[t] \centering \includegraphics[width=0.95\linewidth]{images_jpg/trans_slopes_crownh_rootv.jpg} \caption{Teeth movement variations of the three patients. \textbf{Left:} The coefficients of the functions fitted to the translation-load data. \textbf{Right:} The proposed biomarker values estimated for each patient's teeth. The right teeth IDs are reflected using the corresponding left teeth IDs, which results in two curves per patient.} \label{fig:slopes} \vspace{-0.25cm} \end{figure} Second, the crown heights of teeth are extracted from the intraoral scan of each patient. These measured values are then divided by the root volumes of the corresponding teeth, in which the root volumes are calculated using the associated bounding boxes of the PDL geometries. \Cref{fig:slopes} illustrates the estimated biomarker values for each patient's tooth. The obtained ratios needs to be considered as a patient's tooth biomarker in the tooth displacement models of translation and rotation. Therefore, we investigate the relationship between the coefficients of the displacement functions and the proposed biomarker values. \Cref{fig:result_polys} shows the biomarker values versus coefficients of the teeth displacement functions (translation magnitude and rotation angle) for all patients' teeth. As it can be seen, the biomarker values and coefficients are in line with each other. For example, lower biomarker values and coefficients are associated with the molars while higher biomarker values and coefficients belongs to the incisors. The relation between the biomarker values and coefficients of the teeth displacements can also be described by the square root functions, i.e., $b_t = \lambda_t \sqrt{\alpha_t} + \gamma_t$ and $b_{\theta} = \lambda_{\theta} \sqrt{\alpha_{\theta}} + \gamma_{\theta}$, where $b_t$ and $b_{\theta}$ are the biomarker functions associated with the translation/rotation function coefficients $\alpha_t$ and $\alpha_{\theta}$, respectively. Hence, the tooth displacements (translation/rotation) will be seen as a nonlinear function of both load ($l$) and the proposed biomarker ($b$), wherein the displacement-load function coefficients are replaced with the biomarker values. In other words, to obtain a patient's tooth displacements $t_{j,k}$ and $\theta_{j,k}$ for an applied load, one only needs to obtain the function coefficients $\alpha_{t_{j,k}}$ and $\alpha_{\theta_{j,k}}$ based on the biomarker value of the specific tooth using the fits shown in \Cref{fig:result_polys}. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{images_jpg/trans_rot_fit.jpg} \caption{The biomarker values versus coefficients of the displacement functions (translation and rotation). In each case, the behavior of the data is explained by a square root function.} \label{fig:result_polys} \vspace{-0.2cm} \end{figure} \section{Summary and Conclusion} The main goal of this work was to introduce a computational analysis tool for investigating the influence of the teeth geometry of different patients on the resulting teeth movements. Three biomechanical models were generated for studying the tooth movement variations of three patients. Our study showed that a combination of two clinical biomarkers, i.e., crown height and root volume could affect the tooth displacement. Therefore, we proposed two nonlinear functions for predicting translation and rotation of different patients' teeth for any applied load magnitudes. Proposing such functions not only allows for generalizability of the model across different patients but also provides a way to avoid having multiple values for different teeth IDs. To the best of our knowledge, this is the first time a full dentition intra-patient and inter-patient tooth movement analyses have been considered. This study focused on modeling the movement of teeth under an uncontrolled tipping scenario applied to three patients. The work still can benefit from investigating different tooth movement types such as the crown tipping, root tipping, and pure translation applied to some more patients. \section{Acknowledgments} \begin{minipage}{0.15\textwidth} \vspace{-1.2cm} \includegraphics[width=\textwidth]{images_jpg/flag_yellow_high_250x166.jpg} \end{minipage}\hspace{10pt} \begin{minipage}{0.8\textwidth} This project has received funding from the European Union’s Horizon 2020 research and innovation programme under the Marie Sklodowska-Curie grant agreement No. 764644. This paper only contains the author's views and the Research Executive Agency and the Commission are not responsible for any use that may be made of the information it contains. \end{minipage} \FloatBarrier \bibliographystyle{splncs04}
{'timestamp': '2020-10-13T02:22:32', 'yymm': '2010', 'arxiv_id': '2010.05258', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05258'}
arxiv
\section{Introduction} Children with an immigrant background, including refugees, may have difficulties learning and speaking the local language. This can be a real issue when the children begin in school and are expected to have a certain language proficiency. The situation can put a strain on the school system and teachers to provide the necessary basic language skills while also teaching the rest of the children. The problem is faced by several city districts in Oslo where up to 40\% of the children who enter primary school need additional teaching in the Norwegian language. Children face further difficulties to improve their Norwegian if it is not spoken at home. Children may lose their motivation to stay with the studies and fall further behind their peers. Using social robots to help in the language training may offload some of the teaching load and keep the children motivated. \begin{figure}[tb] \includegraphics[width=1.\linewidth]{bhg} \caption{Nao interacting with a small group of children in a care center context with staff present. Pictures of the terms to be learned are projected on the wall behind the robot.} \label{fig:bhg} \end{figure} We are designing a program to use a social robot to improve immigrant children's ability to learn Norwegian as part of the language education in daycare centers (kindergartens). The program is designed with the help of parents and employees from a city district in Oslo. This paper documents the work that has been done so far, and how the study will be carried out over the next year. \section{Related work} Social robots have been used for teaching language in a variety of situations. The L2TOR project introduced a possible design for using a robot and tablet to teach children a second language \parencite{belpaemeL2TORSecondLanguage2015}. Experiences from this study and other have lead to guidelines for teaching second language to children \parencite{belpaemeGuidelinesDesigningSocial2018}. These guidelines highlight factors to consider such as the modality and if the robot acts as a peer, a teacher, or provides no feedback. A recent large scale study compared how well 194 Dutch primary school children could learn English with a Nao versus a tablet application \parencite{vogtSecondLanguageTutoring2019}. The study showed that children could retain the language they had learned from the robot at the same level they could with a tablet and that iconic gestures from the robot did not seem to effect on how well the children learned. Our work differs in that we are teaching slightly younger immigrant children Norwegian so they can better participate in schools and their education. Beyond language education, robots were programmed to show empathy to see how it affected children playing a game to learn about sustainability issues \parencite{alves-oliveiraEmpathicRobotGroup2019}. Others have also used robots and language to explore children's trust of a robot \parencite{geiskkovitchWhatThatNot2019}. This study draws inspiration from our earlier pilot study using social robots and tablets to teach Norwegian to children in daycare centers \parencite{fuglerudUseSocialRobots2018}. The pilot consisted of the robot together with a teacher, a group of children, and a tablet. The pilot showed that the children needed personalized one-on-one attention that could be provided by the robot, and that the speech recognition for Norwegian (especially for children, a general speech recognition problem \parencite{kennedyChildSpeechRecognition2017}) must be improved. In addition, we are using guidelines from \parencite{belpaemeGuidelinesDesigningSocial2018}. \section{Small-scale study and interviews} To help children before they enter primary school, we targeted day care centers in the Grorud district of Oslo. Most children in the district attend daycare centers from ages one to five. The pedagogic staff of the centers have developed a language program, \term{språkdusj} (language shower), to aid children in expanding their Norwegian vocabulary. Currently, the program is implemented as printed pictures of things for which the proper term is to be learned. The basic principle has children presented with a corresponding visual and the question \enquote{What do you see here?} The children have to recall the correct term from their memory and its pronunciation by saying the word aloud. To reduce issues with the robot recognizing children's speech, the pedagogic staff would assist the children in the process and determine if the answer was correct. A small-scale study was conducted in Autumn 2018 in selected daycare centers. The trial involved a prototype using the Nao robot \parencite{softbankrobotics} that stood in front of approximately 15 children (Figure~\ref{fig:bhg}). The Nao was linked to a web application that was projected on the wall and showed pictures of the terms to be learned (e.g., trousers, chair, fork, showers) one at a time. The robot asked what the children saw, processed the children's answer in its speech recognition engine, and determined the answer's correctness. The study showed promising results in children's motivation as compared to the language program without a robot. From the study, the robot's main advantages appeared to be its attractive, human-like appearance; its not-threatening size for children; speech synthesis and recognition; and the ability to move, gesture, and dance, including support for light, as well as sound and audio effects. We conducted several interviews and workshops with pedagogues and other daycare center staff to find out how a robot could be part of their language program. We also interviewed some of the children's parents to understand the parents' Norwegian abilities and if children spoke (and learned) Norwegian or other languages at home. Overall, twelve people were interviewed. Suggestions included having the children in dialog with a robot and including game elements that would track each child's progress to help motivate the children. The interviews also revealed it was necessary to include parents in the language teaching since they can help maintain the children's motivation at home, and they may also benefit from learning Norwegian themselves. \section{Large-scale Study Design} We used the suggestions from the interviews and workshops to build on the previous study by developing a digitalized version of the language program, and expanded it to include adults. The program includes a Nao, a tablet app, and a mobile app. The tablet app is a prompt and starting point for lessons with Nao. For instance, in one interaction, the app shows a picture with three socks. Nao asks the children what is the pattern of the sock in the middle? Without Nao, the app shows four answer alternatives in a multiple-choice manner. To maintain motivation, Nao will provide varied supporting feedback and give rewards in form of oral acknowledgments, dances, and suitable light and sound effects. The program also adds a mobile application that targets the children's parents at home The mobile app helps to keep track of a single child's or group of children's progress and can be used to have discussions about language at home. Currently, the app contains the entire language program and all instructions for the robot. The robot instructions is an add-on available only in the daycare centers. If the Nao is available, it connects to the app and coordinates the walk-through of the language program in a joint manner. The study will begin in Spring 2020. The main objectives are \begin{enumerate*}[label=(\textit{\arabic*})] \item verify the technology, pedagogical, and gamification concepts; \item measure gains in children's permanent vocabulary using Nao and the accompanying apps compared to the traditional language program. \end{enumerate*} The goal is the children will be better prepared to meet the language vocabulary requirements of the primary school, with a further positive impact on work life and social life as well. The study will be longitudinal and use a between-subjects design. Some district daycare centers will have access to the digitalized solution, others not. The study will start at one daycare center to control for problems and added to other centers as the system stabilizes. Ideally, the centers' employees will control the pace. We will compare the language development of the children that use the program versus those that do not. We plan to test the children's language skills at the beginning of the study, during the study, when it terminates, and 6 months after the trials' termination. This involves testing the words that have been taught in the robot sessions to measure language skills. \section{Discussion and Conclusion} Involving parents and daycare employees has helped create a novel system for language training of immigrant children and maintaining their motivation. There are potential issues, particularly in speech synthesis and speech recognition for children, that may cause the system to fail. We are continually investigating these issues and hope to have them addressed before or during its use in the first daycare center. It will also be interesting to see how the robot becomes part of each daycare center's education program. Our study design should provide good evidence to whether a social robot can be an important tool for immigrant children to learn the Norwegian language before entering primary school. \begin{acks} Thanks to the parents, children, and day car workers at Grorud City District in Oslo, master students in Oslo Metropolitan University, and Innocom AS for help in realizing this project. \end{acks} \printbibliography \end{document} \endinput
{'timestamp': '2020-11-13T02:20:49', 'yymm': '2010', 'arxiv_id': '2010.05491', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05491'}
arxiv
\section{Introduction} Existing experiments \cite{li2017multi} have proven that multimodal news can significantly improve users’ sense of satisfaction for informativeness. As one of these multimedia data forms, introducing news events with video and textual descriptions is becoming increasingly popular, and has been employed as the main form of news reporting by news media including BBC, Weibo, CNN, and Daily Mail. An illustration is shown in Figure~\ref{fig:intro}, where the news contains a video with a cover picture and a full news article with a short textual summary. In such a case, automatically generating multimodal summaries, \emph{i.e.,}\xspace choosing a proper cover frame of the video and generating an appropriate textual summary of the article can help editors save time and readers make decisions more effectively. There are several works focusing on multimodal summarization. The most related work to ours is \cite{zhu2018msmo}, where they propose the task of generating textual summary and picking the most representative picture from 6 input candidates. However, in real-world applications, the input is usually a video consisting of hundreds of frames. Consequently, the temporal dependency in a video cannot be simply modeled by static encoding methods. Hence, in this work, we propose a novel task, Video-based Multimodal Summarization with Multimodal Output (VMSMO), which selects cover frame from news video and generates textual summary of the news article in the meantime. The cover image of the video should be the salient point of the whole video, while the textual summary should also extract the important information from source articles. Since the video and the article focus on the same event with the same report content, these two information formats complement each other in the summarizing process. However, how to fully explore the relationship between temporal dependency of frames in video and semantic meaning of article still remains a problem, since the video and the article come from two different space. Hence, in this paper, we propose a model named \emph{Dual-Interaction-based Multimodal Summarizer (DIMS)}, which learns to summarize article and video simultaneously by conducting a dual interaction strategy in the process. Specifically, we first employ Recurrent Neural Networks (RNN) to encode text and video. Note that by the encoding RNN, the spatial and temporal dependencies between images in the video are captured. Next, we design a dual interaction module to let the video and text fully interact with each other. Specifically, we propose a conditional self-attention mechanism which learns local video representation under the guidance of article, and a global-attention mechanism to learn high-level representation of video-aware article and article-aware video. Last, the multimodal generator generates the textual summary and extracts the cover image based on the fusion representation from the last step. To evaluate the performance of our model, we collect the first large-scale news article-summary dataset associated with video-cover from social media websites. Extensive experiments on this dataset show that DIMS significantly outperforms the state-of-the-art baseline methods in commonly-used metrics by a large margin. To summarize, our contributions are threefold: $\bullet$ We propose a novel Video-based Multimodal Summarization with Multimodal Output (VMSMO) task which chooses a proper cover frame for the video and generates an appropriate textual summary of the article. $\bullet$ We propose a Dual-Interaction-based Multimodal Summarizer (DIMS) model, which jointly models the temporal dependency of video with semantic meaning of article, and generates textual summary with video cover simultaneously. $\bullet$ We construct a large-scale dataset for VMSMO, and experimental results demonstrate that our model outperforms other baselines in terms of both automatic and human evaluations. \begin{figure*} \centering \includegraphics[scale=0.52]{pic/overview.pdf} \caption{ Overview of DIMS. We divide our model into three parts: (1) \textit{Feature Encoder} encodes the input article and video separately; (2) \textit{Dual Interaction Module} learns fused representation of video and article from different level; (3) \textit{Multi-Generator} generates the textual summary and chooses the video cover simultaneously. } \label{fig:overview} \end{figure*} \section{Related Work} Our research builds on previous works in three fields: text summarization, multimodal summarization, and visual question answering. \noindent \textbf{Text Summarization.} Our proposed task bases on text summarization, the methods of which can be divided into extractive and abstractive methods~\cite{Gao2020From}. Extractive models~\cite{zhang2018neural, Narayan2018RankingSF,chen2018iterative,Luo2019ReadingLH,Xiao2019ExtractiveSO} directly pick sentences from article and regard the aggregate of them as the summary. In contrast, abstractive models ~\cite{sutskever2014sequence,See2017GetTT, Wenbo2019ConceptPN, Gui2019AttentionOF,gao2019write,chen2019learning,gao2019abstractive} generate a summary from scratch and the abstractive summaries are typically less redundant. \noindent \textbf{Multimodal Summarization.} A series of works \cite{li2017multi,li2018multi,palaskar2019multimodal,chan2019stick,chen2019rpm,gao2020learning} focused on generating better textual summaries with the help of multimodal input. Multimodal summarization with multimodal output is relatively less explored. \citet{zhu2018msmo} proposed to jointly generate textual summary and select the most relevant image from 6 candidates. Following their work, \citet{zhu3multimodal} added a multimodal objective function to use the loss from the textual summary generation and the image selection. However, in the real-world application, we usually need to choose the cover figure for a continuous video consisting of hundreds of frames. Consequently, the temporal dependency between frames in a video cannot be simply modeled by several static encoding methods. \noindent \textbf{Visual Question Answering.} Visual Question Answering (VQA) task is similar to our task in taking images and a corresponding text as input. Most works consider VQA task as a classification problem and the understanding of image sub-regions or image recognition becomes particularly important~\cite{goyal2017making, malinowski2015ask, wu2016ask, xiong2016dynamic}. As for the interaction models, one of the state-of-the-art VQA models \cite{li2019beyond} proposed a positional self-attention with a co-attention mechanism, which is faster than the recurrent neural network (RNN). \citet{guo2019image} devised an image-question-answer synergistic network, where candidate answers are coarsely scored according to their relevance to the image and question pair and answers with a high probability of being correct are re-ranked by synergizing with image and question. \section{Problem Formulation} Before presenting our approach for the VMSMO, we first introduce the notations and key concepts. For an input news article $X = \{x_1, x_2, \dots, x_{T_d}\}$ which has ${T_d}$ words, we assume there is a ground truth textual summary $Y = \{y_1, y_2, \dots, y_{T_y}\}$ which has ${T_y}$ words. Meanwhile, there is a news video $V$ corresponding to the article, and we assume there is a ground truth cover picture $C$ that extracts the most important frame from the video content. For a given article $X$ and the corresponding video $V$, our model emphasizes salient parts of both inputs by conducting deep interaction. The goal is to generate a textual summary $Y^{'}$ that successfully grasp the main points of the article and choose a frame picture $C^{'}$ that covers the gist of the video. \section{Model} \subsection{Overview} In this section, we propose our Dual Interaction-based Multimodal Summarizer (DIMS), which can be divided into three parts in Figure~\ref{fig:overview}: $\bullet$ \textit{Feature Encoder} is composed of a text encoder and a video encoder which encodes the input article and video separately. $\bullet$ \textit{Dual Interaction Module} conducts deep interaction, including conditional self-attention and global-attention mechanism between video segment and article to learn different levels of representation of the two inputs. $\bullet$ \textit{Multi-Generator} generates the textual summary and chooses the video cover by incorporating the fused information. \subsection{Feature Encoder} \subsubsection{Text encoder} To model the semantic meaning of the input news text $X = \{x_1, x_2, \dots, x_{T_d}\}$, we first use a word embedding matrix $e$ to map a one-hot representation of each word $x_{i}$ into to a high-dimensional vector space. Then, in order to encode contextual information from these embedding representation, we use bi-directional recurrent neural networks (Bi-RNN) \cite{Hochreiter1997LongSM} to model the temporal interactions between words: \begin{align} h^x_t &= \text{Bi-RNN}_\text{X}(e(x_t), h^x_{t-1}), \end{align} where $h^x_t$ denotes the hidden state of $t$-th step in Bi-RNN for $X$. Following \cite{See2017GetTT, ma2018hierarchical}, we choose the long short-term memory (LSTM) as the Bi-RNN cell. \subsubsection{Video Encoder} A news video usually lasts several minutes and consists of hundreds of frames. Intuitively, a video can be divided into several segments, each of which corresponds to different content. Hence, we choose to encode video hierarchically. More specifically, we equally divide frames in the video into several segments and employ a low-level frame encoder and a high-level segment encoder to learn hierarchical representation. \textbf{Frame encoder.} We utilize the Resnet-v1 model \cite{he2016deep} to encode frames to alleviate gradient vanishing \cite{he2016deep} and reduce computational costs: \begin{align} O_j^i&=\text{Resnet-v1}(m_j^i),\\ M_j^i&=\operatorname{relu}\left(F_v(O_j^i)\right), \end{align} where $m_j^i$ is the $j$-th frame in $i$-th segment and $F_{v}(\cdot)$ is a linear transformation function. \textbf{Segment encoder.} As mentioned before, it is important to model the continuity of images in video, which cannot be captured by a static encoding strategy. We employ RNN network as segment encoder due to its superiority in exploiting the temporal dependency among frames \citet{zhao2017hierarchical}: \begin{align} S_j^i = \text{Bi-RNN}_\text{S}(M_j^i, S^i_{j-1}). \end{align} $S_j^i$ denotes the hidden state of $j$-th step in Bi-RNN for segment $s_i$, and the final hidden state $S_{T_f}^i$ denotes the overall representation of the segment $s_i$, where $T_f$ is the number of frames in a segment. \begin{figure} \centering \includegraphics[scale=0.43]{pic/cond.pdf} \caption{ Conditional self-attention module, which captures local semantic information within video segments under the guidance of article representation. } \label{fig:cond} \end{figure} \subsection{Dual Interaction Module} The cover image of the video should contain the key point of the whole video, while the textural summary should also cover extract the important information from source articles. Hence, these two information formats complement each other in the summarizing process. In this section, we conduct a deep interaction between the video and article to jointly model the temporal dependency of video and semantic meaning of text. The module consists of a conditional self-attention mechanism that captures local semantic information within video segments and a global-attention mechanism that handles the semantic relationship between news text and video from a high level. \textbf{Conditional self-attention mechanism.} Traditional self-attention can be used to obtain contextual video representation due to its flexibility in relating two elements in a distance-agnostic manner. However, as illustrated in \citet{xie2020conditional}, the semantic understanding often relies on more complicated dependencies than the pairwise one, especially conditional dependency upon a given premise. Hence, in the VMSMO task, we capture the local semantic information of video conditioned on the input text information. Our conditional self-attention module shown in Figure~\ref{fig:cond} is composed of a stack of N identical layers and a conditional layer. The identical layer learns to encode local video segments while the conditional layer learns to assign high weights to the video segments conditioned on their relationship to the article. We first use a fully-connected layer to project each segment representation $S_{T_f}^i$ into the query $Q^i$, key $K^i$, and value $V^i$. Then, the scaled dot-product self-attention is defined as: \begin{align} \alpha_{i, j} &=\frac{\exp \left(Q^{i} K^{j}\right)}{\sum\nolimits_{n=1}^{T_{s}} \exp \left(Q^{i} K^{n}\right)}, \\ \hat{S}_{i} &=\sum\nolimits_{j=1}^{T_{s}} \frac{\alpha_{i, j} V^{j}}{\sqrt d}, \end{align} where $d$ stands for hidden dimension and $T_{s}$ is the segment number in a video. $\hat{S}_{i}$ is then fed into the feed-forward sub-layer including a residual connection~\cite{he2016deep} and layer normalization~\cite{ba2016layer}. Next, we highlight the salient part of the video under the guidance of article. Taking the article information $h_{T_d}^x$ as condition, the attention score on each original segment representation $S_{T_f}^i$ is calculated as: \begin{align} \beta_{i} &=\sigma\left(F_s(S_{T_f}^i h_{T_d}^x)\right). \end{align} The final conditional segment representation $S^{c}_{i}$ is denoted as $\beta_{i} \hat{S}_{i}$. \textbf{Global-attention mechanism.} The global-attention module grounds the article representation on the video segments and fuses the information of the article into the video, which results in an article-aware video representation and a video-aware article representation. Formally, we utilize a two-way attention mechanism to obtain the co-attention between the encoded text representation $h^x_t$ and the encoded segment representation $S_{T_f}^i$: \begin{align} \label{global} E^{t}_{i} &= F_{h}(h^x_t) \left(F_{t}(S_{T_f}^i)\right)^T. \end{align} We use $E^{t}_{i}$ to denote the attention weight on the $t$-th word by the $i$-th video segment. To learn the alignments between text and segment information, the global representations of video-aware article $\hat{h}^x_t$ and article-aware video $\hat{S}_i^c$ are computed as: \begin{align} \hat{h}^x_t &= \sum\nolimits_{i=1}^{T_d} E^{t}_{i} S_{T_f}^i,\\ \hat{S}_i^c &= \sum\nolimits_{t=1}^{T_s} \left( {E^{t}_{i}}\right )^T h^x_t. \end{align} \subsection{Multi-Generator} In the VMSMO task, the multi-generator module not only needs to generate the textual summary but also needs to choose the video cover. \textbf{Textual summary generation.} For the first task, we use the final state of the input text representation $h^x_{T_d}$ as the initial state $d_0$ of the RNN decoder, and the $t$-th generation procedure is: \begin{align} d_t={\rm \text{LSTM}_{dec}}(d_{t-1}, [e(y_{t-1}); h^{c}_{t-1}]), \end{align} where $d_t$ is the hidden state of the $t$-th decoding step and $h^{c}_{t-1}$ is the context vector calculated by the standard attention mechanism~\cite{bahdanau2014neural}, and is introduced below. To take advantage of the article representation $h^x_t$ and the video-aware article representation $\hat{h}^x_t$, we apply an ``editing gate'' $\gamma_e$ to decide how much information of each side should be focused on: \begin{align} \gamma_e &=\sigma\left( F_d(d_t) \right),\\ g_i &=\gamma_e h^x_i + (1-\gamma_e) \hat{h}^x_i. \end{align} Then the context vector $h^c_{t-1}$ is calculated as: \begin{align} \delta_{it}&=\frac{{\rm exp}(F_a(g_i, d_t))}{\sum\nolimits_j {\rm exp}(F_a(g_j, d_t))}.\\ h_t^{c}&=\sum\nolimits_i \delta_{it}g_i \label{contextvector}, \end{align} Finally, the context vector $h^c_t$ is concatenated with the decoder state $d_t$ and fed into a linear layer to obtain the generated word distribution $P_v$: \begin{align} d_t^o&= \sigma\left( F_p([d_t;h^c_t]) \right),\\ P_v&={\rm softmax} \left(F_o(d_t^o) \right). \end{align} Following \citet{See2017GetTT}, we also equip our model with pointer network to handle the out-of-vocabulary problem. The loss of textual summary generation is the negative log likelihood of the target word $y_t$: \begin{align} \mathcal{L}_{seq} = -\sum\nolimits_{t=1}^{T_y} \log P_v(y_t). \end{align} \textbf{Cover frame selector.} The cover frame is chosen based on hierarchical video representations, \emph{i.e.,}\xspace the original frame representation $M_j^i$ and the conditional segment representation $S^{c}_i$ with the article-aware segment representation $\hat{S}^{c}_i$: \begin{align} p_j^i &=\gamma_f^1 S^{c}_i + \gamma_f^2 \hat{S}^{c}_i + (1-\gamma_f^1 -\gamma_f^2) M_j^i,\\ y^{c}_{i,j} &= \sigma\left( F_c(p_j^i) \right), \end{align} where $y^{c}_{i,j}$ is the matching score of the candidate frames. The fusion gates $\gamma_f^1$ and $\gamma_f^2$ here are determined by the last text encoder hidden state $h_{T_d}^x$: \begin{align} \gamma_f^1 &=\sigma\left( F_{m}(h_{T_d}^x) \right),\\ \gamma_f^2 &=\sigma\left( F_{n}(h_{T_d}^x) \right). \end{align} We use pairwise hinge loss to measure the selection accuracy: \begin{align} \mathcal{L}_{pic} = \sum\nolimits^N \text{max} \left( 0, y^{c}_\text{negative}-y^{c}_\text{positive}+\text{margin} \right), \end{align} where $y^{c}_{negative}$ and $y^{c}_{positive}$ corresponds to the matching score of the negative samples and the ground truth frame, respectively. The margin in the $\mathcal{L}_{pic}$ is the rescale margin in hinge loss. The overall loss for the model is: \begin{align} \mathcal{L} = \mathcal{L}_{seq} + \mathcal{L}_{pic}. \end{align} \section{Experimental Setup} \subsection{Dataset} \label{dataset} To our best knowledge, there is no existing large-scale dataset for VMSMO task. Hence, we collect the first large-scale dataset for VMSMO task from Weibo, the largest social network website in China. Most of China's mainstream media have Weibo accounts, and they publish the latest news in their accounts with lively videos and articles. Correspondingly, each sample of our data contains an article with a textual summary and a video with a cover picture. The average video duration is one minute and the frame rate of video is 25 fps. For the text part, the average length of article is 96.84 words and the average length of textual summary is 11.19 words. Overall, there are 184,920 samples in the dataset, which is split into a training set of 180,000 samples, a validation set of 2,460 samples, and a test set of 2,460 samples. \subsection{Comparisons} \label{comparison} We compare our proposed method against summarization baselines and VQA baselines. \noindent \textit{Traditional Textual Summarization baselines:} \noindent \textbf{Lead}: selects the first sentence of article as the textual summary \cite{nallapati2017summarunner}. \noindent \textbf{TexkRank}: a graph-based extractive summarizer which adds sentences as nodes and uses edges to weight similarity \cite{Mihalcea2004TextRankBO}. \noindent \textbf{PG}: a sequence-to-sequence framework combined with attention mechanism and pointer network \cite{See2017GetTT}. \noindent \textbf{Unified}: a model which combines the strength of extractive and abstractive summarization \cite{hsu2018unified}. \noindent \textbf{GPG}: \citet{shen2019improving} proposed to generate textual summary by ``editing'' pointed tokens instead of hard copying. \noindent \textit{Multimodal baselines:} \noindent \textbf{How2}: a model proposed to generate textual summary with video information \cite{palaskar2019multimodal}. \noindent \textbf{Synergistic}: a image-question-answer synergistic network to value the role of the answer for precise visual dialog\cite{guo2019image}. \noindent \textbf{PSAC}: a model adding the positional self-attention with co-attention on VQA task \cite{li2019beyond}. \noindent \textbf{MSMO}: the first model on multi-output task, which paid attention to text and images during generating textual summary and used coverage to help select picture \cite{zhu2018msmo}. \noindent \textbf{MOF}: the model based on MSMO which added consideration of image accuracy as another loss \cite{zhu3multimodal}. \subsection{Evaluation Metrics} The quality of generated textual summary is evaluated by standard full-length Rouge F1~\cite{lin2004rouge} following previous works \cite{See2017GetTT, chen2018iterative}. R-1, R-2, and R-L refer to unigram, bigrams, and the longest common subsequence respectively. The quality of chosen cover frame is evaluated by mean average precision (MAP) \cite{zhou2018multi-turn} and recall at position ($R_n@k$) \cite{tao2019multi-representation}. $R_n@k$ measures if the positive sample is ranked in the top $k$ positions of $n$ candidates. \begin{table}[t] \centering \small \begin{tabular}{@{}lccc@{}} \toprule & R-1 & R-2 & R-L\\ \midrule \emph{extractive summarization}\\ Lead & 16.2 & 5.3 & 13.9 \\ TextRank & 13.7 & 4.0 & 12.5 \\ \midrule \emph{abstractive summarization}\\ PG \cite{See2017GetTT} & 19.4 & 6.8 & 17.4\\ Unified \cite{hsu2018unified} & 23.0 & 6.0 & 20.9\\ GPG \cite{shen2019improving} & 20.1 & 4.5 & 17.3\\ \midrule \emph{our models}\\ \textbf{DIMS} & \textbf{25.1} & \textbf{9.6} & \textbf{23.2} \\ \bottomrule \end{tabular} \caption{Rouge scores comparison with traditional textual summarization baselines.} \label{tab:sum_baslines} \end{table} \begin{table*}[t] \centering \small \begin{tabular}{@{}lccccccc@{}} \toprule & R-1 & R-2 & R-L & MAP & $R_{10}@1$ & $R_{10}@2$ & $R_{10}@5$\\ \midrule \emph{video-based summarization}\\ How2 \cite{palaskar2019multimodal} & 21.7 & 6.1 & 19.0 & - & - & - & - \\ \midrule \emph{Visual Q\&A methods}\\ Synergistic \cite{guo2019image} & - & - & - & 0.588 & 0.444 & 0.557 & 0.759 \\ PSAC \cite{li2019beyond} & - & - & - & 0.524 & 0.363 & 0.481 & 0.730 \\ \midrule \emph{multimodal summarization with multimodal output}\\ MSMO \cite{zhu2018msmo} & 20.1 & 4.6 & 17.3 & 0.554 & 0.361 & 0.551 & 0.820 \\ MOF \cite{zhu3multimodal} & 21.3 & 5.7 & 17.9 & 0.615 & 0.455 & 0.615 & 0.817 \\ \midrule \emph{our models}\\ \textbf{DIMS} & \textbf{25.1} & \textbf{9.6} & \textbf{23.2} & \textbf{0.654} & \textbf{0.524} & \textbf{0.634} & \textbf{0.824} \\ DIMS-textual summary & 22.0 & 6.3 & 19.2 & - & - & - & - \\ DIMS-cover frame & - & - & - & 0.611 & 0.449 & 0.610 & 0.823\\ \midrule \emph{ablation study}\\ DIMS-G & 23.7 & 7.4 & 21.7 & 0.624 & 0.471 & 0.619 & 0.819\\ DIMS-S & 24.4 & 8.9 & 22.5 & 0.404 & 0.204 & 0.364 & 0.634\\ \bottomrule \end{tabular} \caption{Rouge and Accuracy scores comparison with multimodal baselines.} \label{tab:comp_baslines} \end{table*} \subsection{Implementation Details} We implement our experiments in Tensorflow~\cite{abadi2016tensorflow} on an NVIDIA GTX 1080 Ti GPU. The code for our model is available online\footnote{https://github.com/yingtaomj/VMSMO}. For all models, we set the word embedding dimension and the hidden dimension to 128. The encoding step is set to 100, while the minimum decoding step is 10 and the maximum step is 30. For video preprocessing, we extract one of every 120 frames to obtain 10 frames as cover candidates. All candidates are resized to 128x64. We regard the frame that has the maximum cosine similarity with the ground truth cover as the positive sample, and others as negative samples. Note that the average cosine similarity of positive samples is 0.90, which is a high score, demonstrating the high quality of the constructed candidates. In the conditional self-attention mechanism, the stacked layer number is set to 2. For hierarchical encoding, each segment contains 5 frames. Experiments are performed with a batch size of 16. All the parameters in our model are initialized by Gaussian distribution. During training, we use Adagrad optimizer as our optimizing algorithm and we also apply gradient clipping with a range of $[-2,2]$. The vocabulary size is limited to 50k. For testing, we use beam search with beam size 4 and we decode until an end-of-sequence token is reached. We select the 5 best checkpoints based on performance on the validation set and report averaged results on the test set. \begin{table}[t] \centering \small \begin{tabular}{@{}lcc@{}} \toprule & QA(\%) & Rating \\ \midrule How2 & 46.2 & -0.24\\ MOF & 51.3 & -0.14 \\ Unified & 53.8 & 0.00\\ \textbf{DIMS} & \textbf{66.7} &\textbf{0.38} \\ \bottomrule \end{tabular} \caption{System scores based on questions answered by human and summary quality rating. } \label{tab:comp_human_baslines} \end{table} \section{Experimental Result} \subsection{Overall Performance} We first examine \textit{whether our DIMS outperforms other baselines} as listed in Table~\ref{tab:sum_baslines} and Table~\ref{tab:comp_baslines}. Firstly, abstractive models outperform all extractive methods, demonstrating that our proposed dataset is suitable for abstractive summarization. Secondly, the video-enhanced models outperform traditional textural summarization models, indicating that video information helps generate summary. Finally, our model outperforms \texttt{MOF} by 17.8\%, 68.4\%, 29.6\%, in terms of Rouge-1, Rouge-2, Rouge-L, and 6.3\%, 15.2\% in MAP and $R@1$ respectively, which proves the superiority of our model. All our Rouge scores have a 95\% confidence interval of at most $\pm$0.55 as reported by the official Rouge script. In addition to automatic evaluation, system performance was also evaluated on the generated textual summary by human judgments on 70 randomly selected cases similar to \citet{liu2019hierarchical}. Our first evaluation study quantified the degree to which summarization models retain key information from the articles following a question-answering (QA) paradigm \cite{Narayan2018RankingSF}. A set of questions was created based on the gold summary. Then we examined whether participants were able to answer these questions by reading system summaries alone. We created 183 questions in total varying from two to three questions per gold summary. Correct answers were marked with 1 and 0 otherwise. The average of all question scores is set to the system score. Our second evaluation estimated the overall quality of the textual summaries by asking participants to rank them according to its \textit{Informativeness} (does the summary convey important contents about the topic in question?), \textit{Coherence} (is the summary fluent and grammatical?), and \textit{Succinctness} (does the summary avoid repetition?). Participants were presented with the gold summary and summaries generated from several systems better on autometrics and were asked to decide which was the best and the worst. The rating of each system was calculated as the percentage of times it was chosen as best minus the times it was selected as worst, ranging from -1 (worst) to 1 (best). Both evaluations were conducted by three native-speaker annotators. Participants evaluated summaries produced by \texttt{Unified}, \texttt{How2}, \texttt{MOF} and our \texttt{DIMS}, all of which achieved high perfromance in automatic evaluations. As shown in Table \ref{tab:comp_human_baslines}, on both evaluations, participants overwhelmingly prefer our model. All pairwise comparisons among systems are statistically significant using the paired student t-test for significance at $\alpha$ = 0.01. \begin{figure*} \centering \includegraphics[scale=0.55]{pic/global_visual_1.pdf} \caption{ Visualizations of global-attention matrix between the news article and two frames in the same video. } \label{fig:global_visual} \end{figure*} \subsection{Ablation Study} Next, we conduct ablation tests to assess the importance of the conditional self-attention mechanism (-S), as well as the global-attention (-G) in Table~\ref{tab:comp_baslines}. All ablation models perform worse than \texttt{DIMS} in terms of all metrics, which demonstrates the preeminence of \texttt{DIMS}. Specifically, the global-attention module contributes mostly to the textual summary generation, while the conditional self-attention module is more important for choosing cover frame. \subsection{Analysis of Multi-task learning} Our model aims to generate textural summary and choose cover frame at the same time, which can be regarded as a multi-task. Hence, in this section, we examine whether these two tasks can complement each other. We separate our model into two single-task architecture, named as \texttt{DIMS-textual summary} and \texttt{DIMS-cover frame}, which generates textural summary and chooses video cover frame, respectively. The result is shown in Table~\ref{tab:comp_baslines}. It can be seen that the multi-task \texttt{DIMS} outperforms single-task \texttt{DIMS-textual summary} and \texttt{DIMS-cover frame}, improving the performance of summarization by 20.8\% in terms of ROUGE-L score, and increasing the accuracy of cover selection by 7.0\% on MAP. \subsection{Visualization of dual interaction module} To study the multimodal interaction module, we visualize the global-attention matrix $E^{t}_{i}$ in Equation~\ref{global} on one randomly sampled case, as shown in Figure \ref{fig:global_visual}. In this case, we show the attention on article words of two representative images in the video. The darker the color is, the higher the attention weight is. It can be seen that for the left figure, the word \emph{hand in hand} has a higher weight than \emph{picture}, while for the right figure, the word \emph{Book Fair} has the highest weight. This corresponds to the fact that the main body of the left frame is two old men, and the right frame is about reading books. We show a case study in Table \ref{tab:case_study}, which includes the input article and the generated summary by different models. We also show the question-answering pair in human evaluation and the chosen cover. The result shows that the summary generated by our model is both fluent and accurate, and the cover frame chosen is also similar to the ground truth frame. \begin{CJK*}{UTF8}{gkai} \begin{table}[t] \centering \small \begin{tabular}{ll} \toprule \multicolumn{2}{p{7cm}}{ \emph{\textbf{Article:}} On August 26, in Shanxi Ankang, a 12-year-old junior girl Yu Taoxin goose-stepped like parade during the military training in the new semester, and won thousands of praises. Yu Taoxin said that her father was a veteran, and she worked hard in military training because of the influence of her father. Her father told her that military training should be strict as in the army. 8月26日,陕西安康,12岁的初一女生余陶鑫,在新学期军训期间,她踢出阅兵式般的标准步伐,获千万点赞。余陶鑫说,爸爸是名退伍军人,军训刻苦是因为受到爸爸影响,爸爸曾告诉她,军训时就应和在部队里一样,严格要求自己。 } \\ \hline \multicolumn{2}{p{7cm}}{ \emph{\textbf{Reference summary:}} A 12-year-old girl goose-stepped like parade during the military training, ``My father is a veteran.'' 12岁女孩军训走出阅兵式步伐,“爸爸是退伍军人” } \\ \hline \multicolumn{2}{p{7cm}}{ \textbf{QA:} \emph{What happened on the 12-year-old girl?} [\emph{She goose-stepped like parade.}] 这个12岁女孩做了什么?[她走出阅兵式步伐。] }\\ \multicolumn{2}{p{7cm}}{ \emph{Why did she do this?} [\emph{She was influenced by her father}] 她为什么这样做?[她受到爸爸的影响。] }\\ \hline \multicolumn{2}{p{7cm}}{ \emph{\textbf{Unfied:}} 12-year-old gril Yu Taoxin goose-stepped during military training. 12岁女生余陶鑫军训期间阅兵式般的标准步伐}\\ \hline \multicolumn{2}{p{7cm}}{ \emph{\textbf{How2:}} 12-year-old girls were organized military training, and veteran mother parade. 12岁女生组团军训,退伍军人妈妈阅兵式}\\ \hline \multicolumn{2}{p{7cm}}{ \emph{\textbf{MOF:}} A 12-year-old junior citizen [unk]: father gave a kicked like. 1名12岁初一市民 [unk]:爸爸踢式点赞}\\ \hline \multicolumn{2}{p{7cm}}{ \emph{\textbf{DIMS:}} A 12-year-old junior girl goose-stepped like parade: My father is a veteran, and military training should be strict as in the army. 12岁初一女生踢出阅兵式:爸爸是名退伍军人,军训时就应和在部队一样}\\ \hline \multicolumn{2}{p{7cm}}{ \begin{minipage}{0.1\textwidth} \includegraphics[scale=0.5]{pic/case_study.pdf} \end{minipage}} \\ \bottomrule \end{tabular} \caption{Examples of the generated summary by baselines and DIMS. } \label{tab:case_study} \end{table} \end{CJK*} \section{Conclusion} In this paper, we propose the task of Video-based Multimodal Summarization with Multimodal Output (VMSMO) which chooses a proper video cover and generates an appropriate textual summary for a video-attached article. We propose a model named Dual-Interaction-based Multimodal Summarizer (DIMS) including a local conditional self-attention mechanism and a global-attention mechanism to jointly model and summarize multimodal input. Our model achieves state-of-the-art results in terms of autometrics and outperforms human evaluations by a large margin. In near future, we aim to incorporate the video script information in the multimodal summarization process. \section*{Acknowledgments} We would like to thank the anonymous reviewers for their constructive comments. This work was supported by the National Key Research and Development Program of China (No.2020AAA0105200), and the National Science Foundation of China (NSFC No.61876196, No.61672058). Rui Yan is partially supported as a Young Fellow of Beijing Institute of Artificial Intelligence (BAAI). \input{emnlp2020.bbl} \end{document}
{'timestamp': '2020-10-13T02:27:15', 'yymm': '2010', 'arxiv_id': '2010.05406', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05406'}
arxiv
\section{Introduction}\label{sec:intro} Given a passage, a question, and an answer phrase, the goal of distractor generation (DG) is to generate context-related wrong options (i.e., distractor) for multiple-choice questions (MCQ). Pioneering research \cite{gao2019generating,yeung2019difficulty,zhou2019coattention} have demonstrated the feasibility of generating distractors based on deep learning techniques. \begin{table}[t] \resizebox{\linewidth}{!}{ \begin{tabular}{l} \textbf{Example 1} \\ \hline \multicolumn{1}{|l|}{\textbf{Context} Omitted. (See Appendix)} \\ \multicolumn{1}{|l|}{\textbf{Question}} \\ \multicolumn{1}{|l|}{$\cdot$ Why did Mr.King want to send Henry away?} \\ \multicolumn{1}{|l|}{\textbf{Answer}} \\ \multicolumn{1}{|l|}{\begin{tabular}[c]{@{}l@{}} $\cdot$ Because Henry was too lazy.\end{tabular}} \\ \multicolumn{1}{|l|}{\textbf{Gen. Distractors}} \\ \multicolumn{1}{|l|}{$\cdot d_1:$ Because Henry didn't want to go.} \\ \multicolumn{1}{|l|}{$\cdot d_2:$ Because Henry didn't want to go to the bookstore.} \\ \hline \\ \textbf{Example 2} \\ \hline \multicolumn{1}{|l|}{\textbf{Context} Omitted. (See Appendix)} \\ \multicolumn{1}{|l|}{\textbf{Question}} \\ \multicolumn{1}{|l|}{$\cdot$ Which of the following women would look most attractive?} \\ \multicolumn{1}{|l|}{\textbf{Answer}} \\ \multicolumn{1}{|l|}{$\cdot$ A short red-haired woman who wears a purple hat.} \\ \multicolumn{1}{|l|}{\textbf{Gen. Distractors}} \\ \multicolumn{1}{|l|}{$\cdot d_1:$ A young woman who wears a white hat.} \\ \multicolumn{1}{|l|}{\begin{tabular}[c]{@{}l@{}}$\cdot d_2:$ A woman who wears a white hat.\end{tabular}} \\ \hline \end{tabular} } \caption{Two examples for showing the issue of generating multiple distractors by a simple beam search: Note that the generated distractors (i.e., $d_1$ and $d_2$) are the same statements with only slight word usage difference. Such results lower the distracting power for MCQ preparation.} \label{tab:my-table-mdg} \end{table} While significant advances for DG were reported in the literature, we find that the existing DG results are still far from practical use. In this paper, we investigate the following two issues for distractor generation: (1) \textit{DG quality improvement} and (2) \textit{Multiple distractor generation}. \noindent\textbf{DG Quality Improvement} There is still room to be improved for high-quality distractor generation. By manually examining the DG results generated by the existing method, we find that the results are still far from ideal for practical use. Thus, one goal of our research is to improve the DG quality further. For the quality issues, in this paper, we explore BERT model's employment for performance improvement. As known, employing transformer-based language models has shown to be useful for improving NLP tasks. Thus, we investigate the BERT model's application for DG and report our design in this paper. \noindent\textbf{Multiple Distractor Generation} The existing DG methods mainly focus on \textit{single} distractor generation. However, for practical MCQ preparation, multiple distractors are desired. For more than one distractor, the existing practice is to keep multiple results given by a beam search strategy. However, we find that in many cases, the generated distractors are all referred to the same concept/thing. In fact, the generated distractors are all from the same latent representation, which brings concerns that they might be semantically similar. In Table \ref{tab:my-table-mdg}, we show two DG examples for this problems. In the illustrated examples, one can observe that the generated distractors are the same statements with only a slight word usage difference. Such results lower the distracting power for MCQ preparation. For this limitation, we propose to view multiple distractor generation/selection problems as a \textit{coverage} problem, rather than individually selecting top-\textit{k} distractors based on prediction probability. In other words, we propose to choose a distractor set, which maximizes the difficulty of multiple-choice questions, rather than individually picking results with the highest probability but with similar semantic. The contributions of this paper are (1) a new DG model based on the BERT model employment. The experiment evaluation with benchmarking datasets shows that our model outperforms the existing best models \cite{zhou2019coattention} and pushes the state-of-the-art result from 28.65 to 39.81 (BLEU 1 score). (2) An investigation to employ the use of multiple-choice question answering task to evaluate the DG performance. (3) An investigation for considering the multiple distractors generation problem as a coverage problem. The experiment result demonstrates that the generated multiple distractors are diverse and show strong distracting power for multiple-choice questions. The rest of this paper is organized as follows. In Section \ref{sec:BDG}, we introduce our model design for a single distractor generation. In Section \ref{sec:MDG}, we introduce to our multiple distractor schemes and the incorporation of the question-answer models for distractor selection. In Section \ref{sec:exp}, we report the result of performance analysis. In Section \ref{sec:related}, we review the literature related to this work. Finally, Section \ref{sec:conclusion} concludes our study and discusses future works. \section{Related Work}\label{sec:related} The DG research can be categorized from different perspectives. First, for DG task type, there are two main task categories for DG: cloze-style distractor generation and reading comprehension (RC) distractor generation. In cloze-style DG task, it is viewed as a word filling problem. In general, the first step is to extract distractor candidates from context or some knowledge base, and then the next step is to rank the extracted distractors as a final result. Along this direction, the models are mainly based on similarity heuristic \cite{sumita2005measuring,mitkov2006computer,guo2016questimator,ren2020knowledge} or supervised machine learning way \cite{liang2018distractor,yeung2019difficulty}. The distractors generated for cloze-style DG are mainly word/phrase level. On the other hand, the RC-type QG focuses on generating sentence-level distractors for reading comprehension level testing, such as summarizing article or understanding author opinion \cite{gao2019generating,zhou2019coattention}. For the sentence-level distractors, neural models are commonly employed as it is difficult to generate a semantic rich and fluent distractor from question, content, and answer. In this paper, we also focus on generative sentence-level DG for RC task. However, as mentioned in the introduction, we find the existing DG results are still far from human level. The best SOTA result (in terms of BLEU 1 score) is 29, which is far from the ideal result for practical use. Aiming at this point, we explore the employment of transformer-based pre-trained models for performance improvement. For clarity of comparison, we summarize the existing studies on distractor generation in Table \ref{tab:rel2}. \begin{table*}[t] \centering \resizebox{\textwidth}{!}{ \begin{tabular}{|l|l|l|l|l|l|l|l|} \hline & \multicolumn{2}{l|}{Distractor Level} & \multicolumn{2}{l|}{Answer Type} & \multicolumn{2}{l|}{Method Type} & Model~ \\ \cline{2-8} & Word/phrase & Sentence & Cloze & R.C. & Extractive & Generative & Type \\ \hline \citealt{gao2019generating} & Y & Y & & Y & & Y & RNN \\ \hline \citealt{zhou2019coattention} & Y & Y & & Y & & Y & RNN \\ \hline \citealt{araki2016generating} & Y & & Y & & Y & & Non-neural model \\ \hline \citealt{welbl2017crowdsourcing} & Y & & & Y & Y & & Random forests \\ \hline \citealt{guo2016questimator} & Y & & Y & & Y & & Word2Vec \\ \hline \citealt{kumar2015revup} & Y & Y & Y & & Y & & SVM \\ \hline \citealt{liang2017distractor} & Y & & Y & & & Y & GAN \\ \hline \citealt{liang2018distractor} & Y & Y & & Y & Y & & Non-neural model \\ \hline \end{tabular} } \caption{An Overview of the Existing DG works} \label{tab:rel2} \end{table*} \section{BERT Distractor Generation}\label{sec:BDG} \subsection{BERT Model Review} The BERT model and its family \cite{liu2019roberta,lan2019albert} are composed of a stack of multi-layer bidirectional Transformer encoders. The input to a BERT model is a sequence of tokens. For a given token, its input representation to BERT model is first constructed by summing the corresponding token, segment, and position embeddings. After the input representation, the input embeddings travel through the pre-trained/fine-tuned BERT for task learning and prediction. In general, BERT can be employed in two-level language modeling tasks: sequence-level classification and token-level prediction tasks. For the tasks, there are three special tokens, \texttt{[C]}, \texttt{[S]}, and \texttt{[M]}. The embedding of the \texttt{[C]} token is designed to be used as the aggregate sequence representation for classification tasks. The \texttt{[S]} is designed to distinguish different sentences of a token sequence (to provide/signal information from multiple sentences, as the input token sequence can be a pack of multiple sentences). On the other hand, the \texttt{[M]} token is designed to be used in token-level prediction (e.g., predicting a masked token based on context words or predicting the starting/ending probabilities for span-based tasks such as QA tasks). As reported in \cite{chan2019recurrent, dong2019unified}, BERT essentially is an auto-encoder language modeling design, which aims to reconstruct the original data from corrupted inputs. If BERT is asked to predict a sequence of consecutive masked tokens, it often produces incoherent and ramble results. For example, when using BERT to predict three consecutive $\mathrm{\texttt{[M]}}\mathrm{\texttt{[M]}}\mathrm{\texttt{[M]}}$ masked tokens, the same prediction result for the tokens are often observed. This is because the context (the information for predicting the tokens) for the masked tokens are nearly the same except for the position embedding, making the generated sentences incoherent. Thus, we take into consideration the previous decoded results for decoding the next distractor token, as will be introduced in the next subsection. \begin{table*} \centering \begin{tabular}{|l|l|l|} \hline Iter. & Input Sequence & Predict \\ \hline 1 & \texttt{[C] $C$ [S] [M]} & they \\ \hline 2 & \texttt{[C] $C$ [S]} they \texttt{[M]} & don't \\ \hline 3 & \texttt{[C] $C$ [S]} they don't \texttt{[M]} & know \\ \hline 4 & \texttt{[C] $C$ [S]} they don't know \texttt{[M]} & how \\ \hline 5 & \texttt{[C] $C$ [S]} they don't know how \texttt{[M]} & to \\ \hline 5 & \texttt{[C] $C$ [S]} they don't know how to \texttt{[M]} & get \\ \hline 6 & \texttt{[C] $C$ [S]} they don't know how to get \texttt{[M]} & out \\ \hline 7 & \texttt{[C] $C$ [S]} they don't know how to get out \texttt{[M]} & of \\ \hline 7 & \texttt{[C] $C$ [S]} they don't know how to get out of \texttt{[M]} & the \\ \hline 7 & \texttt{[C] $C$ [S]} they don't know how to get out of the \texttt{[M]} & building \\ \hline 8 & \texttt{[C] $C$ [S]} they don't know how to get out of the building\texttt{[M]} & \texttt{[}S{]} \\ \hline \end{tabular} \caption{A Running Example for the BDG scheme} \label{tab:dg} \end{table*} \subsection{BERT-based Distractor Generation (BDG)}\label{sec:BDG_architecture} In a distractor generation scenario, there are three given inputs: (1) a paragraph $P$, (2) an answer $A$, and (3) a question $Q$. For ease of discussion, let $C$ (referred to as a context sequence) denote the sequence of tokens given by concatenating $P$, $Q$, and $A$. Our BDG model generates distractor tokens in an auto-regressive manner. Specifically, the BDG model predicts a token at a time based on (1) the given context sequence $C$ and (2) the previously predicted distractor tokens. The BDG model takes multiple iterations to generate a distractor. In Table \ref{tab:dg}, we show a running example for the BDG model. Note that at each iteration, our model predicts a token based on $C$ and the previous generated tokens. For example, at Iteration 1, we generate "they" based on $C$. At Iteration 2, we generate "don’t" based on $C$ and "they" tokens, and Iteration 3, we generate "know4" based on $C$, "they", and "don’t". The generation terminates when \texttt{[S]} is predicted. In this example, "they don’t know how to get out of the building" is the final generated result. Specifically, the input sequence $X_{i}$ at Iteration $i$ to BERT is \[ \begin{split} X_{i} = (\mathrm{\texttt{[C]}}, C, \mathrm{\texttt{[S]}},\hat{d_{1}}, ...,\hat{d_{i}},\mathrm{\texttt{[M]}}) \end{split} \] Let $\mathbf{h}_{\texttt{[M]}} \in \mathbb{R}^h$ denote the hidden representation of \texttt{[M]} of $X_{i}$ returned by BERT transformer stacks. The prediction of $\hat{d_i}$ is given by a linear layer transformation $\mathbf{W}_{\texttt{DG}} \in \mathbb{R}^{h\times |V|}$ and a softmax activation to all vocabulary dimension as follows. $$p(w|X_i) = softmax(\mathbf{h}_{\texttt{[M]}}\cdot\mathbf{W}_{\texttt{DG}}+\mathbf{b}_{\texttt{DG}})$$ $$\hat{d_{i+1}}= \mathrm{argmax}_w {Pr(w|X_i)} $$ Subsequently, the newly generated token $\hat{d_i}$ is appended into $X_{i+1}$ and the distractor generation process is repeated based on the new $X_{i+1}$ until \texttt{[S]} is predicted. Our loss function is as follows. $$\underset{\theta}{\text{minimize}}-\sum_{\forall (C, D)} \sum_{i=1}^{|D|}(\text{log}_2p(d_{i+1}|{C, d_{1:i};\theta}))$$ \subsection{Answer Negative Regularization} From the experiment results (will be presented in the later section), we see the BDG model advances the state-of-the-art result \cite{zhou2019coattention} from 28.65 to 35.30 (BLEU 1 score). While the token-level evaluation result looks promising, we find that generation results still have room to be improved. One observation is that in many cases, there is an \textit{answer copying problem} for generating distractors; the generated distractors are similar to the given answers. To better see this phenomenon, we conduct an experiment to count such cases. In the following table, we show the number of cases that the generated distractor $\hat{D}$ has a token-level similarity score greater than $0.95$ with respect to the answer $A$. We also show the cases for the gold distractors. By comparison, there is a significant gap between the human invented distractors and the model generated ones. \\\\ \begin{tabular}{|l|l|l|} \hline & BDG & Gold \\ \hline \# of cases on BLEU1 & 115 & 12 \\ \hline \# of cases on BLEU2 & 115 & 4 \\ \hline \# of cases on BLEU3 & 109 & 0 \\ \hline \# of cases on BLEU4 & 97 & 0 \\ \hline \# of cases on ROUGE-L & 122 & 1 \\\hline \end{tabular} \\\\ Motivated by the answer copying problem, we propose to incorporate a loss (referred to as \textit{answer negative loss}) to discourage predicting tokens in $A$ when predicting $\hat{d_i}$. With the answer negative loss, our loss function for BDG is as follows. \begin{equation} \begin{split} &\underset{\theta}{\text{Minimize}}-\sum_{\forall (C, D)}\phi_{_{a.n.}}(C,D), \\ & \begin{split} \phi_{_{a.n.}}=&\sum_{i=1}^{|D|}(\text{log}_2p(d_{i+1}|{C,d_{1:i};\theta})+\\&\sum_{\forall a_j\in A}\text{log}_2(1-p(a_{j}|{C;\theta})) \end{split} \end{split} \label{eq:SLUL} \end{equation} The design of answer negative loss is motivated by the the desiderata that we expect to regulate the generated distractor $\hat{D}$ to use words different from $A$. \subsection{Multi-task with Parallel MLM} \begin{figure}[t] \centering \includegraphics[width=0.88\columnwidth]{Multi-tasking.png} \caption{The Multi-tasking Architecture} \label{fig:Multi_task} \end{figure} In addition to the answer negative loss, we further propose to jointly train BDG and a parallel MLM (P-MLM) architecture for distractor generation to enhance the quality of BDG. The P-MLM scheme for generating distractors is structured as follows. For a given context $C$, the input sequence $X$ to P-MLM model is formulated as \[ \begin{split} X = (\mathrm{\texttt{[C]}}, C, \mathrm{\texttt{[S]}}, \mathrm{[\texttt{M}]_{d_0}}, \mathrm{[\texttt{M}]_{d_1}}, ...,\mathrm{[\texttt{M}]_{d_{|D|-1}}}) \end{split} \] Let $\mathbf{h}_{\mathrm{\texttt{[M]}_{d_i}}} \in \mathbb{R}^h$ denote the hidden representation of $\mathrm{\texttt{[M]}_{d_i}}$ of $X$ returned by BERT transformer stacks. The prediction of $\hat{q_i}$ is given by a linear layer transformation $\mathbf{W}_{\texttt{P-MLM}} \in \mathbb{R}^{h\times |V|}$ and applying a softmax activation to all vocabulary dimension as follows. $$p(w|X) = softmax(\mathbf{h}_{\mathrm{[\texttt{M}]_{d_i}}}\cdot\mathbf{W}_{\texttt{P-MLM}}+\mathbf{b}_{\texttt{P-MLM}})$$ $$\hat{d_{i}}= \mathrm{argmax}_w {Pr(w|X)} $$ The loss function for P-MLM is $$\underset{\theta}{\text{minimize}}-\sum_{\forall (C, D)}\phi_{_{\texttt{P-MLM}}}(C,D)$$ $$\phi_{_{\texttt{P-MLM}}}(C,D)=\sum_{\forall d_i}\text{log}_2p(d_i|{C, \mathrm{[\texttt{M}]_{d_j}};\theta})$$ We propose to jointly train P-MLM and BDG by the following multi-tasking loss function. Note that $\gamma$ is a hyper-parameter controlling the weighting of answer negative loss. See also the effect of the $\gamma$ value in Subsection \ref{subsec:parameter_study}. \begin{equation} \underset{\theta}{\text{Minimize}}-\sum_{\forall (C, D)}[\phi_{_{a.n.}}(C,D)+\gamma\cdot\phi_{_{\texttt{P-MLM}}}(C,D)] \label{eq:SLPL} \end{equation} The multi-task design is motivated by the following observations. First, as mentioned, we target at learning distractor generation from real reading comprehension examination (RACE-like MCQ), and we find that many questions in the RACE dataset are summary-oriented or making inferences about a certain detail in the article; That is, many questions ask like "what is the best title for this passage?" or "what is this passage about?" Such questions require the model to have capability of passage semantic summarization. While the original BDG scheme design successfully generates fluent question sentences, we find that it may over-fit in sentence writing and under-fit in learning the passage semantic understanding capability. Note that the sequential-MLM design (BDG) essentially is a one-by-one masked token prediction architecture. Such a method may over-focus on the guess of a single token and ignore the overall semantic understanding. Thus, we propose to incorporate the multitask learning setting to prevent the potential over-fitting problem. From the experiments, we find the multi-task learning setting indeed improves the quality of distractor generation. Also, in the experiment section, we show an ablation study to examine the various parameter setting to observe the effects on the distractor generation. \section{Multiple Distractor Generation}\label{sec:MDG} \subsection{Selecting Distractors by Entropy Maximization}\label{sec:EM} As mentioned, another point that can be improved for DG is that the existing methods mainly focus on single distractor generation. For having more than one distractor, the existing practices is to select the results on different beam search paths as multiple options for distractor generation, which lowers the power of distracting a reader for MCQ preparation. Our viewpoint is that we should deal with the multiple distractor selection problem by selecting a distractor set rather than individually selecting top-k distractors based on prediction probability. Based on this view, we propose to incorporate a multi-choice reading comprehension (MRC) model for ranking/selecting distractor sets. First, let $\mathbb{M}_{\texttt{MRC}}$ be a MRC model. Note that $\mathbb{M}_{\texttt{MRC}}$ takes a passage $P$, a question $Q$, and a set of options (including an answer phrase $A$ and distractors $D_1, D_2, ..., D_n$) as input and outputs [$p_A, p_{D_1}, ...,p_{D_n}$] as the answer probabilities of the options. $\mathbb{M}_{\texttt{MRC}}$ is trained by maximizing the answer probability $p_A$ while minimizing the probabilities [$p_{D_1}, ...,p_{D_n}$]. With $\mathbb{M}_{\texttt{MRC}}$, our idea is as follows. First, let $\mathbb{DG}_{\texttt{BDG}}$ be the BDG model for distractor generation. Also, let $\hat{D}=\{\hat{d}_1, \hat{d}_2, ..., \hat{d}_n\}$ be the set of generated distractors by the BDG model. In a common MCQ setting, there are four options (one answer $A$ and three distractors $d_i, d_j, d_k$) for each question. Our idea is to enumerate all possible triples from $\{\hat{d}_1, \hat{d}_2, ..., \hat{d}_n\}$. That is, we have a triple set \[ \{ (d_i, d_j, d_k)| i\neq j\neq k, d_i, d_j, d_k \in \hat{D} \} \] For a given passage $P$, question $Q$, and answer $A$, the goal is to find a triple ($d_i, d_j, d_k$) to form an option set $O$ (i.e., \{$d_i, d_j, d_k$, $A$\} ) that maximizes the following entropy function. \begin{equation}\label{eq:entropy} \underset{}{\text{maximize}}-\sum_{\forall o_i\in O}p_{o_i}log_2p_{o_i} \end{equation} \subsection{Model Ensemble}\label{sec:model-ensemble} The idea of selecting distractors by entropy maximization can be further generalized by employing multiple DG models. For having multiple DG models, our idea is to leverage the variants of the BDG model (i.e., models with/without answer negative regularization or with/without P-MLM multi-task training). Let $\hat{D}, \hat{D}_{\texttt{AN}}$, and $\hat{D}_{\texttt{PM}}$ be the full DG model, the DG model without answer negative regularization, and the DG model without P-MLM multi-task training. With the models, our goal then is to enumerate all possible triples from $\{\hat{d}_1, \hat{d}_2, ..., \hat{d}_n\}$. That is, we have a triple set as follows. \[ \{ (d_i, d_j, d_k)| d_i \in \hat{D}, d_j \in \hat{D}_{\texttt{AN}}, d_k \in \hat{D}_{\texttt{PM}} \} \] With the triple set, the options set that maximizes Eq. (\ref{eq:entropy}) is selected as final distractors. \section{BERT Distractor Generation}\label{sec:BDG} \subsection{BERT Model Review} The BERT model and its family \cite{liu2019roberta,lan2019albert} are composed of a stack of multi-layer bidirectional Transformer encoders. The input to a BERT model is a sequence of tokens. For a given token, its input representation to the BERT model is first constructed by summing the corresponding token, segment, and position embeddings. After the input representation, the input embeddings travel through the pre-trained/fine-tuned BERT for task learning and prediction. In general, BERT can be employed in two-level language modeling tasks: sequence-level classification and token-level prediction tasks. For the tasks, there are three special tokens, \texttt{[C]}, \texttt{[S]}, and \texttt{[M]}. The embedding of the \texttt{[C]} token is designed to be used as the aggregate sequence representation for classification tasks. The \texttt{[S]} is designed to distinguish different sentences of a token sequence (to provide/signal information from multiple sentences, as the input token sequence can be a pack of multiple sentences). On the other hand, the \texttt{[M]} token is designed to be used in token-level prediction (e.g., predicting a masked token based on context words or predicting the starting/ending probabilities for span-based tasks such as QA tasks). As reported in \cite{chan2019recurrent, dong2019unified}, BERT essentially is an auto-encoder language modeling design, which aims to reconstruct the original data from corrupted inputs. If BERT is asked to predict a sequence of consecutive masked tokens, it often produces incoherent and ramble results. For example, when using BERT to predict three consecutive $\mathrm{\texttt{[M]}}\mathrm{\texttt{[M]}}\mathrm{\texttt{[M]}}$ masked tokens, the same prediction result for the tokens are often observed. This is because the context (the information for predicting the tokens) for the masked tokens are nearly the same except for the position embedding, making the generated sentences incoherent. Thus, we take into consideration the previous decoded results for decoding the next distractor token, as will be introduced in the next subsection. \begin{table*} \centering \begin{tabular}{|l|l|l|} \hline Iter. & Input Sequence & Predict \\ \hline 1 & \texttt{[C] $C$ [S][M]} & Because \\ \hline 2 & \texttt{[C] $C$ [S]} Because \texttt{[M]} & Henry \\ \hline 3 & \texttt{[C] $C$ [S]} Because Henry \texttt{[M]} & didn't \\ \hline 4 & \texttt{[C] $C$ [S]} Because Henry didn't \texttt{[M]} & want \\ \hline 5 & \texttt{[C] $C$ [S]} Because Henry didn't want \texttt{[M]} & to \\ \hline 6 & \texttt{[C] $C$ [S]} Because Henry didn't want to \texttt{[M]} & go \\ \hline 7 & \texttt{[C] $C$ [S]} Because Henry didn't want to go \texttt{[M]} & . \\ \hline 8 & \texttt{[C] $C$ [S]} Because Henry didn't want to go.\texttt{[M]} & \texttt{{[}S{]}} \\ \hline \end{tabular} \caption{A Running Example for the BDG scheme} \label{tab:dg} \end{table*} \subsection{BERT-based Distractor Generation (BDG)}\label{sec:BDG_architecture} In a distractor generation scenario, there are three given inputs: (1) a paragraph $P$, (2) an answer $A$, and (3) a question $Q$. For ease of discussion, let $C$ (referred to as a context sequence) denote the sequence of tokens given by concatenating $P$, $Q$, and $A$. Our BDG model generates distractor tokens in an auto-regressive manner. Specifically, the BDG model predicts a token at a time based on (1) the given context sequence $C$ and (2) the previously predicted distractor tokens. The BDG model takes multiple iterations to generate a distractor. In Table \ref{tab:dg}, we show a running example of the BDG model. Note that our model predicts a token based on $C$ and the previously generated tokens at each iteration. For example, at Iteration 1, we generate "Because" based on $C$. At Iteration 2, we generate "Henry" based on $C$ and "Because" tokens, and Iteration 3, we generate "didn't" based on $C$, "Because", and "Henry". The generation terminates when \texttt{[S]} is predicted. In this example, "Because Henry didn't want to go." is the final generated result. Specifically, the input sequence $X_{i}$ at Iteration $i$ to BERT is \[ \begin{split} X_{i} = (\mathrm{\texttt{[C]}}, C, \mathrm{\texttt{[S]}},\hat{d_{1}}, ...,\hat{d_{i}},\mathrm{\texttt{[M]}}) \end{split} \] Let $\mathbf{h}_{\texttt{[M]}} \in \mathbb{R}^h$ denote the hidden representation of \texttt{[M]} of $X_{i}$ returned by BERT transformer stacks. The prediction of $\hat{d_i}$ is given by a linear layer transformation $\mathbf{W}_{\texttt{DG}} \in \mathbb{R}^{h\times |V|}$ and a softmax activation to all vocabulary dimension as follows. $$p(w|X_i) = softmax(\mathbf{h}_{\texttt{[M]}}\cdot\mathbf{W}_{\texttt{DG}}+\mathbf{b}_{\texttt{DG}})$$ $$\hat{d_{i+1}}= \mathrm{argmax}_w {Pr(w|X_i)} $$ Subsequently, the newly generated token $\hat{d_i}$ is appended into $X_{i+1}$ and the distractor generation process is repeated based on the new $X_{i+1}$ until \texttt{[S]} is predicted. Our loss function is as follows. $$\underset{\theta}{\text{minimize}}-\sum_{\forall (C, D)} \sum_{i=0}^{|D|}(\text{log}_2p(d_{i+1}|{C, d_{1:i};\theta}))$$ \subsection{Multi-task with Parallel MLM} From the experiment results (will be presented in the later section), we see the BDG model advances the state-of-the-art result \cite{zhou2019coattention} from 28.65 to 35.30 (BLEU 1 score). While the token-level evaluation result looks promising, we find that generation results still have room to be improved. For performance improvement, we first propose to jointly train BDG and a parallel MLM (P-MLM) architecture for distractor generation to enhance the quality of BDG. The P-MLM scheme for generating distractors is structured as follows. For a given context $C$, the input sequence $X$ to P-MLM model is formulated as \[ \begin{split} X = (\mathrm{\texttt{[C]}}, C, \mathrm{\texttt{[S]}}, \mathrm{[\texttt{M}]_{d_1}}, \mathrm{[\texttt{M}]_{d_2}}, ...,\mathrm{[\texttt{M}]_{d_{|D|}}}) \end{split} \] Let $\mathbf{h}_{\mathrm{\texttt{[M]}_{d_i}}} \in \mathbb{R}^h$ denote the hidden representation of $\mathrm{\texttt{[M]}_{d_i}}$ of $X$ returned by BERT transformer stacks. The prediction of $\hat{q_i}$ is given by a linear layer transformation $\mathbf{W}_{\texttt{P-MLM}} \in \mathbb{R}^{h\times |V|}$ and applying a softmax activation to all vocabulary dimension as follows. $$p(w|X) = softmax(\mathbf{h}_{\mathrm{[\texttt{M}]_{d_i}}}\cdot\mathbf{W}_{\texttt{P-MLM}}+\mathbf{b}_{\texttt{P-MLM}})$$ $$\hat{d_{i}}= \mathrm{argmax}_w {Pr(w|X)} $$ The loss function for P-MLM is $$\underset{\theta}{\text{minimize}}-\sum_{\forall (C, D)}\phi_{_{\texttt{P-MLM}}}(C,D)$$ $$\phi_{_{\texttt{P-MLM}}}(C,D)=\sum_{\forall d_i}\text{log}_2p(d_i|{C, \mathrm{[\texttt{M}]}_{d_i};\theta})$$ We propose to jointly train P-MLM and BDG by the following multi-tasking loss function. Note that $\gamma$ is a hyper-parameter controlling the weighting between the two tasks. See also the effect of the $\gamma$ value in Subsection \ref{subsec:parameter_study}. $$ \underset{\theta}{\text{minimize}}-\sum_{\forall (C, D)}[\phi_{_{\texttt{BDG}}}(C,D)+\gamma\cdot\phi_{_{\texttt{P-MLM}}}(C,D)] ,$$ $$ \phi_{_{\texttt{BDG}}}(C,D)=\sum_{i=0}^{|D|}(\text{log}_2p(d_{i+1}|{C, d_{1:i};\theta})) $$ The multi-task design is motivated by the following observations. First, as mentioned, we target at learning distractor generation from real reading comprehension examination (RACE-like MCQ), and we find that many questions in the RACE dataset are summary-oriented; many questions are about "what is the best title for this passage?" or "what is this passage about?" Such questions require the model to have the capability of passage semantic summarization. While the original BDG scheme design successfully generates fluent question sentences, we find that it may over-fit in sentence writing and under-fit in learning the passage semantic understanding capability. Note that the sequential-MLM design (BDG) essentially is a one-by-one masked token prediction architecture. Such a method may over-focus on the guess of a single token and ignore the overall semantic understanding. Thus, we propose to incorporate the multi-task learning setting to prevent the potential over-fitting problem. From the experiments, we find the multi-task learning setting indeed improves the quality of distractor generation. \subsection{Answer Negative Regularization} In addition to the multi-task design, from the DG result examination, we find another observation that in many cases, there is an \textit{answer copying problem}; the generated distractors are similar to the given answers. To better see this phenomenon, we experiment to count such cases. In the following table, we show the number of cases that the generated distractor $\hat{D}$ has a token-level similarity score greater than $0.95$ with respect to the answer $A$. We also show the cases for the gold distractors (the human-invented distractors from the RACE dataset). By comparison in Table \ref{tab:ARPM}, there is a significant gap between the human-invented distractors and the model generated ones. \begin{table} \centering \begin{tabular}{|l|l|l|} \hline & P.M. & Gold \\ \hline \# of cases on BLEU 1 & 57 & 12 \\ \hline \# of cases on BLEU 2 & 55 & 4 \\ \hline \# of cases on BLEU 3 & 48 & 0 \\ \hline \# of cases on BLEU 4 & 35 & 0 \\ \hline \# of cases on ROUGE-L & 55 & 1 \\\hline \end{tabular} \caption{Answer Copying Problem on P.M.} \label{tab:ARPM} \end{table} Motivated by the answer copying problem, we propose to incorporate a loss (referred to as \textit{answer negative loss}) to discourage predicting tokens in $A$ when predicting $\hat{d_i}$. With the answer negative loss, our loss function for BDG is as follows. \begin{equation} \begin{split} &\underset{\theta}{\text{minimize}}-\sum_{\forall (C, D)}(\phi_{_{\texttt{AN}}}(C,D)+\gamma\cdot\phi_{_{\texttt{P-MLM}}}(C,D)), \\ & \begin{split} \phi_{_{\texttt{AN}}}=&\sum_{i=0}^{|D|}(\text{log}_2p(d_{i+1}|{C,d_{1:i};\theta})+\\&\sum_{\forall a_j\in A}\text{log}_2(1-p(a_{j}|{C,\mathrm{[\texttt{M}]}_{a_j};\theta})) \end{split} \end{split} \label{eq:SLUL} \end{equation} The design of answer negative loss is motivated by that we expect to regulate the generated distractor $\hat{D}$ to use words different from $A$. The overall architecture for training our BDG model is shown in Figure \ref{fig:Multi_task}. The core structure for our distractor generation is mainly based on the sequential recurrent MLM decoding mechanism. That is, during the the testing stage, we use the results from the sequential recurrent MLM decoding part. However, during the training stage, we incorporate the parallel MLM decoding mechanism by jointly considering answer negative regularization and sentence-level distractor loss, as shown in the right-part of the architecture in Figure \ref{fig:Multi_task}. \begin{figure}[t] \centering \includegraphics[width=1.\columnwidth]{Architecture5.png} \caption{The Multi-tasking Architecture} \label{fig:Multi_task} \end{figure} \section{Multiple Distractor Generation}\label{sec:MDG} \subsection{Selecting Distractors by Entropy Maximization}\label{sec:EM} As mentioned, another point that can be improved for DG is that the existing methods mainly focus on single distractor generation. For having more than one distractor, the existing practices are to select the results on different beam search paths as multiple options for distractor generation, which lowers the power of distracting a reader for MCQ preparation. Our viewpoint is to select a distractor set (by considering semantic diversity) rather than individually selecting top-k distractors based on prediction probability. Based on this view, we propose to incorporate a multi-choice reading comprehension (MRC) model for ranking/selecting distractor sets. First, let $\mathbb{M}_{\texttt{MRC}}$ be a MRC model. Note that $\mathbb{M}_{\texttt{MRC}}$ takes a passage $P$, a question $Q$, and a set of options (including an answer $A$ and distractors $D_1, D_2, ..., D_n$) as input and outputs [$p_A, p_{D_1}, ...,p_{D_n}$] as the answer probabilities of the options. $\mathbb{M}_{\texttt{MRC}}$ is trained by maximizing the answer probability $p_A$ while minimizing the probabilities [$p_{D_1}, ...,p_{D_n}$]. With $\mathbb{M}_{\texttt{MRC}}$, our idea is as follows. First, let $\mathbb{DG}_{\texttt{BDG}}$ be a BDG model for distractor generation. Also, let $\hat{D}=\{\hat{d}_1, \hat{d}_2, ..., \hat{d}_n\}$ be the set of generated distractors by the BDG model. In a common MCQ setting, there are four options (one answer $A$ and three distractors $d_i, d_j, d_k$) for each question. Our idea is to enumerate all possible triples from $\{\hat{d}_1, \hat{d}_2, ..., \hat{d}_n\}$. That is, we have a triple set \[ \{ (d_i, d_j, d_k)| i\neq j\neq k, d_i, d_j, d_k \in \hat{D} \} \] For a given passage $P$, question $Q$, and answer $A$, our goal is to find a triple ($d_i, d_j, d_k$) to form an option set $O$ (i.e., \{$d_i, d_j, d_k$, $A$\} ) that maximizes the following entropy function. \begin{equation}\label{eq:entropy} \underset{}{\text{maximize}}-\sum_{\forall o_i\in O}p_{o_i}log_2p_{o_i} \end{equation} \subsection{BDG-EM}\label{sec:model-ensemble} The idea of selecting distractors by entropy maximization can be further generalized by employing multiple DG models. For having multiple DG models, our idea is to leverage the variants of the BDG model (i.e., models with/without answer negative regularization or with/without both answer negative regularization and P-MLM multi-task training). Let $\hat{D}, \hat{D}_{\texttt{PM}}$, and $\hat{D}_{\texttt{PM+AN}}$ be the BDG model without both answer negative regularization and P-MLM multi-task training, the BDG model without answer negative regularization, and the full BDG model. That is, we have a triple set as follows. \[ \{ (d_i, d_j, d_k)| d_i \in \hat{D}, d_j \in \hat{D}_{\texttt{PM}}, d_k \in \hat{D}_{\texttt{PM+AN}} \} \] With the triple set, the set that maximizes Eq. (\ref{eq:entropy}) is selected as final distractors. \section{Introduction} The sentence classification problem in scientific abstracts is motivated by the need for effectively extracting useful information from the scientific literature. As suggested by previous research \cite{jin2018hierarchical,dernoncourt2016neural}, the article retrieving process can be expedited if scientific abstracts can be categorized into different rhetorical sections. Specifically, for a given set of sentences in an abstract \{$s_0$, $s_1$, ..., $s_n$\}, the goal is to predict $s_i$, for all $i$, a rhetorical-section label $l$ $\in$ $L$. The labels indicate the rhetorical structural elements of a sentence in a scientific abstract such as \textit{purpose}, \textit{method}, \textit{result}, or \textit{conclusion}. The problem of classifying sentences in scientific abstracts have been explored in many prior studies \cite{dernoncourt2016neural, jin2018hierarchical, hassanzadeh2014identifying,hirohata2008identifying}. As opposed to prior work, we propose to approach the scientific abstract classification problem as a reading comprehension (RC) task. Specifically, our idea is to train a RC model that takes an abstract and a \textit{label question} (the label question acts like a reading comprehension question, e.g., where are the \textit{method}-related sentences?) as input and produces a text span as output. By casting the sentence classification problem as a RC problem, this paper makes two concise contributions toward scientific abstract sentence classification. First, the paper presents a new SOTA for sentence classification of scientific abstracts using the BERT model. We show that by reformulating the sentence classification problem as a reading comprehension problem, we push the state-of-the-art results from 92 to 96.1 (the F$_{1}$ score). Second, we do not only presenting another "BERT beats everything" before, but also conduct ablations to reveal that the model benefits from the altered training goal of question answering (actually token position prediction) instead of contextual or naïve sentence classification, and that robustness can be achieved by altering sentence order during training. \section{Sentence Classification as RC Task}\label{sec:method} Our model (called BERT-QA) takes (1) an abstract [$s_1$, ..., $s_{n}$] and (2) a label token $L$ as inputs, and then predict a span index [$i$, $j$] in the abstract indicating the text span belongs to the $L$-related section. The model architecture is shown in Figure \ref{fig:bertqa}. We adopt the BERT model as our fundamental building block as follows. First, the input sequence is aligned as \[x=(\texttt{[CLS]}, \texttt{[Label]}, \texttt{[SEP]}, s_1, ..., s_{n}, \texttt{[SEP]})\] Note that $s_i$ is a sequence of word tokens [$w_{i,j}$], where $j=1, ..., |s_i|$. Then we obtain final hidden representation $\mathbf{H}\in \mathbb{R}^{|x|\times h}$ of $x$ through BERT model. The hidden representation is passed to two separate dense layers followed by softmax functions to compute the $Pr(s|w_{i,j})$ and $Pr(e|w_{i,j})$ for $w_{i,j}$ as follows. $Pr(s|w_{i,j}) = softmax(\mathbf{H}\cdot\mathbf{W}_{_{s}}+\mathbf{b}_{_{s}})$ and $Pr(e|w_{i,j}) = softmax(\mathbf{H}\cdot\mathbf{W}_{_{e}}+\mathbf{b}_{_{e}})$ where $\mathbf{W}_{s},\mathbf{W}_{e} \in \mathbb{R}^{h}$, $\mathbf{b}_{s},\mathbf{b}_{e} \in \mathbb{R}$, and a \textit{softmax} function is applied along the dimension of the sequence. With the probabilities, a valid text span with a maximal joint probability is reported as the asked label span $a$ = $[x_s, ..., x_e]$. \subsection{Performance Evaluation}\label{sec:Bert-QA-Result} \noindent\textbf{Compared Models} In this paper, we compare our models with the best performing models \cite{jin2018hierarchical}, HSLN: Hierarchical Sequential Labeling Network proposed by \cite{jin2018hierarchical}. There are two variants of the HSLN model: HSLN-RNN and HSLN-CNN. The difference between HSLN-RNN and HSLN-CNN is the choice of the sentence embedding (using bi-RNN or CNN) in the HSLN. The HSLNs are the state-of-the-art models for sentence classification problem. \noindent\textbf{Datasets}\label{sec:dataset} For performance comparison, we use the same datasets and settings as the state-of-the-art models \cite{jin2018hierarchical}. In \cite{jin2018hierarchical}, the performance evaluation is conducted based on two benchmarking datasets, PubMed RCT (shared by \cite{dernoncourt2017pubmed}) and NICTA-PIBOSO (shared from the ALTA 2012 Shared Task \cite{amini2012overview}), where each sentence of the abstract is annotated with one label indicating the rhetorical role of a sentence. Further, the PubMed dataset is divided into two subsets, PubMed 20k and PubMed 200k. \begin{figure}[t] \centering \includegraphics[width=0.6\columnwidth]{bertqa.png} \caption{The Bert-QA Architecture} \label{fig:bertqa} \end{figure} \begin{table} \centering\tiny \begin{tabular}{@{}lccc@{}} \toprule \textbf{Model} & \textbf{PM 20k} & \textbf{PM 200k} & \textbf{NICTA} \\ \midrule HSLN-CNN & 89.3 & 90.6 & 80.1 \\ HSLN-RNN & 92.0 & 93.9 & 84.0 \\ \bottomrule BERT-QA & \textbf{96.1} & \textbf{97.6} & \textbf{89.3} \\ \bottomrule \end{tabular} \caption{Comparison of F$_{1}$ scores between our model and the best-published methods.} \label{table:comparison_of_f1_simple} \end{table} \begin{table} \centering \tiny \begin{tabular}{|l|c|c|c|c|c|c|c|} \hline & \multicolumn{3}{c|}{\textbf{BERT-QA}} & \multicolumn{3}{c|}{\textbf{HSLN-RNN}} & \\ \hline \textbf{Label} & \textbf{P} & \textbf{R} & \textbf{F$_{1}$} & \textbf{P} & \textbf{R} & \textbf{F$_{1}$} & \textbf{Support} \\ \hline Background & 86.7 & 99.1 & 92.5 & 74.4 & 83.8 & 78.8 & 2676 \\ \hline Objectives & 94.6 & 88.6 & 91.5 & 76.0 & 61.1 & 67.8 & 2043 \\ \hline Methods & 97.8 & 98.0 & 97.9 & 95.0 & 97.2 & 96.1 & 8297 \\ \hline Results & 97.1 & 95.3 & 96.2 & 96.4 & 95.1 & 95.7 & 8056 \\ \hline Conclusions & 98.5 & 95.6 & 97.0 & 97.4 & 96.7 & 97.1 & 3952 \\ \hline \textbf{Total} & \textbf{96.2} & \textbf{96.1} & \textbf{96.1} & \textbf{92.1} & \textbf{92.1} & \textbf{92.0} & \textbf{25024} \\ \hline \end{tabular} \caption{The performance scores (precision (P), recall (R), and F$_{1}$-measure (F$_{1}$), presented in percentage) on the PubMed 20k dataset.} \label{table:class_report_pm20k} \end{table} \noindent\textbf{Performance Result Overview} Table \ref{table:comparison_of_f1_simple} shows the comparison results against the previous state-of-the-art models. We have the following findings to note. First, as shown, our BERT-QA model outperforms the previous best-published results. The BERT-QA achieves the best performing results, which improves the F$_{1}$-scores by 4\%-6\% compared with HSLN-RNN. Furthermore, Table \ref{table:class_report_pm20k} shows the precision, recall and F$_{1}$-measure for the compared models on PubMed 20k dataset. Comparing these two models, the results show that both models are good at predicting the labels \textit{Methods}, \textit{Results}, and \textit{Conclusions}. For the labels \textit{Background} and \textit{Objectives}, our BERT-QA shows significant advantages over the HSLN model; the F$_{1}$ scores of our BERT-QA model are 92.5 and 91.5, while HSLN provides only 78.8 and 67.8. \noindent\textbf{Confusion Matrix Comparison} Table \ref{table:confusion_matrix_HSLN-RNN_pm20k} and Table \ref{table:confusion_matrix_bertqa_pm20k} further show the confusion matrix for our BERT-QA model and HSLN-RNN respectively, where Rows correspond to true labels, and columns correspond to predicted labels. B represents background, O represents objectives, M represents methods, R represents results, and C represents conclusions. From the tables, we see that it is challenging for HSLN-RNN to distinguish between \textit{Background} and \textit{Objectives}. 15\% of the \textit{Background} sentences are incorrectly classified as \textit{Objectives} ones, and 35\% of the \textit{Objectives} sentences are classified as \textit{Background}. This somehow makes sense as the rhetorical roles of \textit{Objectives} and \textit{Background} are similar to some extent. In comparison, we see that BERT-QA shows good performance on these two labels. We consider the reason for this result may come from global attention on the whole abstract empowered by BERT. \begin{table} \centering \begin{subtable}{2in} \tiny \begin{tabular}{|c|c|c|c|c|c|} \hline & \textbf{B} & \textbf{O} & \textbf{M} & \textbf{R} & \textbf{C} \\ \hline \textbf{B} & 2242 & 370 & 51 & 7 & 6 \\ \hline \textbf{O} & 731 & 1249 & 57 & 6 & 0 \\ \hline \textbf{M} & 36 & 24 & 8068 & 157 & 12 \\ \hline \textbf{R} & 3 & 0 & 306 & 7662 & 85 \\ \hline \textbf{C} & 2 & 0 & 9 & 118 & 3823 \\ \hline \end{tabular} \caption{HSLN-RNN}\label{table:confusion_matrix_HSLN-RNN_pm20k} \end{subtable} \quad \begin{subtable}{2in} \tiny \begin{tabular}{|c|c|c|c|c|c|} \hline & \textbf{B} & \textbf{O} & \textbf{M} & \textbf{R} & \textbf{C} \\ \hline \textbf{B} & 2653 & 1 & 20 & 2 & 0 \\ \hline \textbf{O} & 214 & 1809 & 19 & 1 & 0 \\ \hline \textbf{M} & 54 & 29 & 8128 & 85 & 1 \\ \hline \textbf{R} & 140 & 73 & 113 & 7673 & 57 \\ \hline \textbf{C} & 0 & 0 & 35 & 141 & 3776 \\ \hline \end{tabular} \caption{BERT-QA}\label{table:confusion_matrix_bertqa_pm20k} \end{subtable} \caption{Confusion matrix on the PubMed 20k}\label{table:1} \end{table} \section{Performance Gain Analysis}\label{sec:per} Given the promising result, the question then arises: is this another BERT beats everything case? Specifically, we investigate 1) \textit{is the improvement of performance mainly from the power of BERT?} 2) \textit{does our model tend to learn the sequential information between sentences for predictions, as it is easier to learn}. In the following subsection, we report our investigation and findings. \subsection{Does our model tend to learn the sentence order information for prediction?} To answer this question, we conduct a robustness testing experiment. Specifically, we experimentally change the order of the label-sections of abstracts in testing data set to see if there is a performance degradation for our BERT-QA model. In Figure \ref{fig:confusion_matrix_OBMRC} and Figure \ref{fig:confusion_matrix_BORMC}, we report the results by exchanging the order of \textit{Background} and \textit{Objective} sections and the results by exchanging the order of \textit{Method} and \textit{Result} sections, respectively. From the results, we observe some performance degradation in Figure \ref{fig:confusion_matrix_BORMC}. As shown. More than 40\% of \textit{Method} sentences are classified as \textit{Result} ones, and around 60\% of the \textit{Result} sentences are predicted as \textit{Method}-related ones. The results shows that the BERT-QA model mainly leverages sequential information between sentences for predictions. \subsubsection{Possibility of Using Semantic Information?} An interesting thing to note about the experiment result is that for \textit{Background} and \textit{Objective} labels, we observe there is no significant performance degradation (compared with the experiment by exchanging \textit{Method} and \textit{Result} section). We are curious about this result. By further investigation, we consider that the BERT-QA model can use semantic information between sentences for classification. In the benchmark dataset, we find that many medical abstracts have only “background” section without “objective” section (or the opposite); not all medical abstracts have both sections. In the face of this condition, our BERT-QA learns to leverage semantic information for prediction. In fact, the major performance improvement (compared with the HLSN method) comes from the improvement on the part of distinguishing “background” and “objective” sections. \subsubsection{Learning Regularization}\vspace{-3mm} From the above study is that we consider our BERT-QA model does have the ability to learn the semantic relationship between sentences. Therefore, to validate this observation, we experimentally randomly permute the order of the original rhetorical structure of an abstract in the training data and train the BERT-QA with this synthetic training data. Our goal is to regulate the model to learn semantic relationships to make prediction rather than excessively depending on sequential relationships. With the synthetic training data, we conduct the same robustness testings to evaluate the performance of our BERT-QA model trained by the synthetic training data. For ease of the discussion, we called the BERT-QA trained with the synthetic training data as \textit{RBERT-QA} (Robust BERT-QA). In Figure \ref{fig:confusion_matrix_OBMRC-R} and \ref{fig:confusion_matrix_BORMC-R}, we observe the RBERT-QA show performing results on the robust test experiment. The order of the rhetorical structure has no significant impacts on performance. We also show the evaluation with the original PubMed 20k testing data set. As shown in Table \ref{table:class_report_pm20k_bertqa_original_vs_rand}, We find that BERT-QA still provides promising results(with a slight performance degradation for F1 score (96.1$\rightarrow$95.1)). This interesting result shows that BERT-QA can capture semantic information for prediction (rather than relying on sentence orders). Further, although the RBERT-QA model loses 1\% in performance compared to the original BERT-QA model, we believe the RBERT-QA model will be a robust one for practical use. \noindent\textbf{Answers to Our First Question} We find that the original BERT-QA indeed tends to learn position information for prediction. However, by proper training regulation, we show that the BERT-QA can also leverage the semantic information for making the prediction. \begin{figure} \centering \begin{subfigure}{.2\textwidth} \centering \includegraphics[width=1.3\columnwidth]{confusion_matrix_OBMRC.png} \caption{} \label{fig:confusion_matrix_OBMRC} \end{subfigure} \begin{subfigure}{.2\textwidth} \centering \includegraphics[width=1.3\columnwidth]{confusion_matrix_BORMC.png} \caption{} \label{fig:confusion_matrix_BORMC} \end{subfigure} \caption{Model Robustness Test: (a) The result by exchanging \textit {B.} section and \textit {O.} section. (b) The result by exchanging \textit {M.} section and \textit {R.} section.} \label{fig:fig} \end{figure} \begin{figure}[htbp] \centering \begin{subfigure}{.2\textwidth} \centering \includegraphics[width=1.3\columnwidth]{confusion_matrix_random_OBMRC.png} \caption{} \label{fig:confusion_matrix_OBMRC-R} \end{subfigure} \begin{subfigure}{.2\textwidth} \centering \includegraphics[width=1.3\columnwidth]{confusion_matrix_random_BORMC.png} \caption{} \label{fig:confusion_matrix_BORMC-R} \end{subfigure} \caption{Robustness Test with RBERT-QA: (a) The result by exchanging \textit {B.} section and \textit {O.} section. (b) The result by exchanging \textit {M.} section and \textit {R.} section.} \label{fig:fig} \end{figure} \subsection{Is the improvement of performance mainly from the power of BERT?} To answer this question, we design another two BERT variants for the sentence classification. \noindent\textbf{BERT-C}\label{sec:Bert-C} In this model, we propose to formulate the sentence classification problem as a \textit{contextual} sentence classification problem; given a sentence and an abstract containing the sentence, the idea is to learn a BERT-based model to perform the sentence classification through contextual text understanding. With such a formulation, we design a BERT-based model (called BERT-C) that takes (1) a sentence $s_i$ and (2) an abstract of $n$ sentences (a sequence of sentences $[s_1, ..., s_n]$) as input and predicts a rhetorical section label for $s_i$. We expect BERT-C to understand the rhetorical role of a sentence with respect to the other sentences in an abstract. \noindent\textbf{Naive-BERT} We also experiment with a model that directly employs BERT for classification; Naive-BERT model takes only a single sentence as input and predicts/learns the sentence label by BERT. This model is implemented as a comparison baseline when BERT is employed. \begin{table}[h] \centering \tiny \begin{tabular}{|l|c|c|c|c|c|c|c|} \hline & \multicolumn{3}{c|}{\textbf{BERT-QA}} & \multicolumn{3}{c|}{\textbf{RBERT-QA}} & \\ \hline \textbf{Label} & \textbf{P} & \textbf{R} & \textbf{F$_{1}$} & \textbf{P} & \textbf{R} & \textbf{F$_{1}$} & \textbf{Support} \\ \hline Background & 86.7 & 99.1 & 92.5 & 87.1 & 96.9 & 91.7 & 2676 \\ \hline Objectives & 94.6 & 88.6 & 91.5 & 93.9 & 88.0 & 90.8 & 2043 \\ \hline Methods & 97.8 & 98.0 & 97.9 & 96.8 & 97.3 & 97.0 & 8297 \\ \hline Results & 97.1 & 95.3 & 96.2 & 95.7 & 94.5 & 95.1 & 8056 \\ \hline Conclusions & 98.5 & 95.6 & 97.0 & 97.1 & 94.1 & 95.6 & 3952 \\ \hline \textbf{Total} & \textbf{96.2} & \textbf{96.1} & \textbf{96.1} & \textbf{95.2} & \textbf{95.1} & \textbf{95.1} & \textbf{25024} \\ \hline \end{tabular} \caption{The scores for the BERT-QA model and RBERT-QA model on the PubMed 20k.} \label{table:class_report_pm20k_bertqa_original_vs_rand} \end{table} \begin{table}[t!] \centering\tiny \begin{tabular}{@{}lccc@{}} \toprule \textbf{Model} & \textbf{PM 20k} & \textbf{PM 200k} & \textbf{NICTA} \\ \midrule HSLN-CNN & 89.3 & 90.6 & 80.1 \\ HSLN-RNN & 92.0 & 93.9 & 84.0 \\ \bottomrule Naive-BERT & 86.2 & 88.5 & 75.5 \\ BERT-C & 91.9 & 94.3 & 83.3 \\ BERT-QA & \textbf{96.1} & \textbf{97.6} & \textbf{89.3} \\ \bottomrule \end{tabular} \caption{Comparison of F$_{1}$ scores between our model and the best-published methods.} \label{table:comparison_of_f1-1} \end{table} \begin{figure} \centering \includegraphics*[width=0.5\textwidth]{compare_pm20k_f1.png} \caption{F$_{1}$-measure comparison on pubmed 20k.} \label{fig:compare_pm20k_f1} \end{figure} \vspace{-5mm} \subsubsection{Comparison Result} We show the comparison results in Table \ref{table:comparison_of_f1-1} and Figure \ref{fig:compare_pm20k_f1}. We have the following observations. First, we find that the naive BERT employment (Naive-BERT) offers poor performance compared to other models. This results verifies the conclusion suggested by \cite{jin2018hierarchical} that taking into consideration the sequential information is critical to the sentence classification problem. Second, we found that our BERT-QA model achieved the best performance in all categories (except \textit{Conclusion}). As mentioned, we see the performance of predicting \textit {Background} and \textit {Objective} are significantly improved compared with HSLN. Third, The BERT-C model is comparable to the performance of the current best practices, i.e., HLSN-RNN, and outperforms HSLN-CNN. This result suggests that a part of performance gain comes from the BERT model. By further formulating the classification task into our proposed reading comprehension task, the state-of-the-art results are obtained, demonstrating the effectiveness of the proposed reformulation. \noindent\textbf{Answers to Our Second Question} While the BERT model is powerful, the naive model taking only information at a single sentence level offers poor performance, and our BERT model adoption considering context information effectively utilizes the BERT power, and advances the state-of-the-art of the sentence classification problem. \section{Conclusion}\label{sec:con}\vspace{-3mm} This work investigated the employment of the pre-trained BERT language model and proposed two models by adopting BERT models to reformulate the abstract sentence classification problem into two language understanding task variants:(1) contextual sentence classification and (2) machine reading comprehension task. We demonstrate that the proposed reading comprehension formulation is effective and serve as a new SOTA result. \section{Conclusion}\label{sec:conclusion} We present a state-of-the-art neural model based on a pre-trained transformer-based model for DG. We introduce two techniques, Answer Negative Regularization and Multi-task with Parallel MLM, to boost the DG performance. In addition, we also introduce BDG ensemble with an entropy maximization mechanism to enhance the DG quality by leveraging a reading comprehension model. By experimental evaluation, our models outperform the existing best performing models and advances the state-of-the-art result to 39.81 (BLEU 1 score). \section*{Acknowledgement} This work was supported by the Ministry of Science and Technology, Taiwan, under projects No. 109-2221-E-005-058-MY3 and 107-2221-E-005-064-MY2 \subsection{Discussion}\label{sec:disc} \subsection{Effectiveness of our a.n. and p.m. strategy} a.n. token score seems to be lowest to others\ref{tab:one distractor token score} but in have lowest repeating score. a.n. can faster get to lowest evaluation loss. \includegraphics[width=\linewidth]{loss_graph.png} the best setting of a.n. in loss with beta will be set as 1 \ref{tab:a.n. loss in diff setting}. \begin{table} \centering \begin{tabular}{|l|r|} \hline & \multicolumn{1}{l|}{Loss} \\ \hline a.n. beta 0.5 & 2.9975\% \\ \hline a.n. beta 1.0 & 2.9873\% \\ \hline a.n. beta 2.0 & 3.0007\% \\ \hline \end{tabular} \caption{a.n. loss in diff setting} \label{tab:a.n. loss in diff setting} \end{table} Testing in parameter, p.m. can give us higher token score, best setting is repeating in two times \begin{table} \centering \begin{tabular}{|l|r|} \hline & \multicolumn{1}{l|}{BLEU 4 Token score} \\ \hline without p.m. & 7.16 \\ \hline p.m. times 1 & 7.67 \\ \hline p.m. times 2 & 8.95 \\ \hline p.m. times 3 & 8.60 \\ \hline \end{tabular} \caption{p.m. token score in diff setting} \label{tab:p.m. token score in diff setting} \end{table} \subsection{Entropy selection} poor distractor options can make the questions almost trivial to solve we apply our entropy selection in multi-model distractor In this set of experimental results, we have two observations. First, the distractors generated by the random generation method are indeed not as effective as we expected. We can see that the accuracy has increased from 78\% to 88\%. Second, Although in the above experiments, we saw that the distractor produced by BDG has improved on the BLEU score compared to the existing methods. However, since the BLEU score is basically a similarity comparison based on the token level, it cannot completely represent the effect on semantic. using beam-search with beam-size 9 to test whether we need multiple models or not. this strategy have following benefit - parallel inference - better mrc score \section{Performance Evaluation}\label{sec:exp} \subsection{Experimental Settings} \noindent\textbf{Datasets} We follow the setting \cite{gao2019generating} to evaluate our framework with the RACE \cite{lai2017large} dataset. RACE contains 27,933 articles with 97,687 questions from English examinations of Chinese students from grade 7 to 12. We use data split setting from \cite{gao2019generating}. Table \ref{table:training data stat} reports the statistics for the test data set. All sentences are tokenized by the WordPiece tokenizer \cite{wu2016google}. \noindent\textbf{Implementation Details} Our models are implemented based on huggingface transformers framework \cite{Wolf2019HuggingFacesTS}. All experiments are based on bert-base-cased model. For optimization in the training, we use AdamW as the optimizer and the initial learning rate 5e-5 for all baselines and our model. The maximum number of epoch is set to 6 with a batch size of 30 on two RTX Titan GPUs. We also make our code and model available at \href{https://github.com/voidful/BDG}{https://github.com/voidful/BDG} \subsection{Compared Methods} In the experiments, we mainly compare the following distractor generation methods. \begin{itemize} \item \textbf{CO-Att.} We compare with the state-of-the-art method reported in \cite{zhou2019coattention}. The model is based on LSTM augmented by co-attention mechanism. \item \textbf{DS-Att.} We also compare with the method based on LSTM augmented by dynamic and static attention designed reported in \cite{gao2019generating}. This method is served as a baseline for distractor generation based on seq2seq RNN architectures. \item \textbf{GPT} We also experiment with a model based on GPT \cite{radford2018improving} to learn the distractor generation. This scheme can be served as a baseline based on transformer-based pre-trained model. \item \textbf{BDG} The scheme without the answer negative technique and parallel masked-LM multi-task training. \item \textbf{BDG$_\texttt{PM}$} The BDG scheme with the parallel masked-LM multi-task training ($\gamma=1$). \item \textbf{BDG$_\texttt{AN+PM}$} The BDG scheme with both techniques ($\gamma=1$). \end{itemize} \begin{table} \centering \begin{tabular}{ll} \midrule Train samples & 96501 \\ Test samples & 12284 \\ \midrule Avg.article length & 335.6 \\ Avg.distractor length & 8.6 \\ Avg.question length & 10.0 \\ Avg.answer length & 8.3 \\ \hline Avg.distractor number & 2.1 \\ \hline \end{tabular} \caption{Training Data Statistics} \label{table:training data stat} \end{table} \begin{table*} \centering \begin{tabular}{|l|l|l|l|l|l|} \hline & BLEU 1 & BLEU 2 & BLEU 3 & BLEU 4 & ROUGE L \\ \hline BDG$_\texttt{AN+PM}$ & 39.52 & 24.29 & 17.28 & 13.28 & 33.40 \\ \hline BDG$_\texttt{PM}$ & \textbf{39.81} & \textbf{24.81} & \textbf{17.66} & \textbf{13.56} & \textbf{34.01} \\ \hline BDG & 35.30 & 20.65 & 13.66 & 9.53 & 31.11 \\ \hline GPT & 36.49 & 20.75 & 13.31 & 9.31 & 31.59 \\ \hline DS-Att. & 27.32 & 14.69 & 9.29 & 6.47 & 15.12 \\ \hline CO-Att. & 28.65 & 15.15 & 9.77 & 7.01 & 15.39 \\ \hline \end{tabular} \caption{Performance Comparison on Token Scores} \label{tab:toke_score_overview} \end{table*} \begin{table*} \centering \begin{tabular}{|l|l|l|l|l|l|l|l|} \hline & BDG$_\texttt{AN+PM}$ & BDG$_\texttt{PM}$ & BDG & GPT & Gold & Random \\ \hline BLEU 1 & \textbf{43} & 57 & 115 & 124 & 12 & 0 \\ \hline BLEU 2 & \textbf{40} & 55 & 115 & 121 & 4 & 0 \\ \hline BLEU 3 & \textbf{37} & 48 & 109 & 109 & 0 & 0 \\ \hline BLEU 4 & \textbf{30} & 35 & 97 & 88 & 0 & 0 \\ \hline ROUGE-L & \textbf{42} & 55 & 122 & 123 & 1 & 0 \\ \hline \end{tabular} \caption{The Effect on Mitigating Answer Copying Problem} \label{tab:repeating-problem} \end{table*} \subsection{Token Score Comparison} We employ BLEU score \cite{papineni2002bleu} and ROUGE (L) \cite{lin2004rouge} scores to evaluate the performance of the compared methods. The BLEU scores evaluate average n-gram precision on a set of reference sentences, with a penalty for overly long sentences. The ROUGE (L) measure is the recall of longest common sub-sequences. The comparison results are summarized in Table \ref{tab:toke_score_overview}. There are three observations to note. First, one can see that our models significantly outperform the existing methods (i.e., DS-Att. and CO-Att.). Our best performing model advances the state-of-the-art result from 28.65 to 39.81 (BLEU 1 score). Second, as shown, the methods based on transformer models outperform the RNN-based models. This result again demonstrates the effectiveness of the employment of pre-trained transformer model to the downstream tasks. Third, one may notice that our models based on BERT outperforms the GPT-based model. We believe the reason is that the distractors in the RACE data set is mostly a summary type sentence that requires semantic understanding. The GPT-based model may over-focus on sentence writing, and fail to capture the whole context to generate summary-type sentences, and therefore obtain lower scores. We also provide experiment results to observe the effectiveness on reducing the answer copying problem discussed in Subsection \ref{sec:BDG}. In Table \ref{tab:repeating-problem}, we show the number of cases that the generated distractor $\hat{D}$ has a token-level similarity score greater than $0.95$ with respect to the context answer $A$. From the experiment result, we see that there are significant improvement made by the BDG schemes. \subsection{MCQ Model Accuracy Comparison} In this set of experiment, we evaluate the DG quality by the RACE reading comprehension task \cite{lai2017large}. Our idea is that a poorly generated DG result will reduce the difficulty of a MCQ task. Thus, we propose to incorporate a MCQ answering model (also trained by the RACE dataset) to evaluate the accuracy of a multiple-choice question with the distractors generated by the compared model. Specifically, given $C$, $Q$, and $A$, we generate three distractors $D_1$, $D_2$, and $D_3$, and then submit the multiple-choice question to the RACE model. Randomly generated results will be the easiest task to solve, and the best generated results will bring challenges to the MCQ model. Therefore, we use the accuracy of the model as a metric. The higher the accuracy, the worse the generation quality. The training details of the RACE model is as follows. We use PyTorch Transformers\cite{Wolf2019HuggingFacesTS} and the roberta-base-openai-detector fine-tuned by OpenAI \cite{solaiman2019release} with max 512 tokens to implement the model. AdamW with a Learning rate = 1e-5 is used for fine-tuning. The model is trained for 10 epoch on 2 GPUs (V100) with gradient accumulation per two steps, which makes the batch size approximately equal to 18. Model checkpoints are saved and evaluated on the validation set every 5,000 steps. We select the top checkpoint based on evaluation loss on the validations set. The RACE dataset includes middle and high dataset. The total number of passages and questions is 27,933 and 97,687 respectively. Middle dataset averages about 250 words per passage while the High dataset averages 350 words per passage. \begin{table} \centering \begin{tabular}{|l|r|} \hline & \multicolumn{1}{l|}{Accuracy} \\ \hline Random Selected Distractors & 88.10\% \\ \hline Gold Distractor & 78.00\% \\ \hline GPT & 78.07\% \\ \hline BDG & 73.96\% \\ \hline BDG$_\texttt{PM}$ & 74.34\% \\ \hline BDG$_\texttt{AN+PM}$ & 74.05\% \\ \hline BDG$_\texttt{EM}$ & \textbf{69.44\%} \\ \hline \end{tabular} \caption{Comparison by MCQ Accuracy} \label{tab:rc result} \end{table} In this set of experiment, we compare BDG, BDG$_\texttt{PM}$, BDG$_\texttt{AN+PM}$, the BDG model with entropy maximization (called BDG$_\texttt{EM}$) (introduced in Subsection \ref{sec:model-ensemble}) by setting the beam search size to 3, and the BDG model ensemble introduced in Subsection \ref{sec:model-ensemble}. In addition, we also experiment with the GPT, a scheme that takes randomly selected distractors from the data as the DG result, and the scheme uses the gold distractors. The results of the compared methods are summarized in Table \ref{tab:rc result}. We have the following findings to note about the results shown in Table \ref{tab:rc result}. First, as expected, the method with randomly selected distractors makes the MCQA model has the highest accuracy, as the randomly selected distractors obviously lower the difficulty of MCQ task. Second, all our models outperform the MCQ with the gold distractors, showing the effectiveness of the proposed models. Third, as expected, our BDG$_{\texttt{EM}}$ provides the best performing result on this metric. \subsection{Qualitative Examination by Case Study} In this subsection, we present showcases to see the improvement on multiple distractor generation scenario. We use the same examples introduced in Section \ref{sec:intro} for comparison. First, as mentioned, the naive employment of beam search strategy produces similar DG results. As shown in the examples, the distractors generated by BDG are about the same concept. However, as shown in Table \ref{tab:qualitative_Examination}, we see the BDG$_{\texttt{EM}}$ produce more diverse distractors with respect to each other. The results demonstrate the effectiveness of our BDG$_{\texttt{EM}}$ scheme for generating multiple distractors for MCQ preparation. \begin{table}[t] \resizebox{\linewidth}{!}{ \begin{tabular}{l} \textbf{Example 1} \\ \hline \multicolumn{1}{|l|}{\textbf{Context} Omitted. (See Appendix)} \\ \multicolumn{1}{|l|}{\textbf{Question}} \\ \multicolumn{1}{|l|}{$\cdot$ Why did Mr.King want to send Henry away?} \\ \multicolumn{1}{|l|}{\textbf{Answer}} \\ \multicolumn{1}{|l|}{\begin{tabular}[c]{@{}l@{}} $\cdot$ Because Henry was too lazy.\end{tabular}} \\\hline \multicolumn{1}{|l|}{\textbf{BDG}} \\ \multicolumn{1}{|l|}{$\cdot d_1:$ Because Henry didn't want to go.} \\ \multicolumn{1}{|l|}{$\cdot d_2:$ Because Henry didn't want to go to the bookstore.} \\ \multicolumn{1}{|l|}{$\cdot d_3:$ Because Henry didn't want to go out.} \\ \hline \multicolumn{1}{|l|}{\textbf{BDG$_{\mathbf{EM}}$}} \\ \multicolumn{1}{|l|}{$\cdot d_1:$ Because Henry didn't want to go.} \\ \multicolumn{1}{|l|}{$\cdot d_2:$ Because Henry wanted to be rich.} \\ \multicolumn{1}{|l|}{$\cdot d_3:$ Because Henry wanted to be a clever man.} \\ \hline \\ \textbf{Example 2} \\ \hline \multicolumn{1}{|l|}{\textbf{Context} Omitted. (See Appendix)} \\ \multicolumn{1}{|l|}{\textbf{Question}} \\ \multicolumn{1}{|l|}{$\cdot$ Which of the following women would look most attractive?} \\ \multicolumn{1}{|l|}{\textbf{Answer}} \\ \multicolumn{1}{|l|}{$\cdot$ A short red-haired woman who wears a purple hat.} \\\hline \multicolumn{1}{|l|}{\textbf{BDG}} \\ \multicolumn{1}{|l|}{$\cdot d_1:$ A young woman who wears a white hat.} \\ \multicolumn{1}{|l|}{\begin{tabular}[c]{@{}l@{}}$\cdot d_2:$ A woman who wears a white hat .\end{tabular}} \\ \hline \multicolumn{1}{|l|}{\textbf{BDG$_{\mathbf{EM}}$}} \\ \multicolumn{1}{|l|}{$\cdot d_1:$ A short black woman with big, round faces.} \\ \multicolumn{1}{|l|}{$\cdot d_2:$ A young woman who doesn’t like a white hat.} \\ \multicolumn{1}{|l|}{$\cdot d_3:$ A little woman who wears a pink hat.} \\ \hline \end{tabular} } \caption{Qualitative Examination by Case Study} \label{tab:qualitative_Examination} \end{table} \begin{table} \resizebox{\linewidth}{!}{ \centering \begin{tabular}{|l|l|l|l|l|l|} \hline & BLEU 1 & BLEU 2 & BLEU 3 & BLEU 4 & ROUGE L \\ \hline PM($\gamma$=1) & 36.97 & 22.07 & 14.82 & 10.50 & 32.64 \\ \hline PM($\gamma$=2) & 38.45 & 23.21 & 15.81 & 11.36 & 33.18 \\ \hline PM($\gamma$=3) & 39.23 & 24.27 & 17.04 & 12.78 & 33.82 \\ \hline PM($\gamma$=4) & 39.22 & 24.24 & 17.08 & 12.95 & 34.05 \\ \hline PM($\gamma$=5) & 39.74 & 24.50 & 17.29 & 13.09 & \textbf{34.11} \\ \hline PM($\gamma$=6) & \textbf{39.81} & \textbf{24.81} & \textbf{17.66} & \textbf{13.56} & 34.01 \\ \hline PM($\gamma$=7) & 39.37 & 24.13 & 17.09 & 13.07 & 33.45 \\ \hline AN+PM($\gamma$=1) & 37.49 & 22.08 & 13.73 & 10.44 & 32.40 \\ \hline AN+PM($\gamma$=2) & 38.25 & 22.81 & 15.33 & 10.91 & 32.99 \\ \hline AN+PM($\gamma$=3) & 38.71 & 23.54 & 16.26 & 12.04 & \textbf{33.82} \\ \hline AN+PM($\gamma$=4) & 38.84 & 23.70 & 16.57 & 12.46 & 33.53 \\ \hline AN+PM($\gamma$=5) & 39.19 &23.97 & 16.96 & 12.92 & 33.67 \\ \hline AN+PM($\gamma$=6) & \textbf{39.58} & 24.23 & 17.11 & 13.11 & 33.38 \\ \hline AN+PM($\gamma$=7) & 39.52 & \textbf{24.29} & \textbf{17.28} & \textbf{13.28} & 33.40 \\ \hline \end{tabular} } \caption{Performance Comparison on Token Scores with Different $\gamma$ Settings} \label{tab:toke_score_pm_overview} \end{table} \subsection{Parameter Study on $\gamma$}\label{subsec:parameter_study} In this subsection, we examine the effects on varying the values of the parameter $\gamma$. In Table \ref{tab:toke_score_pm_overview}, we show the results. From the result, we can see that the best setting for $\gamma$ is 6, and for BDG trained by answer negative and parallel-MLM, the best setting for $\gamma$ is 7. \section{Multiple Distractor Generation}\label{sec:MDG} \newcommand\BDGname{BDG~} \subsection{Selecting Distractors by Entropy Maximization}\label{sec:EM} As mentioned, another point that can be improved for QG is that the existing methods mainly focus on single distractor generation. For having more than one distractor, the existing practices is to select the results on different beam search paths as multiple options for distractor generation.However, the distractors generated in such a manner are essentially from the same latent representation, and might have similar tokens or semantics, which lowers the power of distracting a reader for MCQ preparation. In Table \ref{tab:my-table-mdg}, we show two examples for this problems. In the illustrated examples, one can observe that the generated distractors are with the same semantics with/without similar tokens. \begin{table}[ht] \resizebox{\linewidth}{!}{ \begin{tabular}{l} \textbf{Example 1} \\ \hline \multicolumn{1}{|l|}{\textbf{Question}} \\ \multicolumn{1}{|l|}{$\cdot$ After reading the passage, we may know that} \\ \multicolumn{1}{|l|}{\textbf{Answer}} \\ \multicolumn{1}{|l|}{\begin{tabular}[c]{@{}l@{}} $\cdot$ it is better if the website domain name is related to \\ the products you sell .\end{tabular}} \\ \multicolumn{1}{|l|}{\textbf{Gen. Distractors}} \\ \multicolumn{1}{|l|}{$\cdot d_1:$ it’s easy to start your business online} \\ \multicolumn{1}{|l|}{$\cdot d_2:$ it is easy to start a business online now} \\ \hline \\ \textbf{Example 2} \\ \hline \multicolumn{1}{|l|}{\textbf{Question}} \\ \multicolumn{1}{|l|}{$\cdot$ Which is Professor Jean Krutmann’ s opinion ?} \\ \multicolumn{1}{|l|}{\textbf{Answer}} \\ \multicolumn{1}{|l|}{$\cdot$We should take action to control air pollution} \\ \multicolumn{1}{|l|}{\textbf{Gen. Distractors}} \\ \multicolumn{1}{|l|}{$\cdot d_1:$ We should avoid air pollution.} \\ \multicolumn{1}{|l|}{\begin{tabular}[c]{@{}l@{}}$\cdot d_2:$ We should protect our environment from dirty \\ air.\end{tabular}} \\ \hline \end{tabular} } \caption{Examples for Distractors Selected by Beam Search: In these example, the distractors are with the same semantics} \label{tab:my-table-mdg} \end{table} Our viewpoint is that we should deal with multiple distractor selection problems from the perspective of set, rather than individually selecting top-k distractors based on prediction probability. In other words, we should choose a distractor set, which can maximize the difficulty of multiple-choice questions, rather than picking prediction results with the highest probability but with similar semantic. Based on this view, we propose to incorporate a multi-choice reading comprehension (MRC) model for ranking/selecting distractor sets. First, let $\mathbb{M}_{\texttt{MRC}}$ be a MRC model. Note that $\mathbb{M}_{\texttt{MRC}}$ takes a context passage $P$, a question $Q$, and a set of options (including an answer phrase $A$ and distractors $D_1, D_2, ..., D_n$) as input and outputs [$p_A, p_{D_1}, ...,p_{D_n}$] as the answer probabilities of the options with respect to the context passage $P$ and the question $Q$. $\mathbb{M}_{\texttt{MRC}}$ is trained by maximizing the answer probability $p_A$ while minimizing the probabilities [$p_{D_1}, ...,p_{D_n}$]. With $\mathbb{M}_{\texttt{MRC}}$, our idea is as follows. First, let $\mathbb{DG}_{\texttt{BDG}}$ be the BDG model for distractor generation. Also, let $\hat{D}=\{\hat{d}_1, \hat{d}_2, ..., \hat{d}_n\}$ be the set of generated distractors by the BDG model. In a common MCQ setting, there are four options (one answer $A$ and three distractors $d_i, d_j, d_k$) for each question. Our idea is to enumerate all possible triples from $\{\hat{d}_1, \hat{d}_2, ..., \hat{d}_n\}$. That is, we have a triple set \[ \{ (d_i, d_j, d_k)| i\neq j\neq k, d_i, d_j, d_k \in \hat{D} \} \] For a given passage $P$, question $Q$, and answer $A$, the goal is to find a triple ($d_i, d_j, d_k$) to form an option set $O$ (i.e., \{$d_i, d_j, d_k$, $A$\} ) that maximizes the following entropy function. \begin{equation}\label{eq:entropy} \underset{}{\text{maximize}}-\sum_{\forall o_i\in O}p_{o_i}log_2p_{o_i} \end{equation} \subsection{Model Ensemble}\label{sec:model-ensemble} The idea of selecting distractors by entropy maximization can be further generalized by employing multiple DG models. For having multiple DG models, our idea is to leverage the variants of the \BDGname model (i.e., models with/without answer negative regularization or with/without P-MLM multi-task training). Let $\hat{D}, \hat{D}_{_{ \neg A.}}$, and $\hat{D}_{_{\neg P.}}$ be the full DG model, the DG model without answer negative regularization, and the DG model without P-MLM multi-task training. With the models, our goal then can be to enumerate all possible triples from $\{\hat{d}_1, \hat{d}_2, ..., \hat{d}_n\}$. That is, we have a triple set as follows. \[ \{ (d_i, d_j, d_k)| d_i \in \hat{D}, d_j \in \hat{D}_{_{ \neg A.}}, d_k \in \hat{D}_{_{\neg P.}} \} \] With the triple set, the options set that maximizes Eq. (\ref{eq:entropy}) is selected as final distractors. \section{Preliminaries}\label{sec:preliminaries} \subsection{Problem Formulation} Formally, let $P$ denote the input context passage and $Q$ denote the question and $A$ the corresponding answer, respectively. The DG task is defined as generating a distractor $D$ as follows. \begin{equation} \hat{D} = \mathrm{argmax}_{D}\; log_2 p(D|P, Q, A) \end{equation} \subsection{BERT Model Review} The BERT model and its family \cite{liu2019roberta,lan2019albert} are composed of a stack of multi-layer bidirectional Transformer encoders. The input to a BERT model is a sequence of tokens. For a given token, its input representation to BERT model is first constructed by summing the corresponding token, segment, and position embeddings. After the input representation, the input embeddings travel through the pre-trained/fine-tuned BERT for task learning and prediction. In general, BERT can be employed in two-level language modeling tasks: sequence-level classification and token-level prediction tasks. For the tasks, there are three special tokens, \texttt{[C]}, \texttt{[S]}, and \texttt{[M]}. The embedding of the \texttt{[C]} token is designed to be used as the aggregate sequence representation for classification tasks. The \texttt{[S]} is designed to distinguish different sentences of a token sequence (to provide/signal information from multiple sentences, as the input token sequence can be a pack of multiple sentences). On the other hand, the \texttt{[M]} token is designed to be used in token-level prediction (e.g., predicting a masked token based on context words or predicting the starting/ending probabilities for span-based tasks such as QA tasks).
{'timestamp': '2020-10-13T02:26:46', 'yymm': '2010', 'arxiv_id': '2010.05384', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05384'}
arxiv
\section{Introduction} The rise of pre-trained language models \cite{devlin2019bert, radford2019language} has led to strong text generation models for applications including summarization \cite{dong2019unified,Lewis2019BARTDS}, paraphrasing \cite{Goyal-Durrett:2020:Syntaxparaphrase, shen2020neural}, story generation \cite{mao2019improving}, and data augmentation \cite{wei2018fast, zhang2019addressing}. However, while these models generate fluent and grammatical text, they are prone to making factual errors that contradict the input text \cite{cao2018faithful}. Automatic metrics used to evaluate text generation, such as ROUGE and BERTScore \cite{Zhang2020BERTScore}, are not correlated with the factual consistency or faithfulness of the generated text \cite{falke2019ranking, kryscinski2019neural}. To address this, recent work has studied the use of textual entailment models to rank and filter non-factual generations \cite{falke2019ranking, maynez2020faithfulness}. However, these models suffer from issues such as dataset biases \cite{gururangan2018annotation,zhou2020towards} and a mismatch between the training data (entailment) and the test data (model generations). \begin{figure} \centering \includegraphics[trim=70mm 60mm 50mm 35mm,scale=0.30,clip]{dae_overview.pdf} \caption{Overview of our dependency arc entailment formulation using a filtered set of Stanford Enhanced Dependencies. The DAE model makes independent factuality decisions for each dependency arc from the two generated hypotheses.} \label{fig:overview} \end{figure} In this paper, we propose to decompose entailment decisions in a sentence to evaluate the faithfulness of generated text in a more fine-grained way. Rather than making a sentence-level entailment decision, we instead evaluate the entailment of dependency arcs of the generated sentence, as illustrated in Figure~\ref{fig:overview}. This approach views dependency arcs as semantic units that can be interpreted in isolation. Each arc is therefore judged \emph{independently} based on whether the relation it implies is entailed by the source sentence. This is helpful in localizing generation errors and consequently providing more interpretable model decisions. Decomposing the factuality evaluation over components of structured representations can also be extended to other formalisms like AMR \cite{banarescu2013abstract}, UDS \cite{white2016universal}, and more. The chief advantage of dependency parsing over these is that pre-existing tools for dependency parsing report very high performance. Another line of work focuses on question answering-based semantic representations \cite{fitzgerald2018large,michael2018crowdsourcing} or generating freeform questions to capture factuality \cite{wang2020asking, durmus2020feqa}. However, these systems require a separate question generation step at \emph{inference} time, so generation is baked into their formalisms in a heavyweight way whereas we \emph{only} require dependencies. A final advantage of our approach is that dependency arcs can be produced in an online fashion during inference, and hence, factuality can be enforced incrementally. We evaluate our proposed dependency arc entailment approach in both summarization and paraphrase settings. In both settings, we show that we can automatically derive labels from actual generation data rather than rely on human annotation of dependency arc entailment, which is challenging to collect at scale. Nevertheless, our results show that our system's performance on factuality classification surpasses both sentence-level entailment and question generation and answering models. Our derived labels from actual generation data provide much better task-specific supervision compared to general entailment datasets. Finally, we demonstrate that predicted entailment scores for individual dependency arcs are meaningful and can be leveraged to understand and localize errors in system generations. \section{Dependency Arc Entailment (DAE)} \label{sec:DAE} \paragraph{Defining arc entailment} Our notion of entailment starts by assuming a rough correspondence between predicates and arguments in two sentences. In natural language inference (NLI) annotation efforts, this has taken the form of anchoring judgments in an underlying imagined scene \cite{bowman-etal-2015-snli}. We make a similar assumption, that events and actors in the source and target sentences are in correspondence unless there is direct evidence to the contrary. For instance, in Figure~\ref{fig:overview}, the \emph{military coup} in the target sentence and its corresponding \emph{amod(coup$\rightarrow$military)} arc should be evaluated with respect to the \emph{military takeover} in the source, giving coreference of the two the benefit of the doubt here With this assumption, we say that a dependency arc in the target sentence is entailed by the source if the \emph{semantic} relationship it implies between its head and child is entailed by the source sentence. There is precedent for such a syntax-semantics correspondence: certain formalisms like meaning-text theory \cite{Melcuk1988} have historically made this mapping more or less explicit. Consider the first hypothesis in Figure~\ref{fig:overview}. Many of the arcs here either contain information analogous to that in semantic roles, or they specify nominal modifiers capturing important entity properties.\footnote{We use enhanced dependencies in our experiments; modifiers with prepositions, augmented conjuncts provide a more useful semantic representation.} In our implementation, we exclude certain arc types which are not strongly tied to semantics, such as arcs involving punctuation; see the Appendix for details. Note that our method does not support commenting on arcs of the input that do not exist in the output; we discuss this later in Section~\ref{sec:limitations}. \begin{figure*}[t!] \centering \includegraphics[trim=110mm 156mm 50mm 57mm,scale=0.35,clip]{dae_model.pdf} \caption{Overview of our dependency arc entailment model. The input (premise) sentence and output (or prefix of the output) are encoded with a pre-trained model. The embeddings of the head and tail of an arc are selected, concatenated with an encoding of the dependency label, and fed to a classification layer to render the judgment.} \label{fig:model} \end{figure*} In some ways, our view of entailment is equivalent with the entailment of NLI settings \cite{bowman-etal-2015-snli,N18-1101}: if a hypothesis is entailed under the NLI definition, then all dependency arcs of the hypothesis must be entailed by our DAE definition. However, in our formulation, arc entailment is a 2-class classification task with labels $\in$ \emph{ \{entailed, non-entailed\}}. This means that arcs that would be \emph{neutral} or \emph{contradiction} in the generic entailment formulation are considered \emph{non-entailed} in our scenario \paragraph{Annotating arc entailment} To model this formulation, we require entailment annotations at the dependency arc level. However, there are several challenges associated with human annotation of arc entailment data. (1) Entailment is not truly a binary decision and is inherently subjective \cite{pavlick2019inherent}. (2) Entailment of an arc may be fundamentally unknowable or undefined if, for example, too much of the context has changed for such a judgment to make sense. (3) Annotators would need to understand the meaning of dependency labels and to be able to isolate the semantics of these individual arcs in sentences. \begin{table} \small \centering \begin{tabular}{p{0.95\linewidth}} \toprule P: Australian Prime Minister, John Howard, has made an unannounced visit to Iraq, according to the office of Iraqi transitional Prime Minister Ibrahim al-Jaafari. \\ H: Howard is a political representative of Australia. \\ \bottomrule \end{tabular} \caption{Example of premise (P) and hypothesis (H) with label \emph{entailment} from the dev set of entailment dataset RTE-2 \cite{bar2006second}.} \label{table:entail-ex} \end{table} Therefore, in this work, we take another approach, which is to \emph{automatically} label data from existing sources and outputs of generation models, which lets us collect large-scale data in a variety of domains. Specifically, we use paraphrase data to construct our dataset. Note however, that there is a fundamental difference between paraphrase pairs, which should be entailed in both directions, and past NLI data, which is forward-entailed by definition. For instance, the premise and hypothesis in Table~\ref{table:entail-ex} would classically be judged as entailed because \emph{political representative} is a hypernym of \emph{prime minister}, but the hypothesis is not a paraphrase of (even part of) the premise. As a result, our automatically-derived dataset captures a more restricted notion of entailment, primarily consisting of entailment relations that are symmetric in nature: arcs in the target sentence entailed by a source sentence also entail some part of the source. However, this is actually closer to what is acceptable for generation models to produce in tasks such as summarization, and the dataset collected in such a manner is useful for downstream tasks, as we show in Section~\ref{sec:filtering-bad-gen}. Moreover, because our training and evaluation data will typically come from closely related sentences, we can sidestep the cases where judgments in our formalism become most difficult to define. \section{Model} \label{sec:model} Let $x$ be the input context, $h$ be a hypothesis produced by a generation model $\mathcal{G}$, and $d(h)$ be the set of arcs in the dependency parse of $h$. We want to predict the entailment decision for each arc $a\in d(h)$ with respect to the input $x$, i.e. $\mathcal{F}_a(a,x)$. The overall model architecture of this dependency arc entailment model $\mathcal{F}_a$ is outlined in Figure~\ref{fig:model}. First, we concatenate the input and the hypothesis. We use a pre-trained encoder model $E$ to obtain contextual representations for each token in the concatenated sequence. From these token level representations, we derive a representation for each dependency arc $a \in d(h)$: \begin{equation*} \mathbf{r}_a = [E(x;h)_{a_h}; E(x;h)_{a_c}; E(a_d)] \end{equation*} as shown in the inset in the figure. Here, $a_h$, $a_c$ are the token indices corresponding to the head word and the child word of dependency arc $a$, and $a_d$ is their corresponding dependency label, which is also embedded with $E$ (non-contextually) Next, these arc representations are passed through a linear layer, followed by a softmax layer to obtain entailment label probabilities corresponding to each arc: $p(y \mid a;x) = \text{softmax}(W\mathbf{r}_a))$. This DAE network is trained using standard binary cross entropy loss and requires supervision on the arc entailment labels $y^* \in$ \emph{\{entailed, non-entailed\}} for the dependency arcs. Examples do not need to be fully labeled; training can use partial sets of annotations of arcs in $d(h)$. However, while using the DAE model in downstream tasks such as hypotheses reranking, entailment decisions for all arcs in the candidate hypothesis are required. \paragraph{Sentence-level factuality from dependency-level judgments} We want to evaluate the factual consistency of each hypothesis $h$ with respect to input $x$, i.e. $\mathcal{F}(h, x)$. This is computed by combining arc-level entailment scores over the dependency arcs set $d(h)$ of the generated hypothesis: \begin{equation*} \mathcal{F}(h, x) = \frac{1}{|d(h)|}\sum_{a \in d(h)}{\mathcal{F}_a(a, x)} \end{equation*} We use the sentence-level score $\mathcal{F}(h, x)$ to rerank the generated hypotheses in Section~\ref{sec:filtering-bad-gen}.\footnote{According to DAE definition, an output is non-factual if any of its arcs is non-entailed. However, min-pooling was very unstable, so we instead use mean-pooling in our experiments.} \section{Automatic Dataset Creation} \label{sec:data} We now describe our method for automatically collecting dependency-level DAE annotations from paraphrase or entailment corpora, avoiding manual annotation. In this creation process, we want data featuring a range of paraphrasing phenomenon, such as passivization, clausal reordering, synonym replacement, and more. Furthermore, we want a natural distribution of errors produced by generation models, such as wrong subject or objects for a verb or hallucination of new content. We represent a single example in our dataset as a tuple $\big(x, h, \big\{(a_i, y_i^*)\big\}_{a_i \in d(h)}\big)$ . Here, $x$ is the input, $h$ is the hypothesis, $a_i$ denotes a single dependency arc in the hypothesis, and $y_i$ refers to the gold entailment label for that arc. To construct data of this form, we assume access to a paraphrase dataset $D$, containing pairs $(x,h^*)$ of input sentences and their corresponding gold paraphrases.\footnote{The paraphrase corpora we use in this work may come from automatic methods like backtranslation; however, we still assume that these are reliable gold-standard paraphrases.} Additionally, we employ a paraphrase generation model $\mathcal{G}_p$, which can output $k$ candidate paraphrases $\{h_1, h_2, ... h_k\}$ given an input $x$. These noisy paraphrases will be used to derive realistic examples of generation errors to contrast with gold paraphrases, using the following techniques. \paragraph{Positive labels from gold paraphrases} Given a ground truth paraphrase, \textbf{we assume that every arc in the target side of the paraphrase $h^*$ is entailed by the source side $x$}. This is in line with our definition of arc entailment in Section~\ref{sec:DAE} and allows us to propagate sentence-level paraphrase judgements to arc-level entailment judgements. Because paraphrase datasets feature diverse linguistic phenomena, this approach leads to a range of positive examples. However, as described in Section~\ref{sec:DAE}, it is less likely to include arcs which are forward-entailed only (e.g., Table~\ref{table:entail-ex}). \paragraph{Auto-derived labels from model generations} To find negative examples for entailment, we leverage the output generations $\{h_1, h_2, ... h_k\}$ of an automatic paraphrase model $\mathcal{G}_p$. These generations will include unseen arcs, which may be positively or negatively entailed. Our key assumption here is that the outputs at the top of the beam are more likely to be factually correct, whereas outputs at the bottom of the beam are of lower quality and more prone to having factual inconsistencies. \textbf{We assume that \emph{new} arcs introduced in \emph{bad} model generations (i.e., bottom-most generations of the beam) are not entailed by the input.} We can then noisily label the generated paraphrases with a mix of positive (\emph{entailed}) and negative (\emph{non-entailed}) labels. We first construct a set of \emph{entailed} dependency arcs: this is a set containing all dependency arcs of the input and the gold paraphrase, i.e., $d(x) \cup d(h^*)$. Next, we annotate the dependency arcs of the bottom-most generations of the beam, say $\{h_{k}, h_{k-1}, h_{k-2}\}$, in the following way: \begin{equation*} y_i= \begin{cases} 1 & \text{if}\ a_i \in d(x) \cup d(h^*) \\ \text{not labeled} & \text{if}\ a_i \in d(h_1)\backslash d(x) \cup d(h^*) \\ 0 & \text{otherwise} \end{cases} \end{equation*} The middle case here leaves arcs that are in $h_1$ but not $x$ or $h^*$ as unannotated. Such arcs are possibly factual under the model, coming from a high-quality generated output, but we do not have enough confidence to assign them a label. During model training, such unannotated arcs are ignored. Finally, we also include the positive arcs from the 1-best hypothesis in our DAE data: $(x, h_1, \{a_i, 1 \})$ for arcs $a_i \in d(x) \cup d(h^*)$. This provides another source of hypothesis sentences with a slightly different distribution during model training. \section{Intrinsic Evaluation of DAE} Our experimental evaluation focuses on the following questions: (1) Does the automatic data collection result in a high quality training dataset? (2) Is the DAE model we train a good classifier? (3) Does DAE allow us to filter model generations and improve reliability of a generation system? We construct our DAE training dataset using the methodology defined in Section~\ref{sec:data}. For this, we leverage the paraphrase pair dataset \textsc{Paranmt-50m} \cite{wieting-gimpel-2018-paranmt} as the base dataset $D$. We use the transformer-based encoder-decoder model for paraphrase generation from \citet{Goyal-Durrett:2020:Syntaxparaphrase} as $\mathcal{G}_p$. We use the paraphrase model to generate $10$ outputs for 20k sentence pairs from $D$. We use the Stanford CoreNLP library \cite{manning-EtAl:2014:P14-5} to extract enhanced dependencies from the outputs sentences. Then, using the strategy outlined in Section~\ref{sec:data}, we generate 100k training samples (sentence pairs), 3k dev samples and 3k test samples. From this dataset, we derive 520k training, 14k dev, and 22k dependency level annotations, which we evaluate on in Section~\ref{sec:intrinsic}. The entailed to not-entailed ratio is roughly 70-30 in this dataset. \subsection{Dataset Quality} Before evaluating our modeling approach, we first evaluate whether the arc annotations in the training data follow the theoretical definition of DAE, outlined in Section \ref{sec:DAE}. Figure \ref{fig:dae-dev-ex} showcases examples from the dev set, corresponding to the same input example. We show positive \emph{entailed} arcs (in green), negative \emph{non-entailed} arcs (in red), and one unlabeled arc (in gray). Here, we can see that the gold paraphrase is important as it provides examples of valid synonym replacements, as well as other rephrasing of the input sentence. For negative examples, the examples from the bottom of the beam do indeed contain bad output and \emph{non-entailed} arcs. \begin{figure}[h] \centering \includegraphics[trim=15mm 160mm 173mm 20mm,scale=0.44,clip]{dae_dev_ex.pdf} \caption{Arc annotations from the automatic labelling strategy of Section \ref{sec:data}. Green (+) arcs are labelled \emph{entailed}, red (-) arcs are \emph{non-entailed}, and the gray arcs are unannotated.} \label{fig:dae-dev-ex} \end{figure} \paragraph{Agreement with human labels} Next, we want to evaluate the quality of the auto-derived dataset by measuring its agreement with human annotations. For this, we manually annotated the dependency arc entailment labels for 100 sentence pairs from the dev set (consisting of 20 gold paraphrases and 80 generated paraphrases), according to our theoretical definition. We compared these manual annotations (gold) with the auto-derived annotations for this set, and observed that the two annotations agreed 82\% of the time. This indicates that the automatic annotation strategy from Section \ref{sec:data} results in a high quality dataset. Further investigation into the disagreements between the manual and automatic labels revealed that false negatives included paraphrasing phenomena like synonym replacement, anaphora resolution during reordering, etc. We describe how to produce additional data to handle some of these cases later. On the other hand, false positives mainly consisted of exact arc matches in incorrect contexts. \subsection{Intrinsic Evaluation: DAE Classification} \label{sec:intrinsic} \begin{table}[h] \small \centering \begin{tabular}{r|cc} \toprule Model & Accuracy & F1 \\ \midrule Majority label & 72.7 & 84.2 \\ Lexical-match & 74.2 & 78.1 \\ \textsc{Bert} & 86.9 & 91.0 \\ \textsc{Electra} & \textbf{88.4} & \textbf{92.1}\\ \bottomrule \end{tabular} \caption{Dependency-level performance of the different models on our held-out DAE examples constructed from paraphrase data. Results show that transformer based models outperform the baseline models.} \label{table:intrinsic} \end{table} \noindent Next, we intrinsically evaluate the performance of the dependency arc entailment model, outlined in Section~\ref{sec:model}, on held-out data from our automatic labeling method. We test the performance of two pre-trained models: \textsc{Bert} (bert-base-uncased, 110M parameters) \cite{devlin2019bert} and \textsc{Electra} (electra-base-discriminator, 110M parameters) \cite{Clark2020ELECTRA}. We compare these models against a \textbf{majority label} baseline (\emph{entailment}) and an \textbf{lexical-match} baseline that predicts $y=\text{\emph{entailment}}$ if the arc (head, child and label) in the output constitute a dependency arc in the input as well, and \emph{non-entailed} otherwise. The performance of the different models is outlined in Table~\ref{table:intrinsic}. Our pre-trained transformer models perform substantially better than the baselines, with \textsc{Bert} achieving $86.9\%$ accuracy, and \textsc{Electra} with $88.4\%$. These models also outperform the lexical-match baseline, showing that the DAE models learn to do more than simple dependency arc matching. Henceforth, we use the best performing \textsc{Electra} model in all our experiments. \subsection{Other Data Generation Methods} Besides the data generation procedure we proposed, there are other ways to synthetically generate noisy annotations for premise-hypothesis pairs \cite{zhang2019paws}. We investigate these from two perspectives: first, does our data generation process cover these phenomena well, and second, can these additional sources of data prove useful? First, we explore a \textbf{word-swapping} technique similar to \citet{zhang2019paws}. Given a premise $x$, we form a hypothesis $x'$ by randomly swapping tokens that share a common part-of-speech tag to introduce errors. The intersection of the arcs in $d(x)$ and the modified sentence $d(x')$ are annotated as positive arcs ($y=\text{\emph{entailment}}$), whereas the newly created or changed arcs are annotated as negative ($y=\text{\emph{non-entailed}}$) Our \textbf{synonym data} is noisily constructed in the same manner as the gold paraphrases, but targets synonym replacements specifically. We extract pairs $(x, h^*)$ from $D$ that generally maintain similar sentence structure between the two sentences,\footnote{We follow prior work \cite{Goyal-Durrett:2020:Syntaxparaphrase} and calculate structure similarity by aligning words in the input and target using GloVe \cite{pennington2014glove} and computing the average displacement of each word.} but with small lexical changes like synonym replacement. We assign a positive \emph{entailment} label to all arcs: $\big(x, h^*, \{(a, 1)\ \; \forall a \in d(h^*)\}\big)$. To construct data with \textbf{hallucinations}, we modify an input sentence $x$, which we take as the \emph{hypothesis} by removing a randomly sampled span of contiguous tokens to derive a premise sentence $x'$. Then, the following DAE model annotations are derived: $\big(x', x, \{(a_i, 0)\; \forall \; a_i \in d(x) \backslash d(x')\}\big)$. Additionally, for each input sentence $x$, we extract another sentence $x'$ with the highest 1-gram overlap in the dataset. From this we derive, $\big(x, x', \{(a_i, 0)\; \forall \; a_i \in d(x')\}\big)$. \begin{table}[h] \small \centering \begin{tabular}{r|cccc} \toprule & \multicolumn{4}{c}{Test set}\\ Model Training Source & WS & AD & S & H \\ \midrule Word-swapping (WS) & 98.5 & 71.6 & 29.6 & 80.0 \\ Auto-derived (AD) & 90.2 & 88.4 & 82.9 & 74.8 \\ + synonyms (S) & 90.5 & 88.0 & 96.0 & 73.9 \\ + hallucinations (H) & 92.4 & 87.8 & 96.9 & 97.6 \\ \bottomrule \end{tabular} \caption{Comparison of different training data methodologies. Our method with augmentations (AD+S+H) performs well on all categories.} \label{table:data-ablations} \end{table} Table \ref{table:data-ablations} shows a comparison of word-swapping with our method (AD), and variants of our method augmented with synonyms and hallucinations. Note that the model trained on word swapped data performs well on a similarly constructed held-out set, but not on the test data for synonym data and auto-derived data. This indicates that artificially constructed data with rule based error introduction does not cover the space of generation possibilities. On the other hand, the model trained on our auto-derived dataset performs well across both artificial and actual generation data, thereby covering a larger range of entailment possibilities. Additional augmentation of synonym- and hallucination-specific data improves the performance further on the respective test sets while retaining the performance on generic entailment data. Henceforth, we use the (AD + S) model for our experiments. \section{Extrinsic Evaluation: Filtering Bad Generations} \label{sec:filtering-bad-gen} Moving beyond the dependency-level inference task, we now want to evaluate the \emph{sentence-level} performance of our model formulation. Namely, can it usefully reject erroneous generations produced by models for summarization (Section~\ref{sec:summarization-eval}) and paraphrasing (Section~\ref{sec:paraphrasing-eval})? \subsection{Summary Ranking} \label{sec:summarization-eval} We perform our evaluation on an abstractive summarization test dataset introduced in \citet{falke2019ranking} and used in other previous work. It contains $373$ test samples, each containing an input source sentence from CNN/DM and two summary sentences covering the same content generated using the model from \citet{chen2018fast}. One of these summary sentences is factually correct and the other is factually incorrect. The evaluation protocol measures how often the correct summary is scored higher than the incorrect summary for each candidate scoring technique. We compare against the following baselines: \begin{enumerate}[leftmargin=*] \item \textbf{NLI models}: Following \citet{falke2019ranking}, we use entailment predictions of NLI models to rerank candidates. We compare the performance of pretrained encoders (\textsc{Bert}, \textsc{RoBerta} and \textsc{Electra}) fine-tuned on the MNLI dataset \cite{N18-1101}.\footnote{We fine-tune the \textsc{Bert} and \textsc{Electra} models ourselves (details in the Appendix), improving on the results from \citet{falke2019ranking}. We use the fine-tuned \textsc{RoBERTa} model released by AllenNLP (\url{https://allennlp.org/}).} \item \textbf{Question Generation and Answering}: \citet{wang2020asking} propose an automatic evaluation metric QAGS that scores each summary by first generating questions pertaining to the summary content, and then comparing the answers to those questions in both the source sentence and the generated summary. \item \textbf{Rule-based}: We score each summary sentence as the fraction of dependency arcs in the output that are common with the input sentence. In case both the correct and the incorrect sentence get the same score, we break ties randomly. \end{enumerate} \begin{table}[t] \small \centering \begin{tabular}{r|c} \toprule Model & Reranking Acc. \\ \midrule \textsc{BERT} (MNLI) & 72.3 \\ \textsc{RoBERTa} (MNLI) & 78.3 \\ \textsc{Electra} (MNLI) & 82.0 \\ \midrule QAGS & 72.1 \\ \midrule Rule-based dependency & 74.8 \\ DAE (ours) & 83.6 \\ \midrule Human & 83.9 \\ \bottomrule \end{tabular} \caption{Performance of the different models at the summary reranking task. The human baseline is reported in \citet{falke2019ranking}. The proposed DAE model performs on par or better than prior works and comes close to human performance.} \label{table:summ-reranking} \end{table} Table \ref{table:summ-reranking} outlines the performance of the different models. The results show that the dependency arc entailment model outperforms the sentence-level NLI models and also the question generation and answering formulation (QAGS). Furthermore, the performance of our DAE model is close to the human performance reported in \citet{falke2019ranking}. Interestingly, the rule-based dependency model also outperforms certain NLI models and QAGS, indicating that these more complex models may fail to capture straightforward lexical relations. During our experimentation, we observed large variance in the performance of the NLI models at the reranking task with respect to their performance at the intrinsic entailment task. To illustrate this, in Figure~\ref{fig:variance-mnli-DAE}, we plot the summarization reranking performance of the two model against the intrinsic task performance at different stages of the training. For DAE, the intrinsic task performance is reported by the dependency-level entailment classification accuracy, and for the MNLI model, we report the classification accuracy on the sentence-level MNLI entailment task. The graph shows a high variance in the summary reranking performance, with stable increase in the MNLI intrinsic task performance at different time steps.\footnote{Note that the best performance of the MNLI model on summary reranking is better than the best performance of the DAE model; however, it did not coincide with the task-level best performance for our particular hyperparameter choice.} This indicates that the general entailment task solves a fundamentally different problem than factuality. By contrast, the DAE model performance on the summarization reranking task is more stable. \begin{figure}[t!] \centering \includegraphics[trim=48mm 153mm 120mm 50mm,scale=0.48,clip]{variance_graph.pdf} \caption{Performance of the \textsc{Electra}-based MNLI model and the DAE model. The figure shows a much higher variance in reranking accuracy for the MNLI model, suggesting that the task-specific performance is not correlated with reranking performance.} \label{fig:variance-mnli-DAE} \end{figure} \subsection{Paraphrase Ranking} \label{sec:paraphrasing-eval} Next, we evaluate the DAE model in the paraphrasing setting. To do this, first, we create a test set, similar to the summarization test set from \citet{falke2019ranking}. We use the transformer based seq2seq model \cite{Goyal-Durrett:2020:Syntaxparaphrase} to obtain $10$ candidate paraphrases for $100$ input sentences from the \textsc{ParaNMT-50m} dataset. We manually assign a label $y \in $ $\{$\emph{factual}, \emph{not factual}$\}$ to each input, candidate pair. Then for each input sentence, we randomly selected one correct and one incorrect paraphrase. This sentence triplet is used for our reranking experiments. \begin{table}[h] \small \centering \begin{tabular}{c|cc} \toprule Model & Reranking Acc \\ \midrule MNLI (\textsc{Electra}) & 79.0 \\ DAE (\textsc{Electra}) & 79.0 \\ \bottomrule \end{tabular} \caption{Performance on the paraphrase reranking task. The DAE performs on par with the NLI based model.} \label{table:para-rerank} \end{table} Table \ref{table:para-rerank} compares the performance of the MNLI-based model and the DAE models. Here, both are \textsc{Electra} based models; these are shown to be the best performing models in the previous sections. The results show that in this setting, the MNLI model and the DAE model perform similarly. Closer inspection of this data revealed that our model is biased towards predicting the label \emph{entailment} for arcs that are common with the input, possibly because we are evaluating the same generation model that was used to produce our arc entailment data, and our model is therefore biased towards predicting \emph{non-entailed} for arcs that are not present in the input. This poses a somewhat adversarial setting for our DAE model \section{Analysis} \begin{figure*}[h] \centering \includegraphics[trim=14mm 77mm 0mm 34mm,scale=0.46,clip]{example_summ_adv.pdf} \caption{Individual arc entailment probabilities for arcs in output sentences from the summarization test set \cite{falke2019ranking} and the paraphrase test set. The $+/-$ superscript signifies the gold label for that arc. Our DAE model is able to localize errors in the output. Compared to this, the MNLI model computes a high entailment score for all arcs that are lexically similar.} \label{fig:example-summ} \end{figure*} \subsection{Dependency- vs.~sentence-level modeling} Although our DAE model has shown strong performance, we have not yet performed a direct apples-to-apples comparison of DAE versus a sentence-level model \emph{when trained on the same sentences.} \paragraph{For MNLI} We construct DAE data from the sentence-level entailment data as follows. First, we extract 10k examples from the MNLI data which have the label \emph{entailment}. This is considered as the source data $D'$. We use a paraphrase model (transformer seq2seq \cite{Goyal-Durrett:2020:Syntaxparaphrase}) and the technique outlined in Section~\ref{sec:data} to extract auto-derived labels from $D'$. This gives us 42k training examples for training the DAE model. We compare this against an MNLI model trained on the original sentence-level entailment task with the same number of examples (42k). \paragraph{For \textsc{ParaNmt}} For this dataset, we do not have negative ($y = \text{\emph{contradiction}}$) annotations at the sentence-level. We derive these from our DAE training data as follows: we consider all pairs of sentences in the original dataset ($x,h^*$) as positive sentences ($y=1$), in addition to any pair of the form ($x,x$). We treat the three generated sentences at the bottom of the beam as negative sentences, meaning that the model is trained to distinguish gold paraphrases from model generations \begin{table}[h] \small \centering \begin{tabular}{c|cc|cc} \toprule Model & \multicolumn{2}{c}{ParaNMT} & \multicolumn{2}{|c}{MNLI}\\ \midrule & Summ & Para & Summ & Para \\ \midrule sent-level & 73.9 & 58.0 & 68.8 & 64.0\\ dep-level & 83.6 & 79.0 & 78.5 & 79.0\\ \bottomrule \end{tabular} \caption{Comparison of the sentence-level and dependency-level formulations. On similarly sized training datasets, the dependency-level formulation outperforms the sentence-level formulation for both types of data sources considered.} \label{table:sent-vs-dep} \end{table} Table~\ref{table:sent-vs-dep} outlines these results. For the paraphrase dataset, we see that the artificially constructed sentence-level dataset does not yield a good sentence-level discriminator. However, our dependency-level annotations \emph{can} form an effective training set. The results on MNLI show that our dependency-level formulation performs better than sentence-level when trained on the same amount of data and is therefore more closely related to the factuality task than past entailment formulations. \subsection{Qualitative Evaluation} \paragraph{Error Localization} Since the DAE formulation computes individual entailment scores for all arcs in the dependency tree structure, it is possible to localize errors in the generated summary or paraphrase. We present examples of input sentences, generated text, and arc entailment scores for a few examples in Figure~\ref{fig:example-summ}. For each input and output pair, we show the individual scores for the dependency arcs in the output sentence. Additionally, we report the MNLI score for the same example. The illustrative examples show that the DAE model is capable of localizing errors where erroneous subject-object pairs were constructed, even when these are the only errors. These errors are tougher for the MNLI model to catch, which evaluates the whole sentence and is prone to lexical overlap biases \cite{zhou2020towards}. In the third example, from our paraphrase setting, we see that the model is able to recognize synonym replacement as a valid re-writing. However, for the last example, the model cannot perform this same judgement for the \emph{variations $\rightarrow$ changes} replacement. Although, note that the model scores it higher than a erroneous replacement of the same word (\emph{variations $\rightarrow$ latter}). This shows that the DAE model is able to rank sentences that incorporate the similar type of re-writing/editing. However, we observed that the model has different error rates for different types of re-writing changes. For example, it is better at identifying text hallucination, or cases where the subject object relation between words change, but has comparatively lesser accuracy over changes such as synonym replacements. Therefore, it may not be ideal for settings where different re-writing types need to be compared. \paragraph{Limitations} \label{sec:limitations} We comment on a few limitations of our approach. First, arcs in our dependency-based formalism are not marked with negation or quantification; these must be handled via the contextualization of the hypothesis sentence rather than in the semantic representation. Second, our method cannot identify arcs that are missing from the input. For instance, consider the following premise: \emph{ In the morning, he goes jogging} and hypothesis: \emph{In the morning}. Here, the hypothesis does not contain critical information from the source sentence; however, since all the \emph{present} arcs are entailed by the source, our model would give this a high score. Furthermore, our model is trained on the \textsc{ParaNMT-50m} dataset, which itself is constructed through a noisy backtranslation process. Therefore, we rely on noisy \emph{gold} data for constructing our model. We believe that better quality paraphrase pairs would lead to a better quality model. \section{Related Work} Recent work in addressing faithfulness of text generations can be broadly divided into three groups: structured information based, multi-task formulations, and post-processing methods. The first group leverages structured knowledge, like Open IE triples \cite{cao2018faithful, goodrich2019assessing}, dependency trees \cite{song2018structure}, or generated semantic roles \cite{fan18irasl} as additional input for generation. However, incorporation of these as additional embeddings in model architectures does not explain \emph{how} these influence model generations. The second group leverages multi-task formulations and trains the generation model jointly with other factuality-related tasks, such as NLI entailment and question generation \cite{guo2018soft}. Other work additionally incorporates a reward for generating summaries entailed by the the input \cite{li2018ensure,pasunuru2018multi}. Our approach can be used to rank/filter outputs from any generation model in a black-box way, without additional augmentation or retraining. In post-processing approaches, recent work has explored NLI-based \cite{falke2019ranking, maynez2020faithfulness} post-generation filtering or ranking of output summaries. Our dependency-level models perform on par with these approaches, while additionally localizing the error in the generations. Other work \cite{durmus2020feqa, wang2020asking} has looked at using question generation and answering to reveal factual inconsistencies in generated text. However, more work is needed to figure out how to make these approaches reliable and broad coverage, as they primarily focus on specific factors like noun phrases and named entities. \section{Conclusion} In this work, we propose the dependency arc entailment formulation to identify factual errors in generated text in a more fine-grained manner. We show that the proposed formulation outperforms past approaches, while additionally providing an interpretable error analysis. \section*{Acknowledgments} Thanks to Katrin Erk for providing feedback on a draft of this work, as well to the anonymous reviewers for their helpful comments. This work was partially supported by NSF Grant IIS-1814522, a gift from Salesforce Inc, and an equipment grant from NVIDIA. The authors acknowledge the Texas Advanced Computing Center (TACC) at The University of Texas at Austin for providing HPC resources used to conduct this research.
{'timestamp': '2020-10-23T02:11:50', 'yymm': '2010', 'arxiv_id': '2010.05478', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05478'}
arxiv
\section{Introduction} According to the official statistics from World Health Organization (WHO) in 2020, there are around 466 million people with disabling hearing loss, which accounts for over $5\%$ of the world's population. Hearing loss leads to difficulty in hearing conversational speech. As a result, people with hearing loss often use sign language for communication. As a kind of visual language, sign language conveys semantic meanings by gestures and hand movements, together with facial expressions. During the long-term evolution, sign language develops its own characteristic rules and grammar. To facilitate such communication, many research efforts have been devoted to continuous sign language recognition (SLR), which aims to automatically identify the corresponding sign word sequence from a given sign video. It's a transdisciplinary research topic which involves computer vision, natural language processing, and multimedia analysis, \emph{etc}. Due to the expensive labeling cost, the continuous sign videos are generally weakly labeled, which means there is no alignment annotation of text sign words to video frames in the sign video. Early works \cite{starner1998real,zhang2016chinese} on continuous SLR rely on hand-crafted visual features and statistical sequential models, \emph{i.e.,} Hidden Markov Model (HMM). Recently, with the success of convolutional neural networks (CNNs) and recurrent neural networks (RNNs) in various computer vision tasks, more and more deep learning based sign language recognition algorithms have been proposed and achieved remarkable performance. Among them, most of the state-of-the-art continuous SLR approaches \cite{cui2019deep,pu2019iterative,camgoz2017subunets,zhou2020spatial} utilize connectionist temporal classification (CTC), which is a popular technique to deal with sequence-to-sequence transformation without accurate alignment. In CTC based methods, beam search algorithms are used for decoding, which iteratively produces word candidates. Basically, the decoding precision and speed depend on the beam width. The number of candidates for the decoded sequences is also equal to the beam width. In practice, we choose the candidate with maximum decoding probability as the final predicted sentence. However, due to the inconformity between CTC objective and evaluation metric, the candidate with maximum decoding probability may not be the best one under the evaluation metric, \emph{e.g.}, word error rate (WER). For example, in Figure~\ref{fig:intro}, although Candidate 5 has the minimum decoding probability among all candidates, it is actually the best one with the lowest WER. To quantitatively illustrate this issue, we study the Top-$K$ WER on RWTH-PHOENIX-Weather based on the state-of-the-art method proposed in \cite{cui2019deep}. Here, Top-$K$ WER is defined as follows: we choose the candidate with the lowest WER out of the $K$ decoded candidates and calculate the average WER over the whole dataset. That is to say, Top-$K$ WER is a lower bound over the decoding results. When the candidate with maximum decoding probability has the lowest WER for all testing samples, WER equals Top-$K$ WER. According to our experiments, the WER on RWTH-PHOENIX-Weather testing set is $23.8\%$, while Top-5 WER decreases to $19.7\%$. In order to bridge the performance gap, our target is to make the candidate with the best performance have the maximum decoding probability, which means to minimize the distance between such candidate and sign video. With the motivation discussed above, in this paper, we present a novel architecture for further boosting the performance of continuous SLR via cross modality augmentation. In continuous SLR, WER is the most important evaluation metric, which is defined as the least operations, \emph{i.e.,} substitution, deletion, and insertion, to transform the target sequence to the reference sequence. To simulate the calculation procedure of WER, we edit the sign video and corresponding text label following the same operations, as illustrated in Figure~\ref{fig:editing_overview}. With such editing, we augment the cross modality data and obtain a pseudo video-text pair. In order to minimize the cross modality distance from the video to ground truth label, while maximizing the distance from video to the pseudo text label, we propose a real-pseudo discriminative loss. Besides, the objective includes alignment-based CTC loss for both real and pseudo video-text pair. A cross modality semantic correspondence loss is also introduced to directly minimize the cross modality distance between real video and real ground truth text label. The proposed framework can be easily extended to other existing CTC based continuous SLR architectures. Extensive experiments on two continuous SLR benchmarks, \emph{i.e.,} RWTH-PHOENIX-Weather and CSL, demonstrate the effectiveness of our proposed method. \begin{figure}[ht] \centering \begin{subfigure}[b]{\linewidth} \includegraphics[width=1.0\textwidth]{figure/edit_sub.pdf} \caption{Illustration of the ``Substitution'' operation.} \label{subfig:edit_sub} \end{subfigure} % \begin{subfigure}[b]{\linewidth} \includegraphics[width=1.0\textwidth]{figure/edit_del.pdf} \caption{Illustration of the ``Deletion'' operation.} \label{subfig:edit_del} \end{subfigure} \begin{subfigure}[b]{\linewidth} \includegraphics[width=1.0\textwidth]{figure/edit_ins.pdf} \caption{Illustration of the ``Insertion'' operation.} \label{subfig:edit_ins} \end{subfigure} \caption{Illustration of different kinds of editing operations.} \label{fig:editing_overview} \Description{} \vspace{-0.15cm} \end{figure} \begin{figure*}[ht!] \begin{center} \includegraphics[width=0.97\linewidth]{figure/Framework.pdf} \end{center} \caption{Overview of our proposed framework. The framework consists of a common CNN-TCN visual encoder, sequential model and text encoder. With the cross modality augmentation, we design multiple loss terms to optimize the architecture.} \label{fig:overview_architecture} \Description{} \vspace{-0.02cm} \end{figure*} \vspace{-2px} \section{Related Work} In this work, we briefly review the key modules and techniques in continuous sign language recognition. Continuous SLR targets at translating the input video into a sequence of glosses in a consistent order. First, the visual encoder transforms the input video into a high-dimensional feature representation. Then the sequential module tries to learn the mapping from this feature representation to the corresponding text sequence. To further refine the recognition result, iterative refinement strategy has been explored with promising results. Besides discussing the above content, we also introduce existing data augmentation techniques in deep learning. \textbf{Video representation learning.} Discriminative feature representation is crucial for sign language recognition. Early works concentrate on the hand-crafted features, such as HOG or HOG-3D~\cite{buehler2009learning, koller2015continuous}, motion trajectories~\cite{koller2015continuous, pfister2013large, evangelidis2014continuous} and SIFT~\cite{pfister2013large}. These features are utilized for describing hand shapes, orientations or motion status. With the advance of convolutional neural networks~(CNNs), many networks are designed for video representation learning. They are based on 2D CNNs~\cite{wang2016temporal, he2016deep, simonyan2014two}, 3D-CNNs~\cite{tran2015learning, qiu2017learning, carreira2017quo, qiu2019learning} or a mixture of them~\cite{jiang2019sparse, zolfaghari2018eco, xie2018rethinking}. For the task of continuous SLR, various CNNs have been investigated. Oscar~\emph{et al.}~\cite{koller2017re} utilize GoogLeNet~\cite{szegedy2015going} as the visual encoder in an end-to-end iterative learning framework. Pu~\emph{et al.} \cite{pu2018dilated} and Zhou~\emph{et al.} \cite{zhou2019dynamic} use 3D ResNet~\cite{qiu2017learning} and I3D~\cite{carreira2017quo} as the feature extractor to jointly model the spatial and temporal information, respectively. There also exist methods~\cite{cui2017recurrent,cui2019deep} using 1D temporal CNNs after 2D CNNs to encode temporal dependency. As one of them, DNF~\cite{cui2019deep} is becomes the most challenging competitor. \textbf{Sequential learning.} In continuous SLR, there are several popular sequential models, \emph{e.g.} hidden Markov model (HMM), recurrent neural network~(RNN) with connectionist temporal classification~(CTC) and encoder-decoder network, \emph{etc}. HMM~\cite{wu2016deep, koller2017re, koller2018deep,koller2019weakly} is one of the most widely used sequential models. Oscar \emph{et al.}~\cite{koller2019weakly} embed CNN-LSTM models in each HMM stream following the hybrid approach exploiting the state transitions and the sequential parallelism for sign language recognition. The Recurrent Neural Networks (RNNs), \emph{e.g.} Long Short-Term Memory (LSTM)~\cite{hochreiter1997long}, Gated Recurrent Unit (GRU)~\cite{cho2014learning}, have been successfully applied to sequential problems, including speech recognition~\cite{graves2014towards}, video captioning~\cite{zhu2019attention, shi2019watch, yang2019structured}, machine translation~\cite{cho2014learning, sutskever2014sequence}, \emph{etc.} In continuous SLR, bidirectional LSTM-CTC architecture~\cite{camgoz2017subunets,cui2017recurrent,pu2019iterative, cui2019deep} is employed as a basic model and becomes the most popular one. Besides, there exist some works~\cite{huang2018video,guo2018hierarchical} adopting an attention-aware encoder-decoder network to learn the mapping between visual features and sign glosses. Camgoz \emph{et al.}~\cite{cihan2018neural} also utilize the encoder-decoder architecture to extend sign language recognition to sign language translation. \textbf{Iterative refinement.} Given that the ground truth only provides sentence-level annotations without specific temporal boundaries for each gloss, continuous sign language can be treated as a weakly supervised problem. Current frameworks usually contain a large number of layers and encounter the vanishing gradient problem for low layers, resulting in not fully optimized visual encoder. Recent works demonstrate the importance of the alignments between video clips and sign glosses. The video segment and sign gloss pairs can be treated as the trimmed video classification problem to enhance the visual encoder. In this way, the whole architecture can be optimized in an iterative way for performance boosting. Cui \emph{et al.}~\cite{cui2019deep} and Zhou \emph{et al.} ~\cite{zhou2019dynamic} generate the pseudo glosses for video segments by aligning the output probability matrix and output glosses sequence through dynamic programming with notable performance gain. Pu \emph{et al.} \cite{pu2019iterative} utilize utilize the soft Dynamic Time Warping (soft-DTW) as the alignment constraint with the warping path indicating the possible alignments between input video clips and sign words. \textbf{Data augmentation in deep learning.} Data augmentation is a powerful method to reduce overfitting, which can help the neural network to extract more information from the original dataset. Data augmentation encompasses a series of techniques enhance the quality and size of the training data. It has been successfully applied in various deep learning based approaches. There are many different data augmentation techniques in different tasks. For image-based tasks, \emph{i.e.,} image classification, object detection, \emph{etc}, the image augmentation skills include geometric transformations (\emph{e.g.} rotation, flipping \emph{etc.}), color space transformation (\emph{e.g.} RGB to HSV), kernel filters, random erasing, \emph{etc.} For video-based tasks, \emph{i.e.,} action recognition, tracking, in addition to the image augmentation techniques, video augmentation is performed in temporal dimension by temporal random sampling. In natural language processing tasks, \emph{e.g.} text classification, the operations to augment sentences include synonym replacement, random insertion, random swap, random deletion, \emph{etc.} In existing techniques, the augmented sample share the same label with the original data, and the optimization loss keeps unchanged. In contrast, in our approach, the augmented video or gloss sentence no longer share the same semantic meaning with the original one. We take advantage of the fact and optimize the DNN model with novel triplet losses. \section{Our Approach} In this section, we first give an overview of our framework. After that, we separately discuss the generation of pseudo video-text pairs, network architecture and loss design. \subsection{Overview} Our whole framework is illustrated in Figure~\ref{fig:overview_architecture}. During training, given an input video and its corresponding text, we first perform the editing process to create the pseudo text. At the same time, according to the same editing operations, we constitute the pseudo video based on the clip alignment, which is obtained from the refinement stage following~\cite{cui2019deep}. Then we feed the real and pseudo video into the same recognition framework with shared parameters and calculate the CTC loss, respectively. Further, we explore the relationship between real and pseudo video-text pairs by designing multiple losses to make the network aware of the editing operations and constrain the correspondence of cross-modal data. The final optimization loss is a summation of the CTC loss, real-peseudo discriminative loss and cross modality semantic loss. During the inference stage, the input video is fed into the backbone, \emph{i.e.,} the visual encoder, sequential model and CTC decoding model to output the final prediction text sequence. \subsection{Pseudo Data Generation} Following the definition of word error rate (WER), one of the most widely used evaluation metrics in continuous SLR, we generate pseudo video-text pair by editing raw video and label. WER corresponds to the least operations of substitution, deletion and insertion to transform the target sequence into the reference sequence. In order to simulate the calculation procedure of WER, the videos and labels are edited following these three operations, \emph{i.e.,}, substitution, deletion, and insertion. Given a real video-text pair, we first substitute, insert or delete a word in the real text and repeat this operation a few times. The inserted or substituted new word is randomly picked from the vocabulary in the training set. On the other hand, we perform the same editing operations on the real video according to the alignment extracted in the refinement stage. For a text label and its corresponding sign video, we perform $k$ editing operations, each of which is randomly taken from substitution, deletion, and insertion The editing times $k$ is randomly sample from the range [1, $K$], where $K$ denotes the maximum editing operations. In this way, we obtain a pseudo video-text pair. Figure~\ref{fig:editing_overview} illustrates three different editing operations. Take ``Substitution'' as an example, as shown in Figure~\ref{subfig:edit_sub}, given a sign video with the label ``Tomorrow Morning Rainy'', we randomly replace a sign gloss. In this case, sign gloss ``Tomorrow'' is replaced with ``Saturday''. Thus, a new pseudo label sequence is generated with such editing operation. After that, all frames corresponding to the sign word ``Tomorrow'' are also replaced by the frame segment with the meaning of ``Saturday'' from other videos. Similarly, we can edit the video-text pair with another two operations, \emph{i.e.,}, insertion and deletion. ``Insertion'' indicates we randomly pick up a text word from the vocabulary and insert it into the original label sequence, while ``deletion'' means a sign word is randomly deleted from the label sequence. \subsection{Network Architecture} \textbf{Visual encoder.} Visual encoder aims at encoding the input video into semantic feature representation. It consists of a spatial encoder $E_{vs}$ followed by a temporal encoder $E_{vt}$ for spatial-temporal representation. In our implementation, we use the same spatial-temporal backbone proposed in \cite{cui2019deep} considering its excellent performance. GoogLeNet~\cite{szegedy2015going} is selected as our spatial encoder. Temporal encoder contains the architecture of \emph{conv1d-maxpool-conv1d-maxpool}. Specifically, the kernel sizes of 1D temporal convolutional layers and max pooling layers are set as 5 and 2, respectively. The strides for all the layers in $V_t$ are set as 1. Following these settings, the time length is reduced to a quarter of the original video with the receptive field as 16. Given a sign video $\mathbf{V} = \{v_t\}_{t=1}^T$ with $T$ frames, the output, \emph{i.e.,} semantic feature representation, is defined as follows, \begin{equation}\label{equ:cnn_tcn} \mathbf{\mathbf{F}} = E_{vt}(E_{vs}(\mathbf{V})), \end{equation} where $\mathbf{V} \in {{\mathbb{R}}^{C_1 \times T\times H\times W}}$ and $\mathbf{F} \in {{\mathbb{R}}^{C_2 \times T/4}}$. \textbf{Sequential model.} The sequential model captures temporal dependency among the semantic feature representations generated by visual encoder, and learn the mapping between visual features and sign glosses. We select Bidirectional Long Short-Term Memory~(BLSTM) $S_{bi}$, which captures the temporal dependency in both forward and backward time steps. It takes the feature sequence as input and generates hidden states $\mathbf{F}_v$ as follows, \begin{equation} \label{equ:blstm} \mathbf{F}_v = S_{bi}(\mathbf{F}), \end{equation} where $\mathbf{F}_v \in {{\mathbb{R}}^{C_3 \times T/4}}$ and $C_3$ indicates the units of the hidden states. After that, the hidden states $\mathbf{H}$ is utilized as the input of a fully-connected layer $f_c$ and a softmax layer $f$ to generate the probability matrix for all the time steps as follows, \begin{equation} \label{equ:fc} \mathbf{\mathbf{P}} = f(f_c(\mathbf{F}_v)), \end{equation} where $\mathbf{P} \in {{\mathbb{R}}^{N \times T/4}}$ and $N$ indicates the number of glosses. \textbf{Text Encoder.} For the semantic correspondence between the visual feature and gloss sequence, we utilize the text label encoder $E_T$ to map the gloss sequence $\bm s$ into the same latent space as the visual features as follows, \begin{equation} \label{equ:text encoder} \mathbf{F}_l = E_t(\bm{s}), \end{equation} where $\mathbf{F}_l \in {{\mathbb{R}}^{C_3 \times T/4}}$ and a two-layer BLSTM is also utilized as the text encoder. \subsection{Objective Function} To optimize the network, we use three different kinds of loss functions, \emph{i.e.,}, alignment loss, real-pseudo discriminative loss, and cross modality semantic correspondence loss. For each stream, in order to learn the alignment between video and text sequence, connectionist temporal classification (CTC) is introduced. CTC is proposed to deal with two unsegmented sequences without accurate alignment. CTC introduces a blank label out of the vocabulary to account for transitions and silence without precise meaning. There may exist several alignment paths $\pi$ between the input sequence and target sequence. The probability of each path $\pi$ is written as follows, \begin{equation}\label{equ:ctc_path} p(\pi|\mathbf{V})=\prod_{t=1}^{T} p(\pi_t|\mathbf{V}), \end{equation} where $\pi_t$ is the label at time step $t$, $T$ is the number of frames in video. A many-to-one mapping $\mathcal{B}$ is defined to remove reduplicated words and blank labels. The conditional probability of the target sequence $\bm{s}$ is calculated as the summation of the probabilities of all alignment paths, which is formulated as follows, \begin{equation}\label{equ:ctc_prob} p(\bm{s}|\bm{V}) = \sum_{\pi\in \mathcal{B}^{-1}(\bm{s})} p(\pi|\bm{V}), \end{equation} where $\mathcal{B}^{-1}$ is the inverse mapping of $\mathcal{B}$. The final CTC objective function is defined as the negative log probability of $p(\bm{s}|\bm{V})$, written as follows, \begin{equation}\label{equ:ctc_loss} \mathcal{L}_{\mathrm{CTC}} = -\ln p(\bm{s}|\bm{V}). \end{equation} Denote the real video and pseudo video as $\mathbf{V}_r$ and $\mathbf{V}_p$, respectively. For the two basic streams with real video and pseudo video, we define two CTC loss as alignment loss $\mathcal{L}_A$, written as follows \begin{equation}\label{equ:loss_align} \mathcal{L}_A = \mathcal{L}_{\mathrm{CTC}}^r + \mathcal{L}_{\mathrm{CTC}}^p, \end{equation} where $\mathcal{L}_{\mathrm{CTC}}^r$ and $\mathcal{L}_{\mathrm{CTC}}^p$ are the CTC loss for real video and pseudo video, respectively. The alignment loss targets at maximizing the total probabilities of all alignment paths between the sign video and the label sequence. In our method, the video data and text label are mapped into the same latent space, which makes it possible for distance measurement. For the input data modalities, \emph{i.e.,}, real video, real label, pseudo video, pseudo label, the corresponding feature representations are denoted as $\bm{f}_v^r$, $\bm{f}_l^r$, $\bm{f}_v^p$, $\bm{f}_l^p$ from Equation~\eqref{equ:blstm} and Equation~\eqref{equ:text encoder}, respectively. We divide the features into two groups, which are $(\bm{f}_v^r, \bm{f}_l^r, \bm{f}_l^p)$ and $(\bm{f}_l^r, \bm{f}_v^r, \bm{f}_v^p)$, respectively. For $(\bm{f}_v^r, \bm{f}_l^r, \bm{f}_l^p)$, the distance of the feature representations between real video and real label is supposed to be closer than that between real video and pseudo label. That is to say, in such triplet, the feature representation of real video is regarded as the anchor, with the real and pseudo label as a positive and negative sample, respectively. We use triplet loss as the objective function to minimize the distance from the anchor to the positive sample, and maximize the distance from the anchor to the negative sample. The real video anchor based real-pseudo discriminative loss is defined as follows, \begin{equation}\label{equ:loss_dv} \mathcal{L}_{D_v} = \mathcal{L}_{trip}(\bm{f}_v^r, \bm{f}_l^r, \bm{f}_l^p) = \max \left (\mathcal{D}(\bm{f}_v^r, \bm{f}_l^r) - \mathcal{D}(\bm{f}_v^r, \bm{f}_l^p)+\alpha, 0 \right), \end{equation} where $\mathcal{L}_{trip}(\cdot)$ means triplet loss~\cite{hoffer2015deep}, $\mathcal{D}$ is the distance function, $\alpha$ is a margin. For another group, with the same purpose, the real text anchor based real-pseudo discriminative loss is defined as follows, \begin{equation}\label{equ:loss_dl} \mathcal{L}_{D_l} = \mathcal{L}_{trip}(\bm{f}_l^r, \bm{f}_v^r, \bm{f}_v^p) = \max \left (\mathcal{D}(\bm{f}_l^r, \bm{f}_v^r) - \mathcal{D}(\bm{f}_l^r, \bm{f}_v^p) +\alpha, 0 \right). \end{equation} The final real-pseudo discriminative loss $\mathcal{L}_{D}$ is the summation of these two parts, written as follows, \begin{equation}\label{equ:loss_d} \mathcal{L}_{D} = \mathcal{L}_{D_v} + \mathcal{L}_{D_l}. \end{equation} The real-pseudo discriminative loss focuses on the relative distance between the video and text label data. For real video-text pair, the distance between the features of such pair in latent space is expected to get as close as possible. Hence, we directly minimize the distance of the real video-text pair, called cross modality semantic correspondence loss. The loss function is defined as the distance metric, \begin{equation}\label{equ:loss_s} \mathcal{L}_{S} = \mathcal{D}(\bm{f}_v^r, \bm{f}_l^r), \end{equation} where $\mathcal{D}$ is the distance metric function. Considering the lengths of video and text are variable, to calculate the distance between two variable length sequences, the distance metric function between $\bm{f}_v^r$ and $\bm{f}_l^r$ is defined as the dynamic time warping (DTW) discrepancy. Denoting the cost between $\bm{f}_v^r$ and $\bm{f}_l^r$ at different time steps $t_1$ and $t_2$ as $d(t_1,t_2)$, DTW typically uses dynamic programming to efficiently find the best alignment that minimizes the overall cost. Define the DTW distance for subsequences $\bm{f}_v^r(1:i)=(\bm{f}_v^r(1), \bm{f}_v^r(2), \cdots, \bm{f}_v^r(i))$ and $\bm{f}_l^r(1:j)=(\bm{f}_l^r(1), \bm{f}_l^r(2), \cdots, \bm{f}_l^r(j))$ as $D_{i,j}$, which can be written as \begin{equation}\label{equ:dtw_pice} D_{i,j}=d(i,j) + \min (D_{i-1,j}, D_{i,j-1}, D_{i-1,j-1}). \end{equation} In our experiments, $d$ is calculated as the cosine distance, written as follows, \begin{equation}\label{equ:dtw_d_cosine} d(i,j)=1 - \frac{\bm{f}_v^r(i) \cdot \bm{f}_l^r(j)} {||\bm{f}_v^r(i)|| \cdot ||\bm{f}_l^r(j)||}. \end{equation} To make DTW distance differentiable, a continuous relaxation of the minimum operator \cite{cuturi2017soft,chang2019d3tw} is introduced with a smoothing parameter $\gamma \geq 0$ \begin{equation} \min\nolimits^{\gamma}{(a_1, \cdots, a_n)} := \left\{ \begin{aligned} &\min_{i} a_i &\gamma=0. \\ &-\gamma\log \sum_{i} e^{-a_i/\gamma} &\gamma \geq 0. \end{aligned} \right. \end{equation} With the formulation of DTW, $\mathcal{D}(\bm{f}_v^r, \bm{f}_l^r)$ is calculated as follows, \begin{equation} \mathcal{D}(\bm{f}_v^r, \bm{f}_l^r) = D_{T,N}, \end{equation} where $T$ is the length of $\bm{f}_v^r$ and $N$ is the length of $\bm{f}_l^r$. The distance in triplet loss used in Equation~\eqref{equ:loss_dv} and Equation~\eqref{equ:loss_dl} is also calculated by DTW since the lengths of the items in triplet are variable. The final objective loss function is defined as follows, \begin{equation}\label{equ:loss_all} \mathcal{L} = \lambda \mathcal{L}_A + (1-\lambda) (\mathcal{L}_D + \mathcal{L}_S), \end{equation} where $\lambda$ is a hyper-parameter, which indicates the weighted summation of these loss terms. Since $\mathcal{L}_D$ and $\mathcal{L}_S$ have the same distance metrics, we combine them and perform weighted sum with $\mathcal{L}_A$. \begin{table*}[ht] \begin{center} \caption{Statistical data on RWTH-PHOENIX-Weather multi-signer, signer-independent and CSL datasets.} \label{tab:stat} \tabcolsep=6pt \begin{tabular}{l|ccc|ccc|cc} \hline \multirow{3}{*}{Statistics} & \multicolumn{3}{c|}{RWTH-PHOENIX-Weather} & \multicolumn{3}{c|}{RWTH-PHOENIX-Weather} & \multicolumn{2}{c}{CSL} \\ & \multicolumn{3}{c|}{Multi-Signer} & \multicolumn{3}{c|}{Signer-Independent} & \\ & Train & Dev & Test & Train & Dev & Test & Train & Test \\ \hline\hline \#signers & 9 & 9 & 9 & 8 & 1 & 1 & 50 & 50 \\ \#frames & 799,006 & 75,186 & 89,472 & 612,027 & 16,460 & 26,891 & 963,228 & 66,529 \\ \#duration~(h) & 8.88 & 0.84 & 0.99 & 6.80 & 0.18 & 0.30 & 10.70 & 0.74 \\ \#vocabulary & 1,231 & 460 & 496 & 1,081 & 239 & 294 & 178 & 20 \\ \#videos & 5,672 & 540 & 629 & 4,376 & 111 & 180 & 4,700 & 300 \\ \hline \end{tabular} \end{center} \end{table*} \section{Experiments} In this section, we conduct comprehensive experiments to validate the effectiveness of our method. We first review our benchmark datasets and evaluation metrics. Then we perform ablation studies on each part of our proposed framework. Finally, we compare our method with state-of-the-art approaches on two benchmark datasets. \subsection{Dataset and Evaluation} We perform our experiments on two benchmark datasets, \emph{i.e.,} RWTH-PHOENIX-Weather multi-signer~\cite{koller2015continuous}, RWTH-PHOENIX-Weather signer-independent~\cite{koller2017re} and CSL~\cite{huang2018video} dataset. RWTH-PHO ENIX-WEATHER multi-signer dataset, focusing on the German sign language, is one of the most popular benchmark datasets in continuous SLR. This dataset is recorded from a public television broadcast from a monocular RGB camera at 25 frames per second~(fps), with a resolution of $210\times260$. It contains a total of 6,841 sentences with a total vocabulary size of 1,295 sign words performed by 9 different signers. Besides the training set, two independent sets are proposed for evaluation, \emph{i.e.,} dev and test set. Each set accounts for about 10\% of the size of the training set. All 9 signers appear in these 3 sets. Additionally, there is another signer-independent setting, where it chooses 8 signers for training and leaves out signer \#5 for evaluation. CSL~\cite{huang2018video} is a continuous Chinese sign language dataset containing 5,000 videos performed by 50 signers. It contains a total of 100 different sentences with a vocabulary size of 100 sign words in daily life. This dataset is divided into the training and test set, containing 4,700 and 300 videos, respectively. The detailed statistics are listed in Table~\ref{tab:stat}. We utilize multiple evaluation metrics for continuous SLR. Word error rate~(WER) is one of the commonly used metrics. It is actually an edit distance, indicating the minimum number of operations, \emph{i.e.,} substitution, deletion and insertion, required to convert the predicted sentence to the reference one: \begin{equation}\label{equ:wer} WER = \frac{n_i + n_d + n_s}{L}, \end{equation} where $n_i$, $n_d$, and $n_s$ are the number of operations for insertion, deletion, and substitution, respectively. We also calculate the ratio of correct words to the reference words, denoted as Acc-w. Besides, we adopt some semantic metrics in Neural Language Processing~(NLP) and Neural Machine Translation~(NMT), including BLEU, METEOR, CIDEr and ROUGE-L. \subsection{Implementation Details} In our experiment, we optimize our framework in a staged strategy following the previous methods~\cite{pu2019iterative, cui2019deep}. First, the backbone GoogLeNet adopts the parameters pre-trained on ILSVRC-2014~\cite{russakovsky2015imagenet} dataset. For the end-to-end training stage, the whole framework is supervised by the loss in Equation~\eqref{equ:loss_all}. In the sequential model and text encoder, BLSTMs both have two layers with the hidden states set to 1024. Adam optimizer is utilized with the learning rate as 5e-3 and batch size as 3. The network is trained for 50 epochs till convergence. In continuous SLR, it is crucial for the visual encoder to produce robust feature representation. The loss terms utilized for the first stage have limited contribution to the low layers of the visual encoder due to the vanishing gradient, which makes the visual encoder not fully optimized. Therefore, we use the CTC decoding method to generate pseudo labels for video clips. After that, in the second stage, we utilize these clip-label pairs for classification. Specifically, we add a fully-connected layer on top of the visual encoder and use the cross-entropy loss to supervise its learning. It is optimized by stochastic gradient descent~(SGD) with totally 40 epochs. The initial learning rate is set as 5e-3 and with 10x reduction when loss saturates. The input clip length is 16. We set the batch size as 32 and weight decay as 1e-4, respectively. Embedded with the optimized visual encoder at this stage, we then train the whole framework using the loss in Equation~\eqref{equ:loss_all} again. Through such optimization strategy, our visual encoder cooperates with the sequential model for better performance. Our whole framework is implemented on PyTorch and experiments are performed on NVIDIA Tesla V100. Besides, data augmentation is crucial for relieving over-fitting. During training, the video is randomly cropped at the same spatial location along the time dimension, with the resolution of $224\times224$. Then it is randomly flipped horizontally. Temporally, we randomly discard 20\% frames individually. During testing, the video is center cropped at the same spatial location with the resolution of $224\times224$. All the frames in the video are fed into the framework. \subsection{Ablation Study} We perform ablation studies on the effectiveness of different parts in our framework. \textbf{Hyper parameter $\lambda$.} We study the impact of $\lambda$ in Equation~\eqref{equ:loss_all} and the result is shown in Figure~\ref{fig:ratio}. The experiments are conducted on RWTH-PHOENIX-Weather multi-signer independent dataset and we utilize the WER result on the dev set as our choosing criterion. It can be seen that the WER result gets improved with a gradual and flexuous process and achieves the best when $\lambda=0.9$. Notice that $\lambda=1$ corresponds to baseline which optimized with only CTC loss. When $\lambda=0$, the network does not converge, so there is no result shown in Figure~\ref{fig:ratio}. Unless stated, we utilize it as our default hyper parameters in the following experiments. \begin{figure}[ht] \begin{center} \includegraphics[width=1\linewidth]{figure/Ratio-c.pdf} \end{center} \caption{Effects of different hyper parameter $\lambda$ in Equation~\eqref{equ:loss_all} on the RWTH-PHOENIX-Weather multi-signer dataset.} \label{fig:ratio} \Description{} \vspace{-2pt} \end{figure} \begin{figure*} \centering \includegraphics[width=1.0\textwidth]{figure/Sample_cr.pdf} \caption{An example on the the dev set of RWTH-PHOENIX-Weather multi-signer dataset. In the figure, the first row represents the input frame sequences. The medium part indicates the sign word with maximum probability at each time step. The bottom part shows the final predicted sentence. Red symbols denotes the wrongly predicted words. ``D'', ``S'', and ``I'' stand for deletion, substitution, and insertion, respectively.} \label{fig:sample-rwth} \Description{} \end{figure*} \textbf{Effectiveness on the pseudo video-text pairs.} We compare the effectiveness of our pseudo video and text respectively on the RWTH-PHOENIX-Weather multi-signer dataset in Table~\ref{tab:pesu_vtp}. ``Video only'' denotes that we only generate pseudo video after editing and supervise the whole framework by the loss terms except the pseudo text related ones. It can be observed that the WER result is improved by 1.8\% and 1.9\% over the baseline on the dev and test set, respectively. ``Text only'' denotes that we only generate pseudo text after editing. The improvement on the WER result is similar to the former, with 1.9\% and 2.0\% on the dev and test set, respectively. When the pseudo video-text pair is generated after editing, the performance is further improved to 21.3\% and 21.9\% on the dev and test set, respectively. It can be concluded that the generated video and text are both beneficial for the performance boost. To qualitatively show its effectiveness, we further visualize an example as shown in Figure~\ref{fig:sample-rwth}. It can be seen the hypothesis sentence of the baseline method shows deletion, substitution and insertion compared with the ground truth sentence. With only pseudo video or text inserted into our framework, the WER result gets improved to some extent, \emph{e.g.} ``Video-only'' method corrects the failure insertion of word ``REGEN-PLUSPLUS''. When using both pseudo video and text, the WER result is further improved by a large margin on this sentence, which also shows the complementary effect of the pseudo video-text pair. \begin{table} \begin{center} \caption{An ablation study on the effectiveness of the pseudo video-text pair on the RWTH-PHOENIX-Weather multi-signer dataset (the lower the better).} \label{tab:pesu_vtp} \tabcolsep=8pt \begin{tabular}{c|rc|rc} \hline \multirow{2}{*}{Methods} & \multicolumn{2}{c|}{Dev} & \multicolumn{2}{c}{Test} \\ & del / ins & WER & del / ins & WER \\ \hline\hline Baseline & 7.8 / 3.5 & 23.8 & 7.8 / 3.4 & 24.4 \\ Video only & 7.7 / 3.0 & 22.0 & 7.0 / 2.8 & 22.5 \\ Text only & 8.1 / 2.8 & 21.9 & 7.8 / 2.4 & 22.4 \\ Ours & 7.3 / 2.7 & \textbf{21.3} & 7.3 / 2.4 & \textbf{21.9} \\ \hline \end{tabular} \end{center} \vspace{-0.3cm} \end{table} \begin{table} \begin{center} \caption{Effects of the maximum editing operations on the RWTH-PHOENIX-Weather signer-independent dataset (the lower the better).} \label{tab:max-num} \tabcolsep=8pt \begin{tabular}{c|cccccc} \hline $K$ & 1 & 2 & 3 & 4 & 5 & 6 \\ \hline \hline del & 7.7 & 7.1 & 7.3 & 8.0 & 8.0 & 7.9 \\ ins & 2.9 & 3.1 & 2.7 & 2.6 & 2.6 & 2.7 \\ WER & 21.9 & 21.7 & 21.3 & 21.8 & 21.8 & 21.7 \\ \hline \end{tabular} \end{center} \vspace{-0.3cm} \end{table} \textbf{Effects of the maximum editing operations.} We perform experiments on the effects of the maximum editing operations. As shown in Table~\ref{tab:max-num}, ``$K$'' indicates the maximum number of editing operations. The number of editing operations on the original video-text pair is randomly selected in the range from 1 to $K$. It can be seen that it reaches the lowest WER when the max number of operations is 3. It can be explained that the lower number of operations makes the framework more concentrate on distinguishing the fine-grained differences between the real and pseudo video-text pairs. Unless stated, we set the default maximum operations as $K=3$ in the following experiments. \begin{table*} \begin{center} \caption{Evaluation on CSL dataset. ($\uparrow$ indicates the higher the better, while $\downarrow$ indicates the lower the better.)} \label{tab:csl} \tabcolsep=6pt \begin{tabular}{l|cccccccc} \hline Methods & Acc-w $\uparrow$ & BLEU-1 $\uparrow$ & CIDEr $\uparrow$ & ROUGE-L $\uparrow$ & METEOR $\uparrow$ & WER $\downarrow$ \\ \hline\hlin ELM~\cite{chen2014using} & 0.175 & 0.376 & 0.028 & 0.120 & 0.388 & 0.987 \\ LSTM \& CTC~\cite{graves2006connectionist,hochreiter1997long} & 0.332 & 0.343 & 0.241 & 0.362 & 0.111 & 0.757 \\ S2VT (3-layer)~\cite{venugopalan2015sequence} & 0.461 & 0.475 & 0.477 & 0.465 & 0.186 & 0.652 \\ HLSTM-attn~\cite{guo2018hierarchical} & 0.506 & 0.508 & 0.605 & 0.503 & 0.205 & 0.641 \\ HRF-Fusion~\cite{guo2019hierarchical} & 0.445 & 0.450 & 0.398 & 0.449 & 0.171 & 0.672 \\ IAN~\cite{pu2019iterative} & 0.670 & 0.724 & \textbf{3.946} & 0.716 & 0.383 & 0.327 \\ \hline \hline \textbf{Ours} & \textbf{0.747} & \textbf{0.784} & 3.006 & \textbf{0.782} & \textbf{0.390} & \textbf{0.245} \\ \hline \end{tabular} \end{center} \end{table*} \begin{table} \begin{center} \caption{Evaluation on RWTH-PHOENIX-Weather multi-signer dataset (the lower the better).} \label{tab:phoenix} \tabcolsep=5pt \begin{tabular}{l|rc|rc} \hline \multirow{2}{*}{Methods} & \multicolumn{2}{c|}{Dev} & \multicolumn{2}{c}{Test} \\ & del / ins & WER & del / ins & WER \\ \hline\hline CMLLR~\cite{koller2015continuous} & 21.8 / 3.9 & 55.0 & 20.3 / 4.5 & 53.0 \\ 1-Million-Hand~\cite{koller2016deep-cvpr} & 16.3 / 4.6 & 47.1 & 15.2 / 4.6 & 45.1 \\ CNN-Hybrid~\cite{koller2016deep} & 12.6 / 5.1 & 38.3 & 11.1 / 5.7 & 38.8 \\ SubUNets~\cite{camgoz2017subunets} & 14.6 / 4.0 & 40.8 & 14.3 / 4.0 & 40.7 \\ RCNN~\cite{cui2017recurrent} & 13.7 / 7.3 & 39.4 & 12.2 / 7.5 & 38.7 \\ Re-sign~\cite{koller2017re} & - & 27.1 & - & 26.8 \\ Hybrid CNN-HMM~\cite{koller2018deep} & - &31.6 & - & 32.5 \\ CNN-LSTM-HMM~\cite{koller2019weakly} & - & 26.0 & - & 26.0 \\ CTF~\cite{wang2018connectionist} & 12.8 / 5.2 & 37.9 & 11.9 / 5.6 & 37.8 \\ Dilated~\cite{pu2018dilated} & 8.3 / 4.8 & 38.0 & 7.6 / 4.8 & 37.3 \\ IAN~\cite{pu2019iterative} & 12.9 / 2.6 & 37.1 & 13.0 / 2.5 & 36.7 \\ DNF (RGB)~\cite{cui2019deep} & 7.8 / 3.5 & 23.8 & 7.8 / 3.4 & 24.4 \\ \hline \hline Ours & 7.3 / 2.7 & \textbf{21.3} & 7.3 / 2.4 & \textbf{21.9} \\ \hline \end{tabular} \end{center} \end{table} \begin{table} \begin{center} \caption{Evaluation on RWTH-PHOENIX-Weather signer-independent dataset (the lower the better).} \label{tab:s-ind} \tabcolsep=8pt \begin{tabular}{c|rc|rc} \hline \multirow{2}{*}{Methods} & \multicolumn{2}{c|}{Dev} & \multicolumn{2}{c}{Test} \\ & del / ins & WER & del / ins & WER \\ \hline\hline Re-sign~\cite{koller2017re} & - & 45.1 & - & 44.1 \\ Baseline~\cite{cui2019deep} & 9.2 / 4.3 & 36.0 & 9.5 / 4.6 & 35.7 \\ Ours & 11.1 / 2.4 & \textbf{34.8} & 11.4 / 3.3 & \textbf{34.3} \\ \hline \end{tabular} \end{center} \vspace{-0.3cm} \end{table} \subsection{Comparison with the State-of-the-art Methods} We perform extensive experiments and compare with other state-of-the-art methods on two benchmark datasets, including RWTH-PHOENIX-Weather multi-signer, signer-independent and CSL dataset. \textbf{Evaluation on the RWTH-PHOENIX-Weather multi-sign er dataset.} The results on RWTH-PHOENIX-Weather multi-signer dataset are shown in Table~\ref{tab:phoenix}. CMLLR \cite{koller2015continuous} and 1-Million-Hand \cite{koller2016deep-cvpr} are classical methods using hand-crafted features with traditional HMM models. CMLLR designs specific features to describe signs from different aspects of SLR, \emph{e.g.} HOG-3D features, trajectories with position, high-level face features and temporal derivatives. With the advance of deep learning, researchers utilize CNNs to adaptively extract feature representations with significant performance gain. SubUNets \cite{camgoz2017subunets} solves simultaneous alignment and recognition problems in an end-to-end framework by incorporating the CNN-BLSTM architecture supervised by the CTC loss. Re-sign \cite{koller2017re} presents an iterative re-alignment approach with further embedding a HMM to correct the frame labels and continuously improves its performance. DNF \cite{cui2019deep} explores the suitable CNN-BLSTM framework and the function of multiple input modalities, becoming the most competitive method. Even compared with these challenging methods, our method still achieves a new state-of-the-art result in this dataset, \emph{i.e.,} 21.3\% and 21.9\% WER on the dev and test set, respectively. It surpasses the best competitor with 2.6\% and 2.5\% on the dev and test set, respectively. \textbf{Evaluation on the RWTH-PHOENIX-Weather signer- independent dataset.} The signer-independent subset is created based on the RWTH-PHOENIX-Weather, where we test on a single individual who has not been seen during training. In Table~\ref{tab:s-ind}, we compare existing the methods on this dataset. It can be observed that our method still outperforms all the methods in this dataset, achieving 34.8\% and 34.3\% WER on the dev and test set, respectively. Compared with the best WER results on its multi-signer counterpart, the independent setting is a more challenging one, with over 10\% WER reduction. \textbf{Evaluation on the CSL dataset.} We perform experiments on the challenging split of the CSL dataset in Table~\ref{tab:csl}. This split is difficult due to the unseen combination and occurrence of words, and different semantic context in the test set. We compare our approach with other challenging methods, such as HRF-Fusion~\cite{guo2019hierarchical}, HLSTM-atten~\cite{guo2018hierarchical} and IAN \cite{pu2019iterative}. HLSTM-atten treats this task as sign language translation and proposes a hierarchical-LSTM (HLSTM) encoder-decoder model with visual content and word embedding, and utilize temporal attention for performance boost. IAN proposes to use the visual encoder and encoder-decoder sequence learning network with iterative refinement. Compared with these methods, our method also achieves the state-of-the-art performance on most of the evaluation metrics on this dataset. It should be noted that our method mimics the editing process and surpasses the best competitor with 8.2\% on the WER result, which is consistent with our optimization target. Besides, it also achieves the state-of-the-art performance on most semantic evaluation metrics, such as BLEU-1, ROUGE-L, METEOR, \emph{etc.} \section{Conclusion} In this paper, we attempt to tackle the issue of inconformity between the CTC objective and the evaluation metric via cross modality augmentation. Following the operations in the definition of WER, \emph{i.e.,} substitution, deletion and insertion, we edit the real video-text pair to generate its corresponding pseudo counterpart. Besides constraining the semantic correspondence between the video and text, we design a discriminative loss to make the network aware of the differences between the real and pseudo video-text pair. Our proposed framework can be easily extended to other existing CTC based continuous SLR networks. We conduct experiments on two continuous SLR benchmarks, \emph{i.e.,} RWTH-PHOENIX-Weather and CSL dataset. Experimental results validate the effectiveness of our proposed method with notable performance gain over previous methods, especially on the WER metric. \begin{acks} This work was supported in part to Dr. Houqiang Li by NSFC under contract No. 61836011, and in part to Dr. Wengang Zhou by NSFC under contract No. 61822208 \& 61632019 and Youth Innovation Promotion Association CAS (No. 2018497). \end{acks} \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-10-13T02:22:42', 'yymm': '2010', 'arxiv_id': '2010.05264', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05264'}
arxiv
\section{Introduction} \label{sec:intro} Nowadays, deep learning has become the major methodology in solving computer vision problems. Deep convolutional neural network (CNN)~\cite{krizhevsky2012imagenet,simonyan2014very,huang2017densely,he2016deep} is an important type of deep learning models and has shown outstanding performance on several tasks, including image classification~\cite{deng2009imagenet,du2020fine,zheng2020iu,ma2019fine}, object detection~\cite{lin2014microsoft,kuznetsova2018open}, and object segmentation~\cite{kuznetsova2018open,zhou2017scene}. Image classification, among others, is a basic vision ability of humans. It is a popular deep learning task and has been researched for decades. The loss function is a key component in deep CNN models for the purpose of parameter estimation and prior information constraint. For instance, a commonly used loss function, the cross entropy loss (CE-Loss)~\cite{sun2014deep,taigman2014deepface}, measures the distance between two probability distributions which adds information entropy as prior information to classification problem. Training with the CE-Loss improves the classification performance by increasing the predicted Softmax probability of the actual label. It guides the deep learning model to learn separate features for different classes. However, the CE-Loss has two main issues that limit the performance of a CNN model for classification. Firstly, the high level features extracted by CNNs with the CE-Loss are only separable with each other but not discriminative enough~\cite{chen2018virtual}, which can easily lead to over-fitting of the model and thus weak generalization performance. Secondly, the parameters of the deep CNN model are trained jointly with all the classes, which makes the high level features extracted by CNNs to be confused with each other and increases the difficulty of optimization. Many improvements on loss functions~\cite{chen2018virtual,liu2017sphereface,wen2016discriminative,wang2018cosface,deng2019arcface,hui2019inter,li2019large,chang2020devil} have been made to address the first problem, by introducing constrains to the feature space for discriminative feature embedding. The center loss~\cite{wen2016discriminative} calculates and updates the class centers within each mini batch, which leads to intra-class compactness. The sphereface loss~\cite{liu2017sphereface} introduces an angular margin to optimize the intra-class and inter-class relationship simultaneously, which yields features that are more discriminative. The cosface loss~\cite{wang2018cosface} adds a cosine angular margin according to the target logits to gain better performance against the sphereface loss. The arcface loss~\cite{deng2019arcface} further develops the angular margin to a addictive angular margin, using summation rather than multiplication for efficient training. The inter-class angular loss (ICAL)~\cite{hui2019inter} and the focal inter class angular loss (FICAL)~\cite{wei2019fical} also consider the angular constrains among classes. By using the cosine distances between the categories, these two loss functions both obtained higher classification accuracy among these loss functions. In addition to these improvements on loss functions for image classification, the focal loss~\cite{lin2017focal} is a loss function proposed for object detection, assigning bigger weights to hard examples and smaller weights to easy examples to deal with class imbalance problem. However, few loss functions have considered the second problem,~\emph{i.e.}, combining the network structure with intra-class and inter-class relationships to decrease the confusion between the features and reduce the difficulty of optimization. To handle this problem and motivated by the mutual channel loss~\cite{chang2020devil}, a recently proposed loss function that fixes the number of deep CNN channels for each class to obtain class-aligned features, we want to make different classes correspond to different channels of the features. This can make the samples belonging to different classes to train different parts of the deep CNN model and further learn the features from different classes to be distinguishable from each other. To this end, we propose a new loss function to align the channels to each sample. As shown in Fig.~\ref{fig:insight}, for the samples from the same class, the proposed loss function can make the channel attention vectors be similar to each other. At the meantime, for the samples belong to different classes, the difference between the channel attention vectors will be increased. Finally, we can obtain high intra-class and low inter-class similarity features, which are beneficial for the image classification task. The proposed loss function is termed as the channel correlation loss (CC-Loss). As shown in Fig.~\ref{fig:pipline}, it has two components that work together for feature embedding. Firstly, the squeeze-and-excitation module (SE module)~\cite{hu2018squeeze} is introduced to generate channel attention for each sample, which is a widely used channel attention module in image classification. After that, we need to consider the intra-class and inter-class relations based on the channel attention vectors. Following the previous idea in the loss function design, a loss function needs to minimize the intra-class difference and maximize the inter-class difference. Therefore, the proposed CC-Loss calculates an Euclidean distance matrix of the attention vectors from one mini-batch. Each item of the calculated matrix represents the Euclidean distance between the channel attention vectors taken from two input images. By minimizing the sum of the Euclidean distances from the same class and maximizing the sum of the Euclidean distances from different classes simultaneously, the CC-Loss guided the CNN model to extract the features that have good intra-class compactness and inter-class separability. The experiments have been conducted by applying the proposed CC-Loss on three commonly used datasets and two network architectures. Experimental results show that the models trained with the CC-Loss is able to extract more discriminative features and outperform the state-of-the-art methods. \begin{figure*} \centering \includegraphics[width=0.8\textwidth]{pipline.pdf} \caption{The pipeline of the proposed CC-Loss. Channel attention vectors extracted from each sample are labeled with ground truth classes. The labeled channel attention vectors will then be used to calculate a distance matrix, representing the similarity between channel attentions of different samples. The similarity of samples belonging to the same class should be minimized while the similarity of samples belonging to the different class should be maximized. The distances between samples from the same class is marked in black and those from different classes are marked in red.} \label{fig:pipline} \end{figure*} \section{The CC-Loss Framework} \label{sec:meth} \subsection{Channel attention module (CAM)} For the purpose of obtaining the channel attention vectors for each sample, we add the SE module to the classifier. The classifier in this work contains a hidden layer and a classification layer. The output of the hidden layer is the features, which are the input to the classification layer. We define the function of the hidden layer as $f_{1}(\cdot)$ and the function of the classification layer as $f_{2}(\cdot)$. Denote the features extracted from the CNN backbone as $\boldsymbol{F} = \left\{F_{1}, F_{2}, \cdots, F_{N} \right\}$, and the output of the classification layer is calculated as $ P_1 = f_{2}(\text{ReLU}(f_{1}(F)))$. Denote the function of the SE module as $f_{se}(\cdot)$ and the channel attention vector as $\textbf{c} = \left\{c_{1}, c_{2}, \cdots, c_{n}\right\}$ ($n$ is channel numbers of features). The channel attention vector will be multiplied to the output vector of $f_{1}(\cdot)$ element-wise. Then the calculation process of the classifier will be $ P_2 = f_{2}(\text{ReLU}(f_{1}(F) \cdot f_{se}(F)))$. \subsection{Channel Correlation Loss} The CE-Loss in each mini-batch can be defined as \begin{equation} \label{Eq:CEL} L_{ce_1} = -\frac{1}{N}\sum_{n=1}^{N}\log(\frac{e^{P_1^{Y_{n}}}}{\sum^{K}_{i=1}e^{P_1^{i}}}), \end{equation} where~\textit{N} is the batch size,~\textit{K} is the total number of classes, and $Y_{n}$ is the label of the $n^{th}$ sample. In the CC-Loss, we use the channel attention vectors from one mini batch to represent the intra- and inter-class relationships. Hence, the channel attention matrix $\boldsymbol{C}$ is presented as \begin{equation} \boldsymbol{C}=\left[ \begin{matrix} c_{1,1} & c_{1,2} & \cdots & c_{1,D} \\ c_{2,1} & c_{2,2} & \cdots & c_{2,D} \\ \vdots & \vdots & \ddots & \vdots \\ c_{N,1} & c_{N,2} & \cdots & c_{N,D} \\ \end{matrix} \right]_{N \times D}, \end{equation} where $c_{i,j}$ is the $j^{th}$ element in the channel attention vector of the $i^{th}$ sample. $N$ the is batch size and $D$ is the dimensionality of the hidden layer. Based on this design, we need to calculate the Euclidean distance between channel attention vectors to obtain the distance matrix from $\boldsymbol{C}$. The distance between the channel attention vector of sample $i$ and sample $j$ is \begin{equation} d_{i,j} = \sum_{d = 1}^{D}(c_{i, d} - c_{j, d})^{2}. \end{equation} Now we obtain the distance matrix $\boldsymbol{D}$ of channel attention vectors for one mini-batch as \begin{equation} \boldsymbol{D}=\left[ \begin{matrix} d_{1,1} & d_{1,2} & \cdots & d_{1,N} \\ d_{2,1} & d_{2,2} & \cdots & d_{2,N} \\ \vdots & \vdots & \ddots & \vdots \\ d_{N,1} & d_{N,2} & \cdots & d_{N,N} \end{matrix} \right]_{N \times N}. \end{equation} It is obvious that the Euclidean distance between the same sample will be $d_{i,i} = 0$ and the distance between the same sample pair is symmetric~\emph{i.e.}, $d_{i,j} = d_{j,i}$. Hence, we can further simplify the matrix to an upper triangular matrix as \begin{equation} \boldsymbol{D}^{\text{UT}} = \left[ \begin{matrix} 0 & d_{1,2} & \cdots & d_{1,N} \\ 0 & 0 & \cdots & d_{2,N} \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots &0 \end{matrix} \right]_{N \times N}. \end{equation} Now the distance matrix is simple enough to calculate the intra-class component and the inter-class component for the CC-Loss. The intra-class component is the sum of the distances within the same class. For example, if sample $i$ and sample $j$ are from the same class, $d_{i,j}$ is added to the intra-class component. Hence, $L_{intra}$ is calculated as \begin{equation} \label{Eq:Intra Comp} L_{intra} = \sum_{i=1}^{N}\sum_{j=i}^{N}d_{i,j}\cdot \text{I}(Y_{i}, Y_{j}), \end{equation} where the operator $\text{I}(Y_{i},Y_{j})$ is defined as \begin{equation} \nonumber \text{I}(Y_{i},Y_{j})=\left\{ \begin{split} 1, &\ \ \ Y_{i}=Y_{j}\\ 0, &\ \ \ \text{otherwise} \end{split} \right. . \end{equation} The inter-class component is the sum of distances from different classes. Therefore, $L_{inter}$ is \begin{equation} \label{Eq:Inter Comp} L_{inter} = \sum_{i=1}^{N}\sum_{j=i}^{N}d_{i,j}\cdot \left[1-\text{I}(Y_{i},Y_{j})\right]. \end{equation} The distances between the same class should be minimized, which forces the channel selection to be the same and enhances the intra-class compactness. Meanwhile, the distances among different classes should be maximized, which forces the channel selection to be different and enlarges the inter-class separability. Hence, the final loss function is defined as \begin{equation} L = L_{ce_2} + \lambda\cdot \frac{L_{intra}}{L_{inter} + \epsilon}, \end{equation} \begin{equation} L_{ce_2} = -\frac{1}{N}\sum_{n=1}^{N}\log(\frac{e^{P_2^{Y_{n}}}}{\sum^{K}_{i=1}e^{P_2^{i}}}), \end{equation} where $\epsilon$ is a small positive constant and $\lambda$ is a hyper-parameter. \subsection{Computational Complexity Reduction} The computational complexity to compute the distance matrix $D$ is $O(N^{2})$, while it is $O(N^{2})$ for calculating $L_{intra}$ and $L_{inter}$. Therefore, the overall computational complexity for CC-Loss is $O(N^{2})$. In order to facilitate the calculation, we reduce the computational complexity of calculating the distance matrix from $O(N^{2})$ to $O(N)$ by the following steps. Each item $d_{i,j}$ in the distance matrix $D$ is calculated as, \begin{equation} \begin{split} d_{i,j} = &\sum_{k = 1}^{D}(c_{i,k} - c_{j,k})^{2}\\ = &\sum_{k = 1}^{D}c_{i,k}^{2} + \sum_{k = 1}^{D}c_{j,k}^{2} - 2\sum_{k = 1}^{D}c_{i,k}c_{j,k}. \end{split} \end{equation} Donate $s_{i}$ as the square sum of each item of the $i^{th}$ channel attention vector in $C$, which is given as, \begin{equation} s_{i} = \sum_{k = 1}^{D}c_{i,k}^{2}, \end{equation} we and then calculate two auxiliary matrix $E$ and $E^\text{T}$ with computational complexity $O(n)$. Here, matrix $E$ is defined as, \begin{equation} E=\left[ \begin{matrix} s_{1} & s_{1} & \cdots & s_{1} \\ s_{2} & s_{2} & \cdots & s_{2} \\ \vdots & \vdots & \ddots & \vdots \\ s_{N} & s_{N} & \cdots & s_{N} \end{matrix} \right]_{N \times N}. \end{equation} After that, we calculate an auxiliary matrix $G = C \times C^\text{T}$ with $O(n)$, which is \begin{equation} \resizebox{0.85\linewidth}{!}{$ G= \left[ \begin{matrix} c_{1,1} & c_{1,2} & \cdots & c_{1,D} \\ c_{2,1} & c_{2,2} & \cdots & c_{2,D} \\ \vdots & \vdots & \ddots & \vdots \\ c_{N,1} & c_{N,2} & \cdots & c_{N,D} \\ \end{matrix} \right] \times \left[ \begin{matrix} c_{1,1} & c_{2,1} & \cdots & c_{N,1} \\ c_{1,2} & c_{2,2} & \cdots & c_{N,2} \\ \vdots & \vdots & \ddots & \vdots \\ c_{1,D} & c_{2,D} & \cdots & c_{N,D} \\ \end{matrix} \right] $}. \end{equation} Note that $G$ is a $N \times N$ matrix and the item $g_{i,j}$ in $G$ is \begin{equation} g_{i,j} = \sum_{k = 1}^{D}c_{i,k}c_{j,k}. \end{equation} Then, the matrix $D$ is now calculated as $D = E + E^\text{T} - 2G$. The overall computational complexity is reduced to $O(N)$. \section{Experimental Results and Discussions} \label{sec:exp} In this section, the proposed CC-Loss is evaluated on three datasets: MNIST~\cite{deng2012mnist}, CIFAR-$100$~\cite{krizhevsky2009cifar}, and Cars-$196$~\cite{KrauseStarkDengFei-Fei_3DRR2013}. Two CNN backbones, VGG$16$ and ResNet$18$, are investigated. Furthermore, we compare the CC-Loss with other loss functions including the CE-Loss~\cite{sun2014deep}, the Focal loss~\cite{lin2017focal}, the A-softmax loss~\cite{liu2017sphereface}, the inter-class angular loss (ICAL)~\cite{hui2019inter}, and the focal inter class angular loss (FICAL)~\cite{wei2019fical}. \subsection{Datasets description} \textbf{MNIST}~\cite{deng2012mnist} is a handwritten digits classification dataset contains numbers from zero to nine. It includes a training set with $60,000$ images and a test set with $10,000$ images. All the images have been normalized and resized to the size of $28\times28$.\\ \textbf{CIFAR-$100$}~\cite{krizhevsky2009cifar} is a natural scene image classification dataset that contains $60,000$ colored images from $100$ classes. The training set and the test set contain $50,000$ and $10,000$ images, respectively. All the images are with the resolution of $32\times32$. \\ \textbf{Cars-196}~\cite{KrauseStarkDengFei-Fei_3DRR2013} is a fine-grained vehicle classification dataset, which contains $8,144$ training images and $8,041$ test images from $196$ classes. \subsection{Implementation details} We applied the CC-loss function to two widely used CNN architectures,~\emph{i.e.}, VGG$16$ and ResNet$18$. \begin{table*} \centering \caption{Classification accuracy($\%$) with different loss functions. The backbone models were VGG$16$ and ResNet$18$ and evaluated on three datasets. All the CC-loss results are the average of five rounds evaluations.} \resizebox{0.9\textwidth}{!}{ \begin{tabular}{ccccc} \hline Loss Function & Backbone Model & MNIST & CIFAR-$100$ & Cars-$196$ \\ \hline CE Loss & VGG$16$/ResNet$18$ & $97.43$/$97.52$ & $74.49$/$77.38$ & $88.02$/$85.77$ \\ Focal Loss & VGG$16$/ResNet$18$ & $97.64$/$97.68$ & $74.46$/$77.63$ & $88.21$/$85.98$ \\ A-softmax Loss & VGG$16$/ResNet$18$ & $98.10$/$98.32$ & $74.55$/$77.78$ & $90.02$/$87.22$ \\ MC Loss & VGG$16$/ResNet$18$ & $98.20$/$\underline{98.45}$ & $72.51$/$70.18$ & $\textbf{92.80}$/- \\ ICAL & VGG$16$/ResNet$18$ & $97.83$/$98.21$ & $74.79$/$77.71$ & $89.32$/$86.67$ \\ FICAL & VGG$16$/ResNet$18$ & $\underline{98.22}$/$98.40$ & $\underline{74.98}$/$\underline{78.18}$ & $89.70$/$\underline{87.38}$ \\ \hline CC-Loss & VGG$16$ + CAM/ResNet$18$ + CAM & $\textbf{98.32}$ $\pm$ $\textbf{0.08}$/$\textbf{98.52}$ $\pm$ $\textbf{0.09}$ & $\textbf{75.49}$ $\pm$ $\textbf{0.15}$/$\textbf{78.23}$ $\pm$ $\textbf{0.07}$ & $\underline{91.46}$ $\pm$ $\underline{0.09}$/$\textbf{88.41 $\pm$ 0.06}$ \\ \hline \end{tabular}} \label{tab:SOTA} \end{table*} All the methods were trained with the stochastic gradient descent (SGD)~\cite{bottou2010large} algrithm with $300$ epochs. The batch sizes for MNIST, CIFAR-$100$, and Cars-$196$ were set to $32$, $32$, and $16$, respectively. The input image sizes were $24\times24$, randomly cropped $32\times32$, and randomly cropped $224\times224$ following a zero padding with size $4$ for MNIST, CIFAR-$100$, and Cars-$196$, respectively. Horizontally flipping with $0.5$ probability was also applied when training CIFAR-$100$ and Cars-$196$. The initial learning rate was set to $0.1$ and adjusted by the cosine annealing schedule~\cite{huang2017snapshot} to $1e-5$. We set the weight decay as $5e-4$ and the momentum as $0.9$. When training MNIST and CIFAR-$100$, the network parameters were initialized with the method in~\cite{he2015delving}. While training Cars-$196$, we used the ImageNet pretrained parameters as the initial ones. For the hyper-parameters of the loss functions used for comparison, we followed the referred papers. For the CC-Loss, we set $\lambda$ to $1$. All the experiments results reported shared the same hyper-parameters. We conducted each of our experiments five rounds and report the average accuracy and margin in the form of $accuracy \pm margin$. The margin is defined as maximum absolute difference between the five results and it's average. For baseline methods in Table~\ref{tab:SOTA} and Table~\ref{tab:CAM}, we refer to results from~\cite{chang2020devil} and~\cite{wei2019fical}, which only report average values. \begin{table} \centering \caption{Ablation Study on the batch size for the CC-Loss. The experiments were conducted on CIFAR-$100$ as well as Cars-$196$ datasets with VGG$16$ backbone.} \vspace{2mm} \begin{tabular}{ccc} \hline Batch Size & CIFAR-$100$ & Cars-$196$\\ \hline $8$ & $74.9 \pm 0.12$ & $91.3 \pm 0.12$ \\ $16$ & $75.3 \pm 0.07$ & $91.5 \pm 0.09$ \\ $32$ & $75.5 \pm 0.15$ & $91.3 \pm 0.16$ \\ $64$ & $75.1 \pm 0.14$ & $90.6 \pm 0.18$ \\ $128$ & $74.5 \pm 0.14$ & $89.9 \pm 0.15$ \\ \hline \end{tabular} \label{tab:batchsize} \end{table} \begin{table} \centering \caption{The $p$ values of one sample $t$-test.} \resizebox{0.45\textwidth}{!}{ \begin{tabular}[width=0.5\textwidth]{cccc} \hline Base Model & MNIST & CIFAR-$100$ & Cars-$196$ \\ \hline VGG$16$ & $3.9\times10^{-3}$ & $4.7\times10^{-4}$ & $2.1\times10^{-7}$ \\ ResNet$18$ & $3.3\times10^{-3}$ & $3.8\times10^{-3}$ & $4.3\times10^{-7}$ \\ \hline \end{tabular}} \label{tab:t-rest} \end{table} \begin{table*} \centering \caption{Ablation study of the channel attention module.} \resizebox{0.9\textwidth}{!}{ \begin{tabular}{ccccc} \hline Loss Function & Backbone Model & MNIST & CIFAR-$100$ & Cars-$196$ \\ \hline CE Loss & VGG$16$/ResNet$18$ & $97.43$/$97.52$ & $74.49$/$77.38$ & $88.02$/$85.77$ \\ CE Loss & VGG$16$ + CAM/ResNet$18$ + CAM & $97.66$ $\pm$ $0.02$/$97.67$ $\pm$ $0.01$ & $74.54$ $\pm$ $0.02$/$77.57$ $\pm$ $0.01$ & $88.15$ $\pm$ $0.03$/$86.04$ $\pm$ $0.02$ \\ CC Loss & VGG$16$ + CAM/ResNet$18$ + CAM & $98.32$ $\pm$ $0.08$/$98.52$ $\pm$ $0.09$ & $75.49$ $\pm$ $0.15$/$78.23$ $\pm$ $0.07$ & $91.46$ $\pm$ $0.09$/$88.41$ $\pm$ $0.06$ \\ \hline \end{tabular}} \label{tab:CAM} \end{table*} \begin{table} \centering \caption{The effect of $\lambda$ in CC-Loss. The experiments were conducted using VGG$16$ + CAM as the backbone } \vspace{2mm} \resizebox{0.45\textwidth}{!}{ \begin{tabular}[width=0.5\textwidth]{cccc} \hline $\lambda$ & MNIST & CIFAR-$100$ & Cars-$196$ \\ \hline $0$ & $97.66$ $\pm$ $0.02$ & $74.54$ $\pm$ $0.02$ & $88.15$ $\pm$ $0.03$ \\ $0.5$ & $98.04$ $\pm$ $0.05$ & $75.12$ $\pm$ $0.03$ & $89.53$ $\pm$ $0.07$ \\ $1.0$ & $98.32$ $\pm$ $0.08$ & $75.49$ $\pm$ $0.15$ & $91.46$ $\pm$ $0.09$ \\ $1.5$ & $97.95$ $\pm$ $0.06$ & $75.04$ $\pm$ $0.09$ & $89.42$ $\pm$ $0.05$ \\ $2.0$ & $97.53$ $\pm$ $0.03$ & $74.32$ $\pm$ $0.12$ & $87.84$ $\pm$ $0.02$ \\ \hline \end{tabular}} \label{tab:lambda} \end{table} \begin{figure*} \centering \subfigure[MNIST visualization for CE-Loss]{ \includegraphics[width=0.45\textwidth]{ce_loss_2.png} } \quad \subfigure[MNIST visualization for CC-Loss]{ \includegraphics[width=0.45\textwidth]{cc_loss_2.png} } \caption{Visualization on MNIST dataset trained by CE-Loss and CC-Loss. The left sub-figure and the right sub-figure shows the results on training set and test set respectively.} \label{fig:vis} \vspace{-2mm} \end{figure*} \vspace{-4mm} \subsection{Comparison with state-of-the-art methods} As shown in Table~\ref{tab:SOTA}, the proposed CC-Loss outperforms the CE-Loss by a large margin. For ResNet$18$, the CC-Loss improves the performance from $97.52\%$ to $98.52\%$, $77.38\%$ to $78.23\%$, and $85.77\%$ to $88.41\%$ on MNIST, CIFAR-$100$, and Cars-$196$ dataset, respectively. For VGG$16$, the CC-Loss outperforms the CE-Loss by $0.89\%$, $1\%$, and $3.33\%$ on MNIST, CIFAR-$100$, and Cars-$196$, respectively. These results indicate the class relation constraints in the CC-Loss indeed help the CNN model with more discriminative features, which shows the effectiveness of the CC-Loss. The improvement on Cars-$196$ dataset is the most significant as the class relationship in the fine-grined image classification dataset is more complex. Therefore, it benefits more from the class relation constrains. The VGG$16$ backbone gets more improvement over ResNet$18$ for higher parameter numbers bring to higher model capacity, which react better with more prior information generated by CC-Loss. While comparing with the state-of-the-art loss functions that only focus on intra- and inter-class relations, the CC-Loss also shows competitive performance on all the three datasets. For ResNet$18$, CC-Loss gets slightly better results on MNIST and CIFAR-$100$ compared to the second best FICAL loss, and get $1.03\%$ boosting performance on the Cars-$196$ dataset. For VGG-$16$, the CC-Loss gets $0.1\%$ and $0.51\%$ improvement against the FICAL loss on MNIST and CIFAR-$100$. It also gets $1.44\%$ accuracy improvement compared with the second best A-softmax Loss. These demonstrate that the additional dynamic class-channel mechanism can help with the classification task. Specifically, we further analyze the results of the MC-Loss, another loss function which focuses on channel-wise intra-class and inter-class relationship designed for the fine-grained visual classification (FGVC) task. The MC-Loss has better performance on the Cars-196 dataset, which is a FGVC dataset. But it has worse performance on image classification datasets,~\emph{i.e.}, MNIST and CIFAR-100. The key reason is that MC-Loss allocates constant channel numbers for each class (3 channels for each class in Cars-196) and learns three different feature maps for each class. While in general image classification tasks, there might not be enough separate feature map for each sample, this will yield sub-optimization of the feature maps and can not meet the separation constraint. Furthermore, using constant channel number is unsuitable for CIFAR and MNIST classes, which also causes a worse result of MC-Loss. \subsection{The effect of CAM} We add a channel attention model on top of the CNN backbone to meet the requirement of dynamic channel selection. An ablation study is proposed to show the performance of the channel attention module when CC-Loss is not applied. As shown in Table~\ref{tab:CAM}, in the case of w/o CC-Loss, dynamic channel selection gives slight improvement against the original backbone. When CC-Loss is used, it provides extra class relation constraint to boost the performance. Also, it is worth to note that CC-Loss can not be implemented without the CAM module. \subsection{The effect of weight in CC-Loss } As shown in Table~\ref{tab:lambda}, we evaluated the performance of different $\lambda$, representing the influence of CC-Loss. The best result is obtained when $\lambda$ is $1$. Further increasing $\lambda$ will cause performance drop because we need class-label relationship provided by the CE-Loss. \subsection{Hyper-parameter tuning on batch size} Since we optimize the channel attention distances within mini-batchs, the batch size is an important hyper-parameter to be tuned. We analyzed the affect of batch size on CIFAR-$100$ and Cars-$196$ datasets with VGG$16$ as the backbone. As shown in Table~\ref{tab:batchsize}, a smaller batch size leads to a higher classification accuracy, since the class relationship in the distance matrix is simpler and easier to optimize. However, when the batch size tends to be very small, the class relationship will disappear and thus the accuracy is decreased. Therefore, we empirically chose a batch size of $32$ for the CIFAR-$100$ dataset and a batch size of $16$ for the Cars-$196$ dataset. \vspace{-2mm} \subsection{Statistical significance analysis} As the number of experiments is less than $30$, we used the one sample unpaired $t$-test~\cite{posten1979robustness} to evaluate the statistical significance of the results. We took the values from the state-of-the-art method as the general average value for test. More specifically, we used the results from the A-softmax Loss for Cars-$196$ dataset on VGG$16$ backbone and the results from the FICAL Loss for the rest. As shown in Table~\ref{tab:t-rest}, all the $p$-values of the one sample $t$-test with SOTA results are below $5\times10^{-3}$, which indicates statistically significant improvements obtained by the CC-Loss compared with the baseline loss functions. \vspace{-2mm} \subsection{Visualization} We carry out the visualization experiments by training VGG$16$ on the MNIST dataset. The output dimensionality of the first linear layer in VGG$16$ was set to $2$. The features extracted from the first linear layer are visualized to present the feature space obtained by the CE-Loss and the CC-Loss. From Fig.~\ref{fig:vis}, it can be observed that the features from the CC-Loss are more compact within the same class while more separable among the neighbour classes. This demonstrates the effectiveness of intra-class and inter-class component of CC-Loss. \vspace{-4mm} \section{Conclusions} In this paper, we proposed a new loss function, namely the Channel Correlation Loss (CC-Loss), for the task of image classification. The CC-Loss dynamically selects the CNN channels for each class via the channel attention mechanism. It assigns larger numbers of channels to the harder classes and smaller numbers of channels to the easier class. Furthermore, by considering the Euclidean distances of the channel attention vectors in mini-batches, the CC-Loss is able to maximize both the intra-class compactness and the inter-class separability, which can extract more discriminative features. Experimental results on three datasets with two different backbones demonstrated that the proposed method outperforms commonly used loss functions. \bibliographystyle{IEEEbib} \section{Introduction} \label{sec:intro} Nowadays, deep learning has become the major methodology in solving computer vision problems. Deep convolutional neural network (CNN)~\cite{krizhevsky2012imagenet,simonyan2014very,huang2017densely,he2016deep} is an important type of deep learning models and has shown outstanding performance on several tasks, including image classification~\cite{deng2009imagenet,du2020fine,zheng2020iu,ma2019fine}, object detection~\cite{lin2014microsoft,kuznetsova2018open}, and object segmentation~\cite{kuznetsova2018open,zhou2017scene}. Image classification, among others, is a basic vision ability of humans. It is a popular deep learning task and has been researched for decades. The loss function is a key component in deep CNN models for the purpose of parameter estimation and prior information constraint. For instance, a commonly used loss function, the cross entropy loss (CE-Loss)~\cite{sun2014deep,taigman2014deepface}, measures the distance between two probability distributions which adds information entropy as prior information to classification problem. Training with the CE-Loss improves the classification performance by increasing the predicted Softmax probability of the actual label. It guides the deep learning model to learn separate features for different classes. However, the CE-Loss has two main issues that limit the performance of a CNN model for classification. Firstly, the high level features extracted by CNNs with the CE-Loss are only separable with each other but not discriminative enough~\cite{chen2018virtual}, which can easily lead to over-fitting of the model and thus weak generalization performance. Secondly, the parameters of the deep CNN model are trained jointly with all the classes, which makes the high level features extracted by CNNs to be confused with each other and increases the difficulty of optimization. Many improvements on loss functions~\cite{chen2018virtual,liu2017sphereface,wen2016discriminative,wang2018cosface,deng2019arcface,hui2019inter,li2019large,chang2020devil} have been made to address the first problem, by introducing constrains to the feature space for discriminative feature embedding. The center loss~\cite{wen2016discriminative} calculates and updates the class centers within each mini batch, which leads to intra-class compactness. The sphereface loss~\cite{liu2017sphereface} introduces an angular margin to optimize the intra-class and inter-class relationship simultaneously, which yields features that are more discriminative. The cosface loss~\cite{wang2018cosface} adds a cosine angular margin according to the target logits to gain better performance against the sphereface loss. The arcface loss~\cite{deng2019arcface} further develops the angular margin to a addictive angular margin, using summation rather than multiplication for efficient training. The inter-class angular loss (ICAL)~\cite{hui2019inter} and the focal inter class angular loss (FICAL)~\cite{wei2019fical} also consider the angular constrains among classes. By using the cosine distances between the categories, these two loss functions both obtained higher classification accuracy among these loss functions. In addition to these improvements on loss functions for image classification, the focal loss~\cite{lin2017focal} is a loss function proposed for object detection, assigning bigger weights to hard examples and smaller weights to easy examples to deal with class imbalance problem. However, few loss functions have considered the second problem,~\emph{i.e.}, combining the network structure with intra-class and inter-class relationships to decrease the confusion between the features and reduce the difficulty of optimization. To handle this problem and motivated by the mutual channel loss~\cite{chang2020devil}, a recently proposed loss function that fixes the number of deep CNN channels for each class to obtain class-aligned features, we want to make different classes correspond to different channels of the features. This can make the samples belonging to different classes to train different parts of the deep CNN model and further learn the features from different classes to be distinguishable from each other. To this end, we propose a new loss function to align the channels to each sample. As shown in Fig.~\ref{fig:insight}, for the samples from the same class, the proposed loss function can make the channel attention vectors be similar to each other. At the meantime, for the samples belong to different classes, the difference between the channel attention vectors will be increased. Finally, we can obtain high intra-class and low inter-class similarity features, which are beneficial for the image classification task. The proposed loss function is termed as the channel correlation loss (CC-Loss). As shown in Fig.~\ref{fig:pipline}, it has two components that work together for feature embedding. Firstly, the squeeze-and-excitation module (SE module)~\cite{hu2018squeeze} is introduced to generate channel attention for each sample, which is a widely used channel attention module in image classification. After that, we need to consider the intra-class and inter-class relations based on the channel attention vectors. Following the previous idea in the loss function design, a loss function needs to minimize the intra-class difference and maximize the inter-class difference. Therefore, the proposed CC-Loss calculates an Euclidean distance matrix of the attention vectors from one mini-batch. Each item of the calculated matrix represents the Euclidean distance between the channel attention vectors taken from two input images. By minimizing the sum of the Euclidean distances from the same class and maximizing the sum of the Euclidean distances from different classes simultaneously, the CC-Loss guided the CNN model to extract the features that have good intra-class compactness and inter-class separability. The experiments have been conducted by applying the proposed CC-Loss on three commonly used datasets and two network architectures. Experimental results show that the models trained with the CC-Loss is able to extract more discriminative features and outperform the state-of-the-art methods. \begin{figure*} \centering \includegraphics[width=0.8\textwidth]{pipline.pdf} \caption{The pipeline of the proposed CC-Loss. Channel attention vectors extracted from each sample are labeled with ground truth classes. The labeled channel attention vectors will then be used to calculate a distance matrix, representing the similarity between channel attentions of different samples. The similarity of samples belonging to the same class should be minimized while the similarity of samples belonging to the different class should be maximized. The distances between samples from the same class is marked in black and those from different classes are marked in red.} \label{fig:pipline} \end{figure*} \section{The CC-Loss Framework} \label{sec:meth} \subsection{Channel attention module (CAM)} For the purpose of obtaining the channel attention vectors for each sample, we add the SE module to the classifier. The classifier in this work contains a hidden layer and a classification layer. The output of the hidden layer is the features, which are the input to the classification layer. We define the function of the hidden layer as $f_{1}(\cdot)$ and the function of the classification layer as $f_{2}(\cdot)$. Denote the features extracted from the CNN backbone as $\boldsymbol{F} = \left\{F_{1}, F_{2}, \cdots, F_{N} \right\}$, and the output of the classification layer is calculated as $ P_1 = f_{2}(\text{ReLU}(f_{1}(F)))$. Denote the function of the SE module as $f_{se}(\cdot)$ and the channel attention vector as $\textbf{c} = \left\{c_{1}, c_{2}, \cdots, c_{n}\right\}$ ($n$ is channel numbers of features). The channel attention vector will be multiplied to the output vector of $f_{1}(\cdot)$ element-wise. Then the calculation process of the classifier will be $ P_2 = f_{2}(\text{ReLU}(f_{1}(F) \cdot f_{se}(F)))$. \subsection{Channel Correlation Loss} The CE-Loss in each mini-batch can be defined as \begin{equation} \label{Eq:CEL} L_{ce_1} = -\frac{1}{N}\sum_{n=1}^{N}\log(\frac{e^{P_1^{Y_{n}}}}{\sum^{K}_{i=1}e^{P_1^{i}}}), \end{equation} where~\textit{N} is the batch size,~\textit{K} is the total number of classes, and $Y_{n}$ is the label of the $n^{th}$ sample. In the CC-Loss, we use the channel attention vectors from one mini batch to represent the intra- and inter-class relationships. Hence, the channel attention matrix $\boldsymbol{C}$ is presented as \begin{equation} \boldsymbol{C}=\left[ \begin{matrix} c_{1,1} & c_{1,2} & \cdots & c_{1,D} \\ c_{2,1} & c_{2,2} & \cdots & c_{2,D} \\ \vdots & \vdots & \ddots & \vdots \\ c_{N,1} & c_{N,2} & \cdots & c_{N,D} \\ \end{matrix} \right]_{N \times D}, \end{equation} where $c_{i,j}$ is the $j^{th}$ element in the channel attention vector of the $i^{th}$ sample. $N$ the is batch size and $D$ is the dimensionality of the hidden layer. Based on this design, we need to calculate the Euclidean distance between channel attention vectors to obtain the distance matrix from $\boldsymbol{C}$. The distance between the channel attention vector of sample $i$ and sample $j$ is \begin{equation} d_{i,j} = \sum_{d = 1}^{D}(c_{i, d} - c_{j, d})^{2}. \end{equation} Now we obtain the distance matrix $\boldsymbol{D}$ of channel attention vectors for one mini-batch as \begin{equation} \boldsymbol{D}=\left[ \begin{matrix} d_{1,1} & d_{1,2} & \cdots & d_{1,N} \\ d_{2,1} & d_{2,2} & \cdots & d_{2,N} \\ \vdots & \vdots & \ddots & \vdots \\ d_{N,1} & d_{N,2} & \cdots & d_{N,N} \end{matrix} \right]_{N \times N}. \end{equation} It is obvious that the Euclidean distance between the same sample will be $d_{i,i} = 0$ and the distance between the same sample pair is symmetric~\emph{i.e.}, $d_{i,j} = d_{j,i}$. Hence, we can further simplify the matrix to an upper triangular matrix as \begin{equation} \boldsymbol{D}^{\text{UT}} = \left[ \begin{matrix} 0 & d_{1,2} & \cdots & d_{1,N} \\ 0 & 0 & \cdots & d_{2,N} \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots &0 \end{matrix} \right]_{N \times N}. \end{equation} Now the distance matrix is simple enough to calculate the intra-class component and the inter-class component for the CC-Loss. The intra-class component is the sum of the distances within the same class. For example, if sample $i$ and sample $j$ are from the same class, $d_{i,j}$ is added to the intra-class component. Hence, $L_{intra}$ is calculated as \begin{equation} \label{Eq:Intra Comp} L_{intra} = \sum_{i=1}^{N}\sum_{j=i}^{N}d_{i,j}\cdot \text{I}(Y_{i}, Y_{j}), \end{equation} where the operator $\text{I}(Y_{i},Y_{j})$ is defined as \begin{equation} \nonumber \text{I}(Y_{i},Y_{j})=\left\{ \begin{split} 1, &\ \ \ Y_{i}=Y_{j}\\ 0, &\ \ \ \text{otherwise} \end{split} \right. . \end{equation} The inter-class component is the sum of distances from different classes. Therefore, $L_{inter}$ is \begin{equation} \label{Eq:Inter Comp} L_{inter} = \sum_{i=1}^{N}\sum_{j=i}^{N}d_{i,j}\cdot \left[1-\text{I}(Y_{i},Y_{j})\right]. \end{equation} The distances between the same class should be minimized, which forces the channel selection to be the same and enhances the intra-class compactness. Meanwhile, the distances among different classes should be maximized, which forces the channel selection to be different and enlarges the inter-class separability. Hence, the final loss function is defined as \begin{equation} L = L_{ce_2} + \lambda\cdot \frac{L_{intra}}{L_{inter} + \epsilon}, \end{equation} \begin{equation} L_{ce_2} = -\frac{1}{N}\sum_{n=1}^{N}\log(\frac{e^{P_2^{Y_{n}}}}{\sum^{K}_{i=1}e^{P_2^{i}}}), \end{equation} where $\epsilon$ is a small positive constant and $\lambda$ is a hyper-parameter. \subsection{Computational Complexity Reduction} The computational complexity to compute the distance matrix $D$ is $O(N^{2})$, while it is $O(N^{2})$ for calculating $L_{intra}$ and $L_{inter}$. Therefore, the overall computational complexity for CC-Loss is $O(N^{2})$. In order to facilitate the calculation, we reduce the computational complexity of calculating the distance matrix from $O(N^{2})$ to $O(N)$ by the following steps. Each item $d_{i,j}$ in the distance matrix $D$ is calculated as, \begin{equation} \begin{split} d_{i,j} = &\sum_{k = 1}^{D}(c_{i,k} - c_{j,k})^{2}\\ = &\sum_{k = 1}^{D}c_{i,k}^{2} + \sum_{k = 1}^{D}c_{j,k}^{2} - 2\sum_{k = 1}^{D}c_{i,k}c_{j,k}. \end{split} \end{equation} Donate $s_{i}$ as the square sum of each item of the $i^{th}$ channel attention vector in $C$, which is given as, \begin{equation} s_{i} = \sum_{k = 1}^{D}c_{i,k}^{2}, \end{equation} we and then calculate two auxiliary matrix $E$ and $E^\text{T}$ with computational complexity $O(n)$. Here, matrix $E$ is defined as, \begin{equation} E=\left[ \begin{matrix} s_{1} & s_{1} & \cdots & s_{1} \\ s_{2} & s_{2} & \cdots & s_{2} \\ \vdots & \vdots & \ddots & \vdots \\ s_{N} & s_{N} & \cdots & s_{N} \end{matrix} \right]_{N \times N}. \end{equation} After that, we calculate an auxiliary matrix $G = C \times C^\text{T}$ with $O(n)$, which is \begin{equation} \resizebox{0.85\linewidth}{!}{$ G= \left[ \begin{matrix} c_{1,1} & c_{1,2} & \cdots & c_{1,D} \\ c_{2,1} & c_{2,2} & \cdots & c_{2,D} \\ \vdots & \vdots & \ddots & \vdots \\ c_{N,1} & c_{N,2} & \cdots & c_{N,D} \\ \end{matrix} \right] \times \left[ \begin{matrix} c_{1,1} & c_{2,1} & \cdots & c_{N,1} \\ c_{1,2} & c_{2,2} & \cdots & c_{N,2} \\ \vdots & \vdots & \ddots & \vdots \\ c_{1,D} & c_{2,D} & \cdots & c_{N,D} \\ \end{matrix} \right] $}. \end{equation} Note that $G$ is a $N \times N$ matrix and the item $g_{i,j}$ in $G$ is \begin{equation} g_{i,j} = \sum_{k = 1}^{D}c_{i,k}c_{j,k}. \end{equation} Then, the matrix $D$ is now calculated as $D = E + E^\text{T} - 2G$. The overall computational complexity is reduced to $O(N)$. \section{Experimental Results and Discussions} \label{sec:exp} In this section, the proposed CC-Loss is evaluated on three datasets: MNIST~\cite{deng2012mnist}, CIFAR-$100$~\cite{krizhevsky2009cifar}, and Cars-$196$~\cite{KrauseStarkDengFei-Fei_3DRR2013}. Two CNN backbones, VGG$16$ and ResNet$18$, are investigated. Furthermore, we compare the CC-Loss with other loss functions including the CE-Loss~\cite{sun2014deep}, the Focal loss~\cite{lin2017focal}, the A-softmax loss~\cite{liu2017sphereface}, the inter-class angular loss (ICAL)~\cite{hui2019inter}, and the focal inter class angular loss (FICAL)~\cite{wei2019fical}. \subsection{Datasets description} \textbf{MNIST}~\cite{deng2012mnist} is a handwritten digits classification dataset contains numbers from zero to nine. It includes a training set with $60,000$ images and a test set with $10,000$ images. All the images have been normalized and resized to the size of $28\times28$.\\ \textbf{CIFAR-$100$}~\cite{krizhevsky2009cifar} is a natural scene image classification dataset that contains $60,000$ colored images from $100$ classes. The training set and the test set contain $50,000$ and $10,000$ images, respectively. All the images are with the resolution of $32\times32$. \\ \textbf{Cars-196}~\cite{KrauseStarkDengFei-Fei_3DRR2013} is a fine-grained vehicle classification dataset, which contains $8,144$ training images and $8,041$ test images from $196$ classes. \subsection{Implementation details} We applied the CC-loss function to two widely used CNN architectures,~\emph{i.e.}, VGG$16$ and ResNet$18$. \begin{table*} \centering \caption{Classification accuracy($\%$) with different loss functions. The backbone models were VGG$16$ and ResNet$18$ and evaluated on three datasets. All the CC-loss results are the average of five rounds evaluations.} \resizebox{0.9\textwidth}{!}{ \begin{tabular}{ccccc} \hline Loss Function & Backbone Model & MNIST & CIFAR-$100$ & Cars-$196$ \\ \hline CE Loss & VGG$16$/ResNet$18$ & $97.43$/$97.52$ & $74.49$/$77.38$ & $88.02$/$85.77$ \\ Focal Loss & VGG$16$/ResNet$18$ & $97.64$/$97.68$ & $74.46$/$77.63$ & $88.21$/$85.98$ \\ A-softmax Loss & VGG$16$/ResNet$18$ & $98.10$/$98.32$ & $74.55$/$77.78$ & $90.02$/$87.22$ \\ MC Loss & VGG$16$/ResNet$18$ & $98.20$/$\underline{98.45}$ & $72.51$/$70.18$ & $\textbf{92.80}$/- \\ ICAL & VGG$16$/ResNet$18$ & $97.83$/$98.21$ & $74.79$/$77.71$ & $89.32$/$86.67$ \\ FICAL & VGG$16$/ResNet$18$ & $\underline{98.22}$/$98.40$ & $\underline{74.98}$/$\underline{78.18}$ & $89.70$/$\underline{87.38}$ \\ \hline CC-Loss & VGG$16$ + CAM/ResNet$18$ + CAM & $\textbf{98.32}$ $\pm$ $\textbf{0.08}$/$\textbf{98.52}$ $\pm$ $\textbf{0.09}$ & $\textbf{75.49}$ $\pm$ $\textbf{0.15}$/$\textbf{78.23}$ $\pm$ $\textbf{0.07}$ & $\underline{91.46}$ $\pm$ $\underline{0.09}$/$\textbf{88.41 $\pm$ 0.06}$ \\ \hline \end{tabular}} \label{tab:SOTA} \end{table*} All the methods were trained with the stochastic gradient descent (SGD)~\cite{bottou2010large} algrithm with $300$ epochs. The batch sizes for MNIST, CIFAR-$100$, and Cars-$196$ were set to $32$, $32$, and $16$, respectively. The input image sizes were $24\times24$, randomly cropped $32\times32$, and randomly cropped $224\times224$ following a zero padding with size $4$ for MNIST, CIFAR-$100$, and Cars-$196$, respectively. Horizontally flipping with $0.5$ probability was also applied when training CIFAR-$100$ and Cars-$196$. The initial learning rate was set to $0.1$ and adjusted by the cosine annealing schedule~\cite{huang2017snapshot} to $1e-5$. We set the weight decay as $5e-4$ and the momentum as $0.9$. When training MNIST and CIFAR-$100$, the network parameters were initialized with the method in~\cite{he2015delving}. While training Cars-$196$, we used the ImageNet pretrained parameters as the initial ones. For the hyper-parameters of the loss functions used for comparison, we followed the referred papers. For the CC-Loss, we set $\lambda$ to $1$. All the experiments results reported shared the same hyper-parameters. We conducted each of our experiments five rounds and report the average accuracy and margin in the form of $accuracy \pm margin$. The margin is defined as maximum absolute difference between the five results and it's average. For baseline methods in Table~\ref{tab:SOTA} and Table~\ref{tab:CAM}, we refer to results from~\cite{chang2020devil} and~\cite{wei2019fical}, which only report average values. \begin{table} \centering \caption{Ablation Study on the batch size for the CC-Loss. The experiments were conducted on CIFAR-$100$ as well as Cars-$196$ datasets with VGG$16$ backbone.} \vspace{2mm} \begin{tabular}{ccc} \hline Batch Size & CIFAR-$100$ & Cars-$196$\\ \hline $8$ & $74.9 \pm 0.12$ & $91.3 \pm 0.12$ \\ $16$ & $75.3 \pm 0.07$ & $91.5 \pm 0.09$ \\ $32$ & $75.5 \pm 0.15$ & $91.3 \pm 0.16$ \\ $64$ & $75.1 \pm 0.14$ & $90.6 \pm 0.18$ \\ $128$ & $74.5 \pm 0.14$ & $89.9 \pm 0.15$ \\ \hline \end{tabular} \label{tab:batchsize} \end{table} \begin{table} \centering \caption{The $p$ values of one sample $t$-test.} \resizebox{0.45\textwidth}{!}{ \begin{tabular}[width=0.5\textwidth]{cccc} \hline Base Model & MNIST & CIFAR-$100$ & Cars-$196$ \\ \hline VGG$16$ & $3.9\times10^{-3}$ & $4.7\times10^{-4}$ & $2.1\times10^{-7}$ \\ ResNet$18$ & $3.3\times10^{-3}$ & $3.8\times10^{-3}$ & $4.3\times10^{-7}$ \\ \hline \end{tabular}} \label{tab:t-rest} \end{table} \begin{table*} \centering \caption{Ablation study of the channel attention module.} \resizebox{0.9\textwidth}{!}{ \begin{tabular}{ccccc} \hline Loss Function & Backbone Model & MNIST & CIFAR-$100$ & Cars-$196$ \\ \hline CE Loss & VGG$16$/ResNet$18$ & $97.43$/$97.52$ & $74.49$/$77.38$ & $88.02$/$85.77$ \\ CE Loss & VGG$16$ + CAM/ResNet$18$ + CAM & $97.66$ $\pm$ $0.02$/$97.67$ $\pm$ $0.01$ & $74.54$ $\pm$ $0.02$/$77.57$ $\pm$ $0.01$ & $88.15$ $\pm$ $0.03$/$86.04$ $\pm$ $0.02$ \\ CC Loss & VGG$16$ + CAM/ResNet$18$ + CAM & $98.32$ $\pm$ $0.08$/$98.52$ $\pm$ $0.09$ & $75.49$ $\pm$ $0.15$/$78.23$ $\pm$ $0.07$ & $91.46$ $\pm$ $0.09$/$88.41$ $\pm$ $0.06$ \\ \hline \end{tabular}} \label{tab:CAM} \end{table*} \begin{table} \centering \caption{The effect of $\lambda$ in CC-Loss. The experiments were conducted using VGG$16$ + CAM as the backbone } \vspace{2mm} \resizebox{0.45\textwidth}{!}{ \begin{tabular}[width=0.5\textwidth]{cccc} \hline $\lambda$ & MNIST & CIFAR-$100$ & Cars-$196$ \\ \hline $0$ & $97.66$ $\pm$ $0.02$ & $74.54$ $\pm$ $0.02$ & $88.15$ $\pm$ $0.03$ \\ $0.5$ & $98.04$ $\pm$ $0.05$ & $75.12$ $\pm$ $0.03$ & $89.53$ $\pm$ $0.07$ \\ $1.0$ & $98.32$ $\pm$ $0.08$ & $75.49$ $\pm$ $0.15$ & $91.46$ $\pm$ $0.09$ \\ $1.5$ & $97.95$ $\pm$ $0.06$ & $75.04$ $\pm$ $0.09$ & $89.42$ $\pm$ $0.05$ \\ $2.0$ & $97.53$ $\pm$ $0.03$ & $74.32$ $\pm$ $0.12$ & $87.84$ $\pm$ $0.02$ \\ \hline \end{tabular}} \label{tab:lambda} \end{table} \begin{figure*} \centering \subfigure[MNIST visualization for CE-Loss]{ \includegraphics[width=0.45\textwidth]{ce_loss_2.png} } \quad \subfigure[MNIST visualization for CC-Loss]{ \includegraphics[width=0.45\textwidth]{cc_loss_2.png} } \caption{Visualization on MNIST dataset trained by CE-Loss and CC-Loss. The left sub-figure and the right sub-figure shows the results on training set and test set respectively.} \label{fig:vis} \vspace{-2mm} \end{figure*} \vspace{-4mm} \subsection{Comparison with state-of-the-art methods} As shown in Table~\ref{tab:SOTA}, the proposed CC-Loss outperforms the CE-Loss by a large margin. For ResNet$18$, the CC-Loss improves the performance from $97.52\%$ to $98.52\%$, $77.38\%$ to $78.23\%$, and $85.77\%$ to $88.41\%$ on MNIST, CIFAR-$100$, and Cars-$196$ dataset, respectively. For VGG$16$, the CC-Loss outperforms the CE-Loss by $0.89\%$, $1\%$, and $3.33\%$ on MNIST, CIFAR-$100$, and Cars-$196$, respectively. These results indicate the class relation constraints in the CC-Loss indeed help the CNN model with more discriminative features, which shows the effectiveness of the CC-Loss. The improvement on Cars-$196$ dataset is the most significant as the class relationship in the fine-grined image classification dataset is more complex. Therefore, it benefits more from the class relation constrains. The VGG$16$ backbone gets more improvement over ResNet$18$ for higher parameter numbers bring to higher model capacity, which react better with more prior information generated by CC-Loss. While comparing with the state-of-the-art loss functions that only focus on intra- and inter-class relations, the CC-Loss also shows competitive performance on all the three datasets. For ResNet$18$, CC-Loss gets slightly better results on MNIST and CIFAR-$100$ compared to the second best FICAL loss, and get $1.03\%$ boosting performance on the Cars-$196$ dataset. For VGG-$16$, the CC-Loss gets $0.1\%$ and $0.51\%$ improvement against the FICAL loss on MNIST and CIFAR-$100$. It also gets $1.44\%$ accuracy improvement compared with the second best A-softmax Loss. These demonstrate that the additional dynamic class-channel mechanism can help with the classification task. Specifically, we further analyze the results of the MC-Loss, another loss function which focuses on channel-wise intra-class and inter-class relationship designed for the fine-grained visual classification (FGVC) task. The MC-Loss has better performance on the Cars-196 dataset, which is a FGVC dataset. But it has worse performance on image classification datasets,~\emph{i.e.}, MNIST and CIFAR-100. The key reason is that MC-Loss allocates constant channel numbers for each class (3 channels for each class in Cars-196) and learns three different feature maps for each class. While in general image classification tasks, there might not be enough separate feature map for each sample, this will yield sub-optimization of the feature maps and can not meet the separation constraint. Furthermore, using constant channel number is unsuitable for CIFAR and MNIST classes, which also causes a worse result of MC-Loss. \subsection{The effect of CAM} We add a channel attention model on top of the CNN backbone to meet the requirement of dynamic channel selection. An ablation study is proposed to show the performance of the channel attention module when CC-Loss is not applied. As shown in Table~\ref{tab:CAM}, in the case of w/o CC-Loss, dynamic channel selection gives slight improvement against the original backbone. When CC-Loss is used, it provides extra class relation constraint to boost the performance. Also, it is worth to note that CC-Loss can not be implemented without the CAM module. \subsection{The effect of weight in CC-Loss } As shown in Table~\ref{tab:lambda}, we evaluated the performance of different $\lambda$, representing the influence of CC-Loss. The best result is obtained when $\lambda$ is $1$. Further increasing $\lambda$ will cause performance drop because we need class-label relationship provided by the CE-Loss. \subsection{Hyper-parameter tuning on batch size} Since we optimize the channel attention distances within mini-batchs, the batch size is an important hyper-parameter to be tuned. We analyzed the affect of batch size on CIFAR-$100$ and Cars-$196$ datasets with VGG$16$ as the backbone. As shown in Table~\ref{tab:batchsize}, a smaller batch size leads to a higher classification accuracy, since the class relationship in the distance matrix is simpler and easier to optimize. However, when the batch size tends to be very small, the class relationship will disappear and thus the accuracy is decreased. Therefore, we empirically chose a batch size of $32$ for the CIFAR-$100$ dataset and a batch size of $16$ for the Cars-$196$ dataset. \vspace{-2mm} \subsection{Statistical significance analysis} As the number of experiments is less than $30$, we used the one sample unpaired $t$-test~\cite{posten1979robustness} to evaluate the statistical significance of the results. We took the values from the state-of-the-art method as the general average value for test. More specifically, we used the results from the A-softmax Loss for Cars-$196$ dataset on VGG$16$ backbone and the results from the FICAL Loss for the rest. As shown in Table~\ref{tab:t-rest}, all the $p$-values of the one sample $t$-test with SOTA results are below $5\times10^{-3}$, which indicates statistically significant improvements obtained by the CC-Loss compared with the baseline loss functions. \vspace{-2mm} \subsection{Visualization} We carry out the visualization experiments by training VGG$16$ on the MNIST dataset. The output dimensionality of the first linear layer in VGG$16$ was set to $2$. The features extracted from the first linear layer are visualized to present the feature space obtained by the CE-Loss and the CC-Loss. From Fig.~\ref{fig:vis}, it can be observed that the features from the CC-Loss are more compact within the same class while more separable among the neighbour classes. This demonstrates the effectiveness of intra-class and inter-class component of CC-Loss. \vspace{-4mm} \section{Conclusions} In this paper, we proposed a new loss function, namely the Channel Correlation Loss (CC-Loss), for the task of image classification. The CC-Loss dynamically selects the CNN channels for each class via the channel attention mechanism. It assigns larger numbers of channels to the harder classes and smaller numbers of channels to the easier class. Furthermore, by considering the Euclidean distances of the channel attention vectors in mini-batches, the CC-Loss is able to maximize both the intra-class compactness and the inter-class separability, which can extract more discriminative features. Experimental results on three datasets with two different backbones demonstrated that the proposed method outperforms commonly used loss functions. \bibliographystyle{IEEEbib}
{'timestamp': '2020-10-13T02:29:02', 'yymm': '2010', 'arxiv_id': '2010.05469', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05469'}
arxiv
\section{Copyright} All papers submitted for publication by AAAI Press must be accompanied by a valid signed copyright form or, in the case of technical reports, by a valid signed permission to distribute form. There are no exceptions to this requirement. You must send us the original version of this form. However, to meet the deadline, you may fax (1-650-321-4457) or scan and e-mail the form ([email protected]) to AAAI by the submission deadline, and then mail the original via postal mail to the AAAI office. \textbf{If you fail to send in a signed copyright or permission form, your paper will not be published.} You will find PDF versions of the AAAI copyright and permission to distribute forms in the author kit. \section{Formatting Requirements in Brief} We need source and PDF files that can be used in a variety of ways and can be output on a variety of devices. AAAI imposes some requirements on your source and PDF files that must be followed. Most of these requirements are based on our efforts to standardize conference manuscript properties and layout. These requirements are as follows, and all papers submitted to AAAI for publication must comply: \begin{itemize} \item Your .tex file must compile in PDF\LaTeX{} --- \textbf{ no .ps or .eps figure files.} \item All fonts must be embedded in the PDF file --- \textbf{ this includes your figures.} \item Modifications to the style sheet (or your document) in an effort to avoid extra page charges are NOT allowed. \item No type 3 fonts may be used (even in illustrations). \item Your title must follow US capitalization rules. \item \LaTeX{} documents must use the Times or Nimbus font package (do not use Computer Modern for the text of your paper). \item No \LaTeX{} 209 documents may be used or submitted. \item Fonts that require non-English language support (CID and Identity-H) must be converted to outlines or removed from the document (even if they are in a graphics file embedded in the document). \item Two-column format in AAAI style is required for all papers. \item The paper size for final submission must be US letter. No exceptions. \item The source file must exactly match the PDF. \item The document margins must be as specified in the formatting instructions. \item The number of pages and the file size must be as specified for your event. \item No document may be password protected. \item Neither the PDFs nor the source may contain any embedded links or bookmarks. \item Your source and PDF must not have any page numbers, footers, or headers. \item Your PDF must be compatible with Acrobat 5 or higher. \item Your \LaTeX{} source file (excluding references) must consist of a \textbf{single} file (use of the ``input" command is not allowed. \item Your graphics must be sized appropriately outside of \LaTeX{} (do not use the ``clip" command) . \end{itemize} If you do not follow the above requirements, it is likely that we will be unable to publish your paper. \section{What Files to Submit} You must submit the following items to ensure that your paper is published: \begin{itemize} \item A fully-compliant PDF file. \item Your \LaTeX{} source file submitted as a \textbf{single} .tex file (do not use the ``input" command to include sections of your paper --- every section must be in the single source file). The only exception is the bibliography, which you may include separately. Your source must compile on our system, which includes the standard \LaTeX{} support files. \item All your graphics files. \item The \LaTeX{}-generated files (e.g. .aux and .bib file, etc.) for your compiled source. \item All the nonstandard style files (ones not commonly found in standard \LaTeX{} installations) used in your document (including, for example, old algorithm style files). If in doubt, include it. \end{itemize} Your \LaTeX{} source will be reviewed and recompiled on our system (if it does not compile, you may incur late fees). \textbf{Do not submit your source in multiple text files.} Your single \LaTeX{} source file must include all your text, your bibliography (formatted using aaai.bst), and any custom macros. Accompanying this source file, you must also supply any nonstandard (or older) referenced style files and all your referenced graphics files. Your files should work without any supporting files (other than the program itself) on any computer with a standard \LaTeX{} distribution. Place your PDF and source files in a single tar, zipped, gzipped, stuffed, or compressed archive. Name your source file with your last (family) name. \textbf{Do not send files that are not actually used in the paper.} We don't want you to send us any files not needed for compiling your paper, including, for example, this instructions file, unused graphics files, and so forth. A shell script (created by an AAAI member --- it might not work without modification on your system) that might help you create the \LaTeX{} source package is included in the Author Kit. \section{Using \LaTeX{} to Format Your Paper} The latest version of the AAAI style file is available on AAAI's website. Download this file and place it in a file named ``aaai.sty" in the \TeX\ search path. Placing it in the same directory as the paper should also work. You must download the latest version of the complete author kit so that you will have the latest instruction set. \subsection{Document Preamble} In the \LaTeX{} source for your paper, you \textbf{must} place the following lines as shown in the example in this subsection. This command set-up is for three authors. Add or subtract author and address lines as necessary, and uncomment the portions that apply to you. In most instances, this is all you need to do to format your paper in the Times font. The helvet package will cause Helvetica to be used for sans serif, and the courier package will cause Courier to be used for the typewriter font. These files are part of the PSNFSS2e package, which is freely available from many Internet sites (and is often part of a standard installation). Leave the setcounter for section number depth commented out and set at 0 unless you want to add section numbers to your paper. If you do add section numbers, you must uncomment this line and change the number to 1 (for section numbers), or 2 (for section and subsection numbers). The style file will not work properly with numbering of subsubsections, so do not use a number higher than 2. \begin{quote} \begin{small} \textbackslash documentclass[letterpaper]{article}\\ \% \textit{Required Packages}\\ \textbackslash usepackage\{aaai\}\\ \textbackslash usepackage\{times\}\\ \textbackslash usepackage\{helvet\}\\ \textbackslash usepackage\{courier\}\\ \textbackslash setlength\{\textbackslash pdfpagewidth\}\{8.5in\} \textbackslash setlength\{\textbackslash pdfpageheight\}\{11in\}\\ \%\%\%\%\%\%\%\%\%\%\\ \% \textit{PDFINFO for PDF\LaTeX{}}\\ \% Uncomment and complete the following for metadata (your paper must compile with PDF\LaTeX{})\\ \textbackslash pdfinfo\{\\ /Title (Input Your Paper Title Here)\\ /Author (John Doe, Jane Doe)\\ /Keywords (Input your paper's keywords in this optional area)\\ \}\\ \%\%\%\%\%\%\%\%\%\%\\ \% \textit{Section Numbers}\\ \% Uncomment if you want to use section numbers\\ \% and change the 0 to a 1 or 2\\ \% \textbackslash setcounter\{secnumdepth\}\{0\}\\ \%\%\%\%\%\%\%\%\%\%\\ \% \textit{Title, Author, and Address Information}\\ \textbackslash title\{Title\}\\ \textbackslash author\{Author 1 \textbackslash and Author 2\textbackslash\textbackslash \\ Address line\textbackslash\textbackslash\\ Address line\textbackslash\textbackslash \\ \textbackslash And\\ Author 3\textbackslash\textbackslash\\ Address line\textbackslash\textbackslash\\ Address line\}\\ \%\%\%\%\%\%\%\%\%\%\\ \% \textit{Body of Paper Begins}\\ \textbackslash begin\{document\}\\ \textbackslash maketitle\\ ...\\ \%\%\%\%\%\%\%\%\%\%\\ \% \textit{References and End of Paper}\\ \textbackslash bibliography\{Bibliography-File\}\\ \textbackslash bibliographystyle\{aaai\}\\ \textbackslash end\{document\} \end{small} \end{quote} \subsection{Inserting Document Metadata with \LaTeX{}} PDF files contain document summary information that enables us to create an Acrobat index (pdx) file, and also allows search engines to locate and present your paper more accurately. \textbf{Document Metadata for Author and Title are REQUIRED.} If your paper includes illustrations that are not compatible with PDF\TeX{} (such as .eps or .ps documents), you will need to convert them. The epstopdf package will usually work for eps files. You will need to convert your ps files to PDF however. \textit{Important:} Do not include \textit{any} \LaTeX{} code or nonascii characters (including accented characters) in the metadata. The data in the metadata must be completely plain ascii. It may not include slashes, accents, linebreaks, unicode, or any \LaTeX{} commands. Type the title exactly as it appears on the paper (minus all formatting). Input the author names in the order in which they appear on the paper (minus all accents), separating each author by a comma. You may also include keywords in the Keywords field. \subsection{Preparing Your Paper} After the preamble above, you should prepare your paper as follows: \begin{quote} \begin{small} \textbackslash begin\{document\}\\ \textbackslash maketitle\\ ...\\ \textbackslash bibliography\{Bibliography-File\}\\ \textbackslash bibliographystyle\{aaai\}\\ \textbackslash end\{document\}\\ \end{small} \end{quote} \subsection{Incompatible Packages} The following packages are incompatible with aaai.sty and/or aaai.bst and must not be used (this list is not exhaustive --- there are others as well): \begin{itemize} \item hyperref \item natbib \item geometry \item titlesec \item layout \item caption \item titlesec \item T1 fontenc package (install the CM super fonts package instead) \end{itemize} \subsection{Illegal Commands} The following commands may not be used in your paper: \begin{itemize} \item \textbackslash input \item \textbackslash vspace (when used before or after a section or subsection) \item \textbackslash addtolength \item \textbackslash columnsep \item \textbackslash top margin (or text height or addsidemargin or even side margin) \end{itemize} \subsection{Paper Size, Margins, and Column Width} Papers must be formatted to print in two-column format on 8.5 x 11 inch US letter-sized paper. The margins must be exactly as follows: \begin{itemize} \item Top margin: .75 inches \item Left margin: .75 inches \item Right margin: .75 inches \item Bottom margin: 1.25 inches \end{itemize} The default paper size in most installations of \LaTeX{} is A4. However, because we require that your electronic paper be formatted in US letter size, you will need to alter the default for this paper to US letter size. Assuming you are using the 2e version of \LaTeX{}, you can do this by including the [letterpaper] option at the beginning of your file: \textbackslash documentclass[letterpaper]{article}. This command is usually sufficient to change the format. Sometimes, however, it may not work. Use PDF\LaTeX{} and include \textbackslash setlength\{\textbackslash pdfpagewidth\}\{8.5in\} \textbackslash setlength\{\textbackslash pdfpageheight\}\{11in\} in your preamble. \textbf{Do not use the Geometry package to alter the page size.} Use of this style file alters aaai.sty and will result in your paper being rejected. \subsubsection{Column Width and Margins.} To ensure maximum readability, your paper must include two columns. Each column should be 3.3 inches wide (slightly more than 3.25 inches), with a .375 inch (.952 cm) gutter of white space between the two columns. The aaai.sty file will automatically create these columns for you. \subsection{Overlength Papers} If your paper is too long, turn on \textbackslash frenchspacing, which will reduce the space after periods. Next, shrink the size of your graphics. Use \textbackslash centering instead of \textbackslash begin\{center\} in your figure environment. If these two methods don't work, you may minimally use the following. For floats (tables and figures), you may minimally reduce \textbackslash floatsep, \textbackslash textfloatsep, \textbackslash abovecaptionskip, and \textbackslash belowcaptionskip. For mathematical environments, you may minimally reduce \textbackslash abovedisplayskip, \textbackslash belowdisplayskip, and \textbackslash arraycolsep. You may also alter the size of your bibliography by inserting \textbackslash fontsize\{9.5pt\}\{10.5pt\} \textbackslash selectfont right before the bibliography. Commands that alter page layout are forbidden. These include \textbackslash columnsep, \textbackslash topmargin, \textbackslash topskip, \textbackslash textheight, \textbackslash textwidth, \textbackslash oddsidemargin, and \textbackslash evensizemargin (this list is not exhaustive). If you alter page layout, you will be required to pay the page fee \textit{plus} a reformatting fee. Other commands that are questionable and may cause your paper to be rejected include \textbackslash parindent, and \textbackslash parskip. Commands that alter the space between sections are also questionable. The title sec package is not allowed. Regardless of the above, if your paper is obviously ``squeezed" it is not going to to be accepted. Before using every trick you know to make your paper a certain length, try reducing the size of your graphics or cutting text instead or (if allowed) paying the extra page charge. It will be cheaper in the long run. \subsection{Figures} Your paper must compile in PDF\LaTeX{}. Consequently, all your figures must be .jpg, .png, or .pdf. You may not use the .gif (the resolution is too low), .ps, or .eps file format for your figures. When you include your figures, you must crop them \textbf{outside} of \LaTeX{}. The command \textbackslash includegraphics*[clip=true, viewport 0 0 10 10]{...} might result in a PDF that looks great, but the image is \textbf{not really cropped.} The full image can reappear when page numbers are applied or color space is standardized. \subsection{Type Font and Size} Your paper must be formatted in Times Roman or Nimbus. We will not accept papers formatted using Computer Modern or Palatino or some other font as the text or heading typeface. Sans serif, when used, should be Courier. Use Symbol or Lucida or Computer Modern for \textit{mathematics only. } Do not use type 3 fonts for any portion of your paper, including graphics. Type 3 bitmapped fonts are designed for fixed resolution printers. Most print at 300 dpi even if the printer resolution is 1200 dpi or higher. They also often cause high resolution imagesetter devices and our PDF indexing software to crash. Consequently, AAAI will not accept electronic files containing obsolete type 3 fonts. Files containing those fonts (even in graphics) will be rejected. Fortunately, there are effective workarounds that will prevent your file from embedding type 3 bitmapped fonts. The easiest workaround is to use the required times, helvet, and courier packages with \LaTeX{}2e. (Note that papers formatted in this way will still use Computer Modern for the mathematics. To make the math look good, you'll either have to use Symbol or Lucida, or you will need to install type 1 Computer Modern fonts --- for more on these fonts, see the section ``Obtaining Type 1 Computer Modern.") If you are unsure if your paper contains type 3 fonts, view the PDF in Acrobat Reader. The Properties/Fonts window will display the font name, font type, and encoding properties of all the fonts in the document. If you are unsure if your graphics contain type 3 fonts (and they are PostScript or encapsulated PostScript documents), create PDF versions of them, and consult the properties window in Acrobat Reader. The default size for your type should be ten-point with twelve-point leading (line spacing). Start all pages (except the first) directly under the top margin. (See the next section for instructions on formatting the title page.) Indent ten points when beginning a new paragraph, unless the paragraph begins directly below a heading or subheading. \subsubsection{Obtaining Type 1 Computer Modern for \LaTeX{}.} If you use Computer Modern for the mathematics in your paper (you cannot use it for the text) you may need to download type 1 Computer fonts. They are available without charge from the American Mathematical Society: http://www.ams.org/tex/type1-fonts.html. \subsection{Title and Authors} Your title must appear in mixed case (nouns, pronouns, and verbs are capitalized) near the top of the first page, centered over both columns in sixteen-point bold type (twenty-four point leading). This style is called ``mixed case." Author's names should appear below the title of the paper, centered in twelve-point type (with fifteen point leading), along with affiliation(s) and complete address(es) (including electronic mail address if available) in nine-point roman type (the twelve point leading). (If the title is long, or you have many authors, you may reduce the specified point sizes by up to two points.) You should begin the two-column format when you come to the abstract. \subsubsection{Formatting Author Information} Author information can be set in a number of different styles, depending on the number of authors and the number of affiliations you need to display. For several authors from the same institution, use \textbackslash and: \begin{quote} \begin{small} \textbackslash author\{Author 1 \textbackslash and ... \textbackslash and Author \textit{n}\textbackslash \textbackslash \\ Address line \textbackslash \textbackslash ~... \textbackslash \textbackslash ~Address line\} \end{small} \end{quote} \noindent If the names do not fit well on one line use: \begin{quote} \begin{small} \textbackslash author\{Author 1\}\textbackslash \textbackslash \\ \{\textbackslash bf Author 2\}\textbackslash \textbackslash ~ ... \textbackslash \textbackslash ~\{\textbackslash bf Author \textit{n}\}\textbackslash \textbackslash \\ Address line \textbackslash \textbackslash ~ ... \textbackslash \textbackslash ~ Address line\} \end{small} \end{quote} \noindent For authors from different institutions, use \textbackslash And: \begin{quote} \begin{small} \textbackslash author\{Author 1\textbackslash \textbackslash ~ Address line \textbackslash \textbackslash ~... \textbackslash \textbackslash ~ Address line \textbackslash And ... \textbackslash And Author \textit{n}\textbackslash \textbackslash \\ Address line\textbackslash \textbackslash ~ ... \textbackslash \textbackslash ~ Address line\} \end{small} \end{quote} \noindent To start a separate ``row" of authors, use \textbackslash AND: \begin{quote} \begin{small} \textbackslash author\{Author 1\textbackslash\textbackslash ~ Address line \textbackslash\textbackslash ~ ... \textbackslash \textbackslash ~ Address line\textbackslash\textbackslash \\ \textbackslash AND\\ Author 2 \textbackslash\textbackslash ~ Address line \textbackslash\textbackslash ~ ... \textbackslash \textbackslash ~ Address line\textbackslash\textbackslash \\ \textbackslash And\\ Author 3 \textbackslash\textbackslash ~ Address line \textbackslash\textbackslash ~ ... \textbackslash \textbackslash ~ Address line\textbackslash\textbackslash \\\} \end{small} \end{quote} \noindent If the title and author information does not fit in the area allocated, place \textbackslash setlength\textbackslash titlebox\{\textit{height}\} after the \textbackslash documentclass line where \{\textit{height}\} is something like 2.5in. \subsection{\LaTeX{} Copyright Notice} The copyright notice automatically appears if you use aaai.sty. If you are creating a technical report, it is not necessary to include this notice. You may disable the copyright line using the \verb+\+nocopyrightcommand. To change the entire text of the copyright slug, use: \textbackslash copyrighttext \{\emph{text}\}. Either of these must appear before \textbackslash maketitle. Please be advised, however, that \textit{if you disable or change the copyright line and transfer of copyright is required, your paper will not be published.} \subsection{Credits} Any credits to a sponsoring agency should appear in the acknowledgments section, unless the agency requires different placement. If it is necessary to include this information on the front page, use \textbackslash thanks in either the \textbackslash author or \textbackslash title commands. For example: \begin{quote} \begin{small} \textbackslash title\{Very Important Results in AI\textbackslash thanks\{This work is supported by everybody.\}\} \end{small} \end{quote} Multiple \textbackslash thanks commands can be given. Each will result in a separate footnote indication in the author or title with the corresponding text at the botton of the first column of the document. Note that the \textbackslash thanks command is fragile. You will need to use \textbackslash protect. Please do not include \textbackslash pubnote commands in your document. \subsection{Abstract} The abstract must be placed at the beginning of the first column, indented ten points from the left and right margins. The title ÒAbstractÓ should appear in ten-point bold type, centered above the body of the abstract. The abstract should be set in nine-point type with ten-point leading. This concise, one-paragraph summary should describe the general thesis and conclusion of your paper. A reader should be able to learn the purpose of the paper and the reason for its importance from the abstract. The abstract should be no more than two hundred words in length. (Authors who are submitting short one- or two-page extended extracts should provide a short abstract of only a sentence or so.) \textbf{Do not include references in your abstract!} \subsection{Page Numbers} Do not \textbf{ever} print any page numbers on your paper. \subsection{Text } The main body of the paper must be formatted in ten-point with twelve-point leading (line spacing). \subsection{Citations} Citations within the text should include the author's last name and year, for example (Newell 1980). Append lower-case letters to the year in cases of ambiguity. Multiple authors should be treated as follows: (Feigenbaum and Engelmore 1988) or (Ford, Hayes, and Glymour 1992). In the case of four or more authors, list only the first author, followed by et al. (Ford et al. 1997). \subsection{Extracts} Long quotations and extracts should be indented ten points from the left and right margins. \begin{quote} This is an example of an extract or quotation. Note the indent on both sides. Quotation marks are not necessary if you offset the text in a block like this, and properly identify and cite the quotation in the text. \end{quote} \subsection{Footnotes} Avoid footnotes as much as possible; they interrupt the reading of the text. When essential, they should be consecutively numbered throughout with superscript Arabic numbers. Footnotes should appear at the bottom of the page, separated from the text by a blank line space and a thin, half-point rule. \subsection{Headings and Sections} When necessary, headings should be used to separate major sections of your paper. Remember, you are writing a short paper, not a lengthy book! An overabundance of headings will tend to make your paper look more like an outline than a paper. First-level heads should be twelve-point Times Roman bold type, mixed case (initial capitals followed by lower case on all words except articles, conjunctions, and prepositions, which should appear entirely in lower case), with fifteen-point leading, centered, with one blank line preceding them and three additional points of leading following them. Second-level headings should be eleven-point Times Roman bold type, mixed case, with thirteen-point leading, flush left, with one blank line preceding them and three additional points of leading following them. Do not skip a line between paragraphs. Third-level headings should be run in with the text, ten-point Times Roman bold type, mixed case, with twelve-point leading, flush left, with six points of additional space preceding them and no additional points of leading following them. \subsubsection{Section Numbers} The use of section numbers in AAAI Press papers is optional. To use section numbers in \LaTeX{}, uncomment the setcounter line in your document preamble and change the 0 to a 1 or 2. Section numbers should not be used in short poster papers. \subsubsection{Section Headings.} Sections should be arranged and headed as follows: \subsubsection{Acknowledgments.} The acknowledgments section, if included, appears after the main body of text and is headed ``Acknowledgments." This section includes acknowledgments of help from associates and colleagues, credits to sponsoring agencies, financial support, and permission to publish. Please acknowledge other contributors, grant support, and so forth, in this section. Do not put acknowledgments in a footnote on the first page. If your grant agency requires acknowledgment of the grant on page 1, limit the footnote to the required statement, and put the remaining acknowledgments at the back. Please try to limit acknowledgments to no more than three sentences. \subsubsection{Appendices.} Any appendices follow the acknowledgments, if included, or after the main body of text if no acknowledgments appear. \subsubsection{References} The references section should be labeled ``References" and should appear at the very end of the paper (don't end the paper with references, and then put a figure by itself on the last page). A sample list of references is given later on in these instructions. Please use a consistent format for references. Poorly prepared or sloppy references reflect badly on the quality of your paper and your research. Please prepare complete and accurate citations. \subsection{Illustrations and Figures} Figures, drawings, tables, and photographs should be placed throughout the paper near the place where they are first discussed. Do not group them together at the end of the paper. If placed at the top or bottom of the paper, illustrations may run across both columns. Figures must not invade the top, bottom, or side margin areas. Figures must be inserted using the \textbackslash usepackage\{graphicx\}. Number figures sequentially, for example, figure 1, and so on. The illustration number and caption should appear under the illustration. Labels, and other text in illustrations must be at least nine-point type. \subsubsection{Low-Resolution Bitmaps.} You may not use low-resolution (such as 72 dpi) screen-dumps and GIF files---these files contain so few pixels that they are always blurry, and illegible when printed. If they are color, they will become an indecipherable mess when converted to black and white. This is always the case with gif files, which should never be used. The resolution of screen dumps can be increased by reducing the print size of the original file while retaining the same number of pixels. You can also enlarge files by manipulating them in software such as PhotoShop. Your figures should be a minimum of 266 dpi when incorporated into your document. \subsubsection{\LaTeX{} Overflow.} \LaTeX{} users please beware: \LaTeX{} will sometimes put portions of the figure or table or an equation in the margin. If this happens, you need to scale the figure or table down, or reformat the equation. Check your log file! You must fix any overflow into the margin (that means no overfull boxes in \LaTeX{}). If you don't, the overflow text will simply be eliminated. \textbf{Nothing is permitted to intrude into the margins.} \subsubsection{Using Color.} Your paper will be printed in black and white and grayscale. Consequently, because conversion to grayscale can cause undesirable effects (red changes to black, yellow can disappear, and so forth), we strongly suggest you avoid placing color figures in your document. Of course, any reference to color will be indecipherable to your reader. \subsubsection{Drawings.} We suggest you use computer drawing software (such as Adobe Illustrator or, (if unavoidable), the drawing tools in Microsoft Word) to create your illustrations. Do not use Microsoft Publisher. These illustrations will look best if all line widths are uniform (half- to two-point in size), and you do not create labels over shaded areas. Shading should be 133 lines per inch if possible. Use Times Roman or Helvetica for all figure call-outs. \textbf{Do not use hairline width lines} --- be sure that the stroke width of all lines is at least .5 pt. Zero point lines will print on a laser printer, but will completely disappear on the high-resolution devices used by our printers. \subsubsection{Photographs and Images.} Photographs and other images should be in grayscale (color photographs will not reproduce well; for example, red tones will reproduce as black, yellow may turn to white, and so forth) and set to a minimum of 266 dpi. Do not prescreen images. \subsubsection{Resizing Graphics.} Resize your graphics \textbf{before} you include them with LaTeX. You may \textbf{not} use trim or clip options as part of your \textbackslash includgraphics command. Resize the media box of your PDF using a graphics program instead. \subsubsection{Fonts in Your Illustrations} You must embed all fonts in your graphics before including them in your LaTeX document. \subsection{References} The aaai.sty file includes a set of definitions for use in formatting references with BibTeX. These definitions make the bibliography style fairly close to the one specified below. To use these definitions, you also need the BibTeX style file ``aaai.bst," available in the author kit on the AAAI web site. Then, at the end of your paper but before \textbackslash end{document}, you need to put the following lines: \begin{quote} \begin{small} \textbackslash bibliographystyle\{aaai\} \textbackslash bibliography\{bibfile1,bibfile2,...\} \end{small} \end{quote} The list of files in the \textbackslash bibliography command should be the names of your BibTeX source files (that is, the .bib files referenced in your paper). The following commands are available for your use in citing references: \begin{quote} \begin{small} \textbackslash cite: Cites the given reference(s) with a full citation. This appears as ``(Author Year)'' for one reference, or ``(Author Year; Author Year)'' for multiple references.\\ \textbackslash shortcite: Cites the given reference(s) with just the year. This appears as ``(Year)'' for one reference, or ``(Year; Year)'' for multiple references.\\ \textbackslash citeauthor: Cites the given reference(s) with just the author name(s) and no parentheses.\\ \textbackslash citeyear: Cites the given reference(s) with just the date(s) and no parentheses. \end{small} \end{quote} \textbf{Warning:} The aaai.sty file is incompatible with the hyperref and natbib packages. If you use either, your references will be garbled. Formatted bibliographies should look like the following examples. \smallskip \noindent \textit{Book with Multiple Authors}\\ Engelmore, R., and Morgan, A. eds. 1986. \textit{Blackboard Systems.} Reading, Mass.: Addison-Wesley. \smallskip \noindent \textit{Journal Article}\\ Robinson, A. L. 1980a. New Ways to Make Microcircuits Smaller. \textit{Science} 208: 1019--1026. \smallskip \noindent \textit{Magazine Article}\\ Hasling, D. W.; Clancey, W. J.; and Rennels, G. R. 1983. Strategic Explanations in Consultation. \textit{The International Journal of Man-Machine Studies} 20(1): 3--19. \smallskip \noindent \textit{Proceedings Paper Published by a Society}\\ Clancey, W. J. 1983b. Communication, Simulation, and Intelligent Agents: Implications of Personal Intelligent Machines for Medical Education. In Proceedings of the Eighth International Joint Conference on Artificial Intelligence, 556--560. Menlo Park, Calif.: International Joint Conferences on Artificial Intelligence, Inc. \smallskip \noindent \textit{Proceedings Paper Published by a Press or Publisher}\\ Clancey, W. J. 1984. Classification Problem Solving. In \textit{Proceedings of the Fourth National Conference on Artificial Intelligence,} 49--54. Menlo Park, Calif.: AAAI Press. \smallskip \noindent \textit{University Technical Report}\\ Rice, J. 1986. Poligon: A System for Parallel Problem Solving, Technical Report, KSL-86-19, Dept. of Computer Science, Stanford Univ. \smallskip \noindent \textit{Dissertation or Thesis}\\ Clancey, W. J. 1979b. Transfer of Rule-Based Expertise through a Tutorial Dialogue. Ph.D. diss., Dept. of Computer Science, Stanford Univ., Stanford, Calif. \smallskip \noindent \textit{Forthcoming Publication}\\ Clancey, W. J. 1986a. The Engineering of Qualitative Models. Forthcoming. \section{Producing Reliable PDF\\Documents with \LaTeX{}} Generally speaking, PDF files are platform independent and accessible to everyone. When creating a paper for a proceedings or publication in which many PDF documents must be merged and then printed on high-resolution PostScript RIPs, several requirements must be met that are not normally of concern. Thus to ensure that your paper will look like it does when printed on your own machine, you must take several precautions: \begin{itemize} \item Use type 1 fonts (not type 3 fonts) \item Use only standard Times, Nimbus, and CMR font packages (not fonts like F3 or fonts with tildes in the names or fonts---other than Computer Modern---that are created for specific point sizes, like Times\~{}19) or fonts with strange combinations of numbers and letters \item Embed all fonts when producing the PDF \item Do not use the [T1]{fontenc} package (install the CM super fonts package instead) \end{itemize} \subsection{Creating Output Using PDF\LaTeX{} Is Required} By using the PDF\TeX{} program instead of straight \LaTeX{} or \TeX{}, you will probably avoid the type 3 font problem altogether (unless you use a package that calls for metafont). PDF\LaTeX{} enables you to create a PDF document directly from \LaTeX{} source. The one requirement of this software is that all your graphics and images must be available in a format that PDF\LaTeX{} understands (normally PDF). PDF\LaTeX{}'s default is to create documents with type 1 fonts. If you find that it is not doing so in your case, it is likely that one or more fonts are missing from your system or are not in a path that is known to PDF\LaTeX{}. \subsubsection{dvipdf Script} Scripts such as dvipdf which ostensibly bypass the Postscript intermediary should not be used since they generally do not instruct dvips to use the config.pdf file. \subsubsection{dvipdfm} Do not use this dvi-PDF conversion package if your document contains graphics (and we recommend you avoid it even if your document does not contain graphics). \subsection{Ghostscript} \LaTeX{} users should not use GhostScript to create their PDFs. \subsection{Graphics} If you are still finding type 3 fonts in your PDF file, look at your graphics! \LaTeX{} users should check all their imported graphics files as well for font problems. \section{Proofreading Your PDF} Please check all the pages of your PDF file. Is the page size A4? Are there any type 3, Identity-H, or CID fonts? Are all the fonts embedded? Are there any areas where equations or figures run into the margins? Did you include all your figures? Did you follow mixed case capitalization rules for your title? Did you include a copyright notice? Do any of the pages scroll slowly (because the graphics draw slowly on the page)? Are URLs underlined and in color? You will need to fix these common errors before submitting your file. \section{Improperly Formatted Files } In the past, AAAI has corrected improperly formatted files submitted by the authors. Unfortunately, this has become an increasingly burdensome expense that we can no longer absorb. Consequently, if your file is improperly formatted, it may not be possible to include your paper in the publication. If time allows, however, you will be notified via e-mail (with a copy to the program chair) of the problems with your file and given the option of correcting the file yourself (and paying a late fee) or asking that AAAI have the file corrected for you, for an additional fee. If you opt to correct the file yourself, please note that we cannot provide you with any additional advice beyond that given in your packet. Files that are not corrected after a second attempt will be withdrawn. \subsection{\LaTeX{} 209 Warning} If you use \LaTeX{} 209 we will not be able to publish your paper. Convert your paper to \LaTeX{}2e. \section{Naming Your Electronic File} We request that you name your \LaTeX{} source file with your last name (family name) so that it can easily be differentiated from other submissions. If you name your files with the name of the event or ``aaai" or ``paper" or ``camera-ready" or some other generic or indecipherable name, you bear all risks of loss --- it is extremely likely that your file may be overwritten. \section{Submitting Your Electronic Files to AAAI} Submitting your files to AAAI is a two-step process. It is explained fully in the author registration and submission instructions. Please consult this document for details on how to submit your paper. \section{Inquiries} If you have any questions about the preparation or submission of your paper as instructed in this document, please contact AAAI Press at the address given below. If you have technical questions about implementation of the aaai style file, please contact an expert at your site. We do not provide technical support for \LaTeX{} or any other software package. To avoid problems, please keep your paper simple, and do not incorporate complicated macros and style files. \begin{quote} \noindent AAAI Press\\ 2275 East Bayshore Road, Suite 160\\ Palo Alto, California 94303\\ \textit{Telephone:} (650) 328-3123\\ \textit{E-mail:} See the submission instructions for your particular conference or event. \end{quote} \section{Additional Resources} \LaTeX{} is a difficult program to master. If you've used that software, and this document didn't help or some items were not explained clearly, we recommend you read Michael Shell's excellent document (testflow doc.txt V1.0a 2002/08/13) about obtaining correct PS/PDF output on \LaTeX{} systems. (It was written for another purpose, but it has general application as well). It is available at www.ctan.org in the tex-archive. \section{ Acknowledgments} AAAI is especially grateful to Peter Patel Schneider for his work in implementing the aaai.sty file, liberally using the ideas of other style hackers, including Barbara Beeton. We also acknowledge with thanks the work of George Ferguson for his guide to using the style and BibTeX files --- which has been incorporated into this document --- and Hans Guesgen, who provided several timely modifications, as well as the many others who have, from time to time, sent in suggestions on improvements to the AAAI style. The preparation of the \LaTeX{} and Bib\TeX{} files that implement these instructions was supported by Schlumberger Palo Alto Research, AT\&T Bell Laboratories, Morgan Kaufmann Publishers, The Live Oak Press, LLC, and AAAI Press. Bibliography style changes were added by Sunil Issar. \verb+\+pubnote was added by J. Scott Penberthy. George Ferguson added support for printing the AAAI copyright slug. Additional changes to aaai.sty and aaai.bst have been made by the AAAI staff. \bigskip \noindent Thank you for reading these instructions carefully. We look forward to receiving your electronic files! \end{document} \section{Introduction} Consider the problem of an epidemic spreading in the population, without any known cure or vaccination procedure. To contain the disease and prevent it from spreading, it becomes critical to detect infected carriers and isolate them; see Fig.~\ref{fig:viralinfection} for an illustration. As the epidemic spreads, the demand for tests outgrows their availability, and not all potential carriers can be tested. It becomes necessary to identify the most likely epidemic carriers using limited testing resources. This raises a major question: How can we rank candidates and prioritize testing to prevent the disease from spreading? This prioritization problem is an important example of a family of problems: learning to control diffusive processes over networks through nodal interventions. Other examples include opinions spreading on social network, product adaption, viruses inflicting computer networks and cascades of failures in server farms. In all these cases, the dynamics of the system can be steered using interventions that modify the states of a (relatively) small number of nodes. For instance, infected people can be asked to self-quarantine, preventing the spread of a disease, at-risk computers can be patched by security updates, and users may be selected and be exposed to new information to influence their opinion. \begin{figure}[t] \centering \includegraphics[width=0.8\columnwidth]{figs/RL_graphs_fig1_trimmed.png} \caption{A viral infection process on a graph and an intervention aimed to stop its spread. Here, graph nodes represent people and edges represent interactions. At $t=1$ only two people are infected (red). At $t=2$ several interactions resulted in new \textit{exposed} people (yellow); At $t=3$ the blue node was selected to be quarantined to stop the viral spread. This paper presents a framework for learning how to select which nodes should be quarantined. }\label{fig:viralinfection} \end{figure} The problem of controlling the dynamics of a system using localized interventions is very hard, and for several reasons. First, it requires to make decision in a continuously changing environment with complex dependencies. Second, to solve the problem one must assess the potential downstream ripple effect for any specific node that becomes infected, and balance it with the probability that the node indeed becomes infected. Finally, models must handle noise and partial observability. We pose the problem of controlling a diffusive process on a temporally evolving graph as a sequential decision making problem in the context of a partially-observed Markov decision process. We then formulate the problem of selecting a subset of nodes for dynamical intervention as a {\em ranking } problem, and design an actor-critic RL algorithm to solve it. We use the observed changes of nodes states and connections to construct a temporal multi-graph, which has time-stamped interactions over edges, and describe a deep architecture based on GNNs to process it. To the best of our knowledge, this work is the first work that consider Deep RL in the context of a temporally evolving graph. The current work combines three research fields: dynamic processes on temporal graphs, deep graph learning and reinforcement learning. Combining these three into a cohesive model raises several new challenges. Most importantly, the model must learn to handle two types of dynamics: learn to infer the potential risk of not removing a node, and learn to predict the probability that a node becomes infected. As explained below, these two processes operate on different time scales. To address this issue, our architecture contains two separate GNN modules, taking as input a multi-graph over the nodes, where edges are time-stamped with the time of interactions. Also, we show below that combining RL with temporal graphs requires to stabilize how information is aggregated from neighbors when updating nodes hidden states, and control how actions are sampled during training to ensure sufficient exploration. We show empirically the beneficial effects of these components. This paper demonstrates that combining RL with GNNs provides a powerful approach for controlling spreading processes on graphs. In the context of COVID-19 spread, we show that using the RL-GNN approach increases the fraction of healthy by $25\%$ \gal{revise} and allows for confining the spread of an epidemic $30\%$ more often, and $3\times$ times more often that using non-learned approaches. ~\newline This paper makes the following contributions:\\ {\bf (1)}~A new framework for controlling the dynamics of diffusive processes over graphs. Namely, learning to perform local interventions to steer the global dynamics of a graph-based dynamical system. \\ {\bf (2)}~A new architecture for this problem, and a way to train a decision-making agent using reinforcement learning to prioritize interventions on the temporal multi-graph. \\ {\bf (3)}~An observation of the interfplay between the dynamics of graph states and how information flows over the graph for a decision making agent, which motivates the design of our deep network architecture. \\ {\bf (4)}~A set of benchmarks and strong baselines for this problem. This includes statistics collected from real-world contact tracing data for COVID-19. Our RL approach achieves superior performance over these datasets, often significantly. \section{Previous work} Our work is in the intersection of a few disciplines. We tackle the problem of \emph{controlling a dynamic process} by considering it as \emph{ranking problem on a temporal graph}. As a particular example, we address the problem of a controlling a viral epidemic spreading on a social graph. \textbf{Deep Learning on graphs.} Graph neural networks (GNNs) are deep neural networks that can process graph-structured data. GNNs became very popular and were shown useful for solving a variety of tasks including social network analysis \cite{kipf,fan2019graph} and molecule property prediction \cite{Gilmer2017,Duvenaud2015}. Perhaps the most popular GNN models are Message Passing Neural Networks (MPNN) \cite{Gilmer2017, Hamilton2017, Velickovic2017}, which operate by repeatedly updating the feature vector of each node by aggregating information from its neighbourhood. Several works combine recurrent mechanisms with GNNs to learn temporal graph data, e.g., \cite{guo2019attention, zhao2019t, fang2019gstnet,yu2017spatio} tackled the traffic forecasting problem . \cite{li2019study,kapoor2020examining} proposed a graph-structured RNN for coarse spatial prediction of epidemic spread. Unlike this work, these works model the epidemic spread and do not try to intervene with the diffusive process. More generally, several recent studies \cite{liu2019towards, rossi2020temporal, liu2020towards, pareja2020evolvegcn} tackle a setup in which both nodes and edges vary over time, with applications in social network analysis and other fields. Further information can be found in \cite{kazemi2020representation}. \textbf{Ranking on graphs.} The problem of ranking on graphs is a fundamental problem in Computer Science, in which the task is to rank the nodes of a given graph according to some criteria. It has various applications such as web page ranking \cite{page1999pagerank,agarwal2006ranking} and knowledge graph search \cite{xiong2017explicit}. \textbf{Reinforcement learning and graphs.} Recently, a surge of work combining Reinforcement Learning and graphs emerged. These works can be split into two main categories: leveraging graph structure for general RL problems (e.g., \cite{Zhang2018,Jiang2018}), and applying reinforcement learning methods for graph problems. Our work falls into the latter. An important line of work utilizes Reinforcement Learning in order to solve NP-hard combinatorial optimization problems defined on a graph \citep{Zhu,Dai}. Another common application is the usage of RL for path searching in a knowledge graph \citep{xiong2017explicit,Das}. Reinforcement learning was also shown in a few other graph problems, such as chemical reaction prediction \cite{Do2018}. \textbf{Dynamic processes on graphs. } Modelling diffusive processes is an active research field. Key models such as SIR (Suscpetible-Infected-Removed) and SIS (Suscpetible-Infected-Suscpetible) \cite{Newman2010a} to the recent SEIR (Suscpetible-Exposed-Infectious-Removed) COVID-19 epidemic model \cite{Lin2020,Lopez2020} have proven useful in modelling the spread of contagions. The application of these models is extended, and varies from early epidemic detection \cite{Meirom2015}, to influence maximization \cite{Kempe2003} and network security \cite{Gourdin2011}. The control of such processes on graphs was less discussed, and mostly focused on simple networks models and asymptotic results \citep{Tennenholtz2017, Hoffmann2020}. \section{A motivating example} We begin with an example to illustrate the trade-offs of the problem. A natural algorithmic choice would be to act upon nodes that are most likely infected. The following example shows why this approach is suboptimal. We form a time-varying graph from a list of interactions between nodes at various times. If $u,v$ interacted at time $t$ then the edge $(u,v)$ exists at time $t$. Each interaction is characterized by a transmission probability $p_e(t)$. If a node was infected at time $t$ and its neighbor was healthy, then the healthy node is infected with probability $p_e(t)$. We can test a single node at odd timesteps. If the node is identified as infected, it is sent to quarantine and cannot further interact with other nodes. Otherwise, we do not perturb the dynamics and it may interact freely with its neighbors. Our goal is to minimize the number of infected nodes. Consider the "two stars" network in \figref{fig:toy-example}. The left hub (node $v_1$) has $m_1$ neighbors, and $m_2$ nodes are attached to the right hub $v_2$. At $t=0,$ only the edge $e=(v_{1},v_{2})$ is present with $p_e(t=0)=p$. Then, for all $t\geq1$, all edges depicted in \figref{fig:toy-example} exist with $p_e(t)=1$. Assume that this information is known to the agent, and that at $t=1$ it is revealed that node $v_{1}$ was infected at $t=0$. In this example, we clearly should test either $v_{1}$ or $v_{2}$. We can compute the expected cost of each option exactly. \textbf{Alternative I:} Test ${v_2}$. With probability $p$, $v_{2}$ becomes infected at $t=1$, and we block the epidemic from spreading. However, we forfeit protecting $v_{1}$ neighbors, as all of them will be infected in the next step. With probability $1\!-\!p$ test is negative, and we fail to affect the dynamics. At $t=2$ node $v_{2}$ will get infected and at $t=3$ all of $v_{2}$'s neighbors become infected too, ending up with a total of $\left(m_{2}+1\right)$ infections. The expected cost in choosing to test $v_{2}$ is $(1-p)\cdot m_{2}+m_{1}$. \textbf{Alternative II:} Test $v_{1}$. We block the spread to $v_{1}$'s neighbors, but sacrifice all $m_{2}$ neighbors of $v_{2}$ with probability $p$. The expected cost in choosing $v_2$ is $p\cdot m_{2}$. The decision would therefore be to test for $v_{2}$ if $2p\geq1+m_{1}/m_{2}$. This example illustrates that an optimal policy must balance two factors: \emph{the probability that the dynamics is affected} - that a test action yields a ``positive", and the future consequences of our action - the \emph{strategic importance} of selecting\emph{ $v_{1}$ vs. $v_{2}$}, expressed by the ratio $m_{1}/m_{2}$. A policy targeting likely-infected nodes will always pick node $v_1$, but since it only focuses on the first term and ignores the second term, it is clearly suboptimal. \begin{figure} \begin{minipage}[c]{0.4\columnwidth} \includegraphics[width=0.99\columnwidth]{figs/toy_example.png} \end{minipage} \hfill \begin{minipage}[c]{0.5\columnwidth} \caption{ A double star configuration. The state of $v_{2}$ is unknown at the $t=1$. $v_1$ is infected at $t=0$.} \label{fig:toy-example} \end{minipage} \end{figure} An immediate question arise: How can we develop methods that address both terms? It is difficult to measure the strategic importance of a node in a large dynamical process with constant external interventions directly. Instead, one may use simulations and try to learn from the collected experience and the interplay between dynamics and actions a method that finds the optimal policy end-to-end and internally weighs the two terms optimally. This calls for a reinforcement learning framework. \begin{figure}[t] \centering \includegraphics[width=0.9\columnwidth]{figs/RL_graphs_fig2.png} \caption{Schematic of our approach. The Ranking module receives as input a sequence of graphs and outputs scores over nodes. Scores are then used to sample actions, selecting nodes for intervention. Here, the person circled in blue is selected for quarantine and its connections are cancelled (dashed blue lines). The downstream effect on epidemic progression is then fed as a loss to the ranking module.} \label{fig:Approachsechematics} \end{figure} \section{Problem Formulation} \label{sec:problem_formulation} We first discuss the general framework, and then present a concrete example focusing on the spread of epidemics. \secref{sec:extensions} provides additional use cases and applications of the general framework. Consider a diffusive process on a temporal graph $G(t)=(\mathcal{V},\mathcal{E}(t))$ whose structure changes in time. $\mathcal{V}$ is the set of nodes and $\mathcal{E}(t)=\{e_{uv}(t)\}$ is the set of edges at time step $t$. An edge $(u,v)$ between two nodes exists at time $t$ iff the two nodes interacted at time $t$. Each edge $e_{uv}(t)$ is associated with features $\phi_{uv}(t)$ which may vary in time, and each node $v$ is characterized with features $\zeta_{v}(t)$. The state of a node $v\in\mathcal{V}$ is a random variable $ST_v(t)$ which can have values in $\mathcal{Y}=\{y_{1},y_{2},..\}$. The node's state $ST_v(t)$ depends on the interactions between $v$ and its neighbors at time $t$ and on the state of those neighbors, We aggregate all neighborhood information to a random variable $$N_{v}(t)=\left\{ \left(\phi_{vu}(t),\zeta_{u}(t),ST_u(t)(t-1)\right)|u,e_{vu}\in\mathcal{E}(t)\right\} .$$ Additionally, $ST_v(t)$ depends on the previous state $ST_v(t-1)$ and on node features. In other words, \[ ST_v(t)=f\left(ST_v(t-1),\zeta_{v}(t),N_{v}(t)\right). \] At each step, we may select a subset $A(t)$ of $k$ nodes, and change the state of any selected node $v\in A(t)$. Selecting nodes and setting their states defines the space of actions for the agent, and plays the role of a knob for controlling the global dynamics of the process over the graph. Formally we apply a transformation $u(\cdot)$ on node $v$, setting $ST_v(t)=u\left(ST_v(t)\right),\forall v\in A(t)$. The optimization objective should be invariant to permuting (relabeling) of the nodes. We assume it depends only on the total number of nodes in state $i$, $c_{i}(t)=\sum_{v}\mathbb{I}_{SV(t)=s_{i}}$, where $I$ is the indicator function. The objective is therefore of the form \[ \sum_{t,v\in\mathcal{V}}\gamma^{t-t_{0}}g(c_{1}(t),c_{2}(t),..), \] where future evaluation are weighted by a discount factor $\gamma \le 1$. Additionally, the agent may be subject to constraints written in a similar manner $\sum_{i}f_{i}(c_{1}(t),c_{2}(t),..)\geq y_{i}(t)$. \subsection{Epidemic test prioritization} We consider the recent COVID-19 outbreak that spreads through social contacts. The temporal graph $G$ is defined over a group of people $\mathcal{V}$, and its edges $\mathcal{E}(t)$ are determined by their daily social interactions. Each of these interactions is characterized by various features, including its duration, distancing and environment (indoors or outdoors). \textbf{The SEIR model}. We follow the widely-used SEIR model \cite{Lopez2020}. Every node (person) can be in one of the following states, $\mathcal{Y}={S, L, I, R}$, namely: \textit{susceptible} -- a healthy, yet uninfected person, \textit{exposed/latent} -- infected but cannot infect others, \textit{infectious} -- may infect other nodes, or \textit{removed/recovered} -- self-quarantined and removed from the graph . \textbf{Node state dynamics}. In our model, a healthy node can become infected with a probability that depends on its interactions with its neighbors. Once infected, transitioning from \textit{Exposed/Latent} to \textit{Infected} is defined by a probabilistic process. A node becomes \textit{Removed} if it is selected for self-quarantine (tests positive); see Fig.~\ref{fig:viralinfection} for an illustration. Formally, let $\mathcal{I}(t)\subset V$ be the set of infectious nodes at time $t$, and similarly $\mathcal{L}(t)$, $\mathcal{R}(t)$ and $\mathcal{S}(t)$ be the sets of latent(exposed), removed and susceptible (healthy) nodes. Each edge that is active at time $t$, $e\in\mathcal{E}(t)$, carries a transmission probability $p_{e}(t)$. Denote the set of impinging edges on node $v$ with an infectious counterpart at time $t$ by $E_{v}(t)=\left\{ e\in\mathcal{E}(t)|e=(v,u),SV_u(t-1)=I\right\} .$ The probability of a healthy node to remain healthy at time $t$ is $1-\prod_{e\in E_{v}(t)}\left(1-p_{e}(t)\right)$, otherwise it becomes infected, but still in a latent state. We denote the time of infection of node $v$ as $T_{v}.$ A node in a latent state will stay in this state at time $t$ if $t<T_{v}+D_{v}$, where $D_{v}$ is a RV representing the latency period length, otherwise its state changes to infectious. The testing intervention $u(\cdot)$ changes the state of a node. If infected or exposed, its state is set to $R$, otherwise it remains as it is. \textbf{Optimization goal and action space.} The objective is to minimize the spread of the epidemic, namely, minimize the number of infected people over time, $\mathbb{I}_{ST_v(t)\in\{L,D\}}$. Assuming that testing is limited to a fixed capacity of $k$ tests per day, the optimization goal becomes $ \min\sum_{t,v}\gamma^{t}\mathbb{I}_{ST_v(t)\in\{L,D\}}, $ where $\gamma\in(0,1]$ is a discount factor representing the relative importance of the future compared to the present. We used $\gamma=0.99$ throughout the paper. Of course, this is but one particular optimization goal and other goals that weigh different states differently, or add additional aspects are possible. The action space consists of all possible selections of a subset of $k$ nodes $\mathcal{T}_{t}\subset V$. Even for moderate graph, with $\sim100-1000$ and small $k$ the action space ${k \choose |\mathcal{V}|}$ is huge. \textbf{Observation space.} At each time $t$, the agent is exposed to all past interactions between network nodes $\left\{ \mathcal{E}(t')|t'<t\right\} $. In addition, we are given partial information on the nodes state. The agent is provided with information on a subset of the infectious nodes at $t=0$. At every $t>0$, the agent observes all past test results. Formally, for every $v\in a(t)$ we observe if $ST_v(t)\in\mathcal{I}(t)\cup\mathcal{L}(t) $ or not. \section{Approach} \label{sec:approach} Our approach is depicted in Figure \ref{fig:Approachsechematics}. The RL agent receives as input the node and edge features of the temporal graph, and processes them using its ranking module. A probability distribution over graph nodes is generated from the ranking module’s scores, and the agent samples a subset of $k$ nodes for testing. Namely, the scores encode the agent's policy. We use Proximal Policy Optimization algorithm (PPO, \cite{Schulman2017}) as to optimize our agent. We sequentially apply the suggested action, log the (state, action) tuple in an experience replay buffer, and train our model based on the PPO loss term. Next, we describe the ranking module and sampling procedure. We reason about our choice of the RL framework in the supplementary information. \subsection{RL Agent Ranking Module} \label{sec:ranking_module} \paragraph{Overview} Our GNN-RNN module serves to update the internal representation of a node $v$, denoted $h_v(t)$, and its score $s_v(t)$ (\figref{fig:ranking}). This score is later used for selecting nodes to be acted on. The ranking module is applied in a recurrent fashion at each time step. The ranking module contains two GNNs: (1) $E$, which updates the epidemic state, and (2) $I$, which updates the information state. It also contains two other networks, $G$ and $F$, which update node representations and node scores by using the epidemic state and information state as well as the previous node representations. \textbf{Input.} The input to the ranking module consists of three feature types (See \figref{fig:ranking}): (1) \textit{Static node features} $\zeta^s_v(t)$: topological graph centralities (betweeness, closeness, eigenvector and degree centralities) and random node features. (2) \textit{Dynamic node features} $\zeta^d_v(t)$ : All test results that were performed up the current timestamp (including positive and negative test results). We denote all nodes features as a concatenation $\zeta_v(t)=[\zeta^s_v(t),\zeta^d_v(t)]$. (3) \textit{Edge features} and the structure of the temporal graph $\mathcal{E}(t)$: All previous interactions up to the current step, including the transmission probability for each interaction. Figure \ref{fig:ranking} illustrates the basic data flow in the ranking module. \begin{figure}[t] \centering \includegraphics[width=0.8\columnwidth]{figs/RL_graphs_fig3.png} \caption{Block diagram of our suggested ranking module. It is composed of 4 neural networks $I$,$E$,$G$,$F$, which update the nodes scores and hidden states at each time step.} \label{fig:ranking} \end{figure} \textbf{Epidemic GNN.} The spread of epidemic through point contact is modeled by a GNN $E$. As the epidemic cannot spread by more than one hop per step, it is sufficient to model the spread with a single GNN layer. Formally, denote by $p_{vu}$ the probability of transmission during the interaction between $(v,u)$ at time $t$. For each $v$, the output of $E(\cdot)$ is a feature vector denoted by $e_v(t)$: \begin{align*} e_{v}(t) & =\sum_{u\sim_{t}v}p_{vv'}(t)\cdot M_{e}(\zeta_{v}(t),\zeta_{v'}(t);\theta_{m_e}), \end{align*} where $M$ is multilayer perceptron (MLP). \textbf{Information GNN.} The score of a node is affected both by the propagation dynamics, and by the information available to the agent. One may hope that since the former has a known timescale (days), on a short time scale (single day) the score of node would only be affected by its neighboring nodes. This, however, is not the true because information can propagate long distance in the graph almost instantaneously. As a simple example, consider nodes in a connected chain of (untested) nodes and note that they are statistically dependent. As a result, revealing the state of one node immediately affects the distribution over all nodes in the chain. With this consideration in mind, we designed an \textit{information GNN}, $I$, which represents the {\em information state} of each node. As discussed above, updated information on a node $u$ a few hops away from node $v$ may abruptly change our beliefs on the state of $v$. Furthermore, this change may occur even if $v$ and $u$ did not interact in the last time step but rather a while ago. To update the information state, we construct a cumulative multi-graph $G'$ where the set of edges between nodes $v$ and $u$ at time $t$ are all the interactions that occurred during the last $\tau$ steps, $\mathcal{E}_{G'}$=$\cup_{t'\in[t-\tau,t]}\mathcal{E}_{G}(t)$. The features of each edge in $\mathcal{E}_{G'}$, $\phi_{vu}(t')$, are the interaction delay $t-t'$ and the transmission probability $p_{v,v'}(t')$. The information features are the output of $k$-layer GNN; the $l^{th}$ layer is: \[ x_{v}^{l}(t)=\sum_{v'\sim_{t}v}M^{l}(x_v^{l-1}(t),x_{v'}^{l-1}(t),\phi_{vv'\text{\rq}(t)};\theta_M^l). \] As before, $M^l$ is an MLP, with $x_{v}^{0}(t)=\zeta_{v}(t)$ and $x_{v}^{k}(t)=i_{v}(t)$ are the final node features. The value of $\tau$, the information window size, was 7 in all our experiments. \textbf{Score and hidden state update.} For every node we hold a hidden state $h_{v}(t)$, which is updated following \begin{equation} h_{v}(t)=G(h_{v}(t-1),\zeta_{v}(t),e_{v}(t), i_{v}(t) ;\theta_{g}) \end{equation} After updating the new node hidden state, we use them to calculate the node score using a neural network $F$, \begin{equation} s_{v}(t)= F(h_{v}(t),h_{v}(t-1),\zeta_{v}(t);\theta_{f}) \end{equation} Here, $F$ is an MLP, while $G$ can be either an MLP or recurrent module such as GRU. \textbf{Sampling.} Given the score per node $s_v(t)$, we sample without replacement $k$ nodes iteratively. We (1) map the score of $n$ nodes to a probability distribution using a score-to-probability distribution function, (2) sample a node, and (3) adjust the distribution by removing its weight. We repeat this process $k$ iterations. \subsection{Design choices} \textbf{Critic module.} PPO, as an actor-critic algorithm, requires a critic module to estimate the value function in a given state. We construct the actor using a similar architecture to the ranking module, but apply to element-wise max operation on the rows (representing the nodes) of the input to the score module $F$ (\figref{fig:ranking}). This reduces $F$'s input to a single row of features, and the output is then a scalar rather than a vector. Importantly, the critic is parametrized by a different set of weights than the ranking module (actor). \textbf{Score-to-probability distribution.} Usually, node scores are converted to a distribution over actions using a softmax. This approach is problematic for our case because node probabilities decay exponentially with their scores, leading to two major drawbacks. It discourages exploration of low-score nodes, and limits sensitivity to the top of the distribution, instead of at the top-k selected. Instead, we define the probability to sample an action $a_{i}$ to be $\Pr(a_{i})=\frac{x_{i}'}{\sum x_{i}'}$, with $x_{i}'=x_{i}-\min_{i}x_{i}+\epsilon$, where $\{x_{i}\}$ be the set of scores and $\epsilon$ a constant. We discuss selection of $\epsilon$ in the supplemental. \textbf{Normalization in scale-free networks.} RNN are well-known to suffer from the problem of exploding or vanishing gradients. This problem is exacerbated in a RNN-GNN framework used for RL algorithms, because they may be applied for arbitrary long episodes, causing internal state to grow unbounded. This problem is particularly severe if the underlying graph contains hubs (highly connected nodes). One approach to alleviate this problem, is by including an RNN like a GRU module, where the hidden state values pass through a sigmoid layer. As the magnitude of the input grows, gradient become smaller and training slows down. We found that the problem can be solved by directly normalize each node hidden state ($L_2$ norm). \section{Experiments} \subsection{Compared approaches} We compare methods from three categorizes: A) programmed; B) supervised learning (SL) C) Reinforcement learning (RL). Each experiment was performed with at least three random seeds. Additional experimental and implementation details, including network architecture, are provided in the supplementary material. \textbf{A. Programmed baselines.} Most countries currently prioritize their testing based on fixed procedures determined in advance and not learned form data. We compare with two such methods to rank nodes. \textbf{(1) Infected neighbors.} Rank nodes based on the number of known infected nodes in their 2-hop neighborhood (neighbors and their neighbors). Each node $v$ is assigned a tuple $(I_{v}^{(1)},I_{v}^{(2)})$, and tuples are sorted in a decreasing lexicographical order. A similar algorithm was used in \cite{Meirom2015, 8071015} to detect infected nodes in a noisy environment. \textbf{(2) Probabilistic risk.} Each node keeps an estimate of the probability it is infected at time $t-1$. To estimate infection probability at time $t$, beliefs are propagated from neighbors, and dynamic programming is used to analytically solve the probability update. See suppl. for details. \textbf{B. Supervised learning.} Algorithms that learn the risk per node using features of the temporal graph, its connectivity and infection state. Then, $k$ nodes with the highest risk are selected. \textbf{(3) Supervised (vanilla).} We treat each time step $t$ and each node $v_i$ as a sample, and train a 3-layer deep network using a cross entropy loss against the ground truth state of that node at time $t$. The input of the DNN has two components: A static component described in \secref{sec:ranking_module}, and a dynamic part that contains the number of infected neighbors and their neighbors (like \#1 above). \textbf{(4) Supervised (+GNN).} Like \#3, but the input to the model is the set of all historic interactions of $v_i$'s and its $d$-order neighbours and their time stamps as an edge feature. The architecture is a GNN that operates on node and edge features. We used the same ranking module as our GNN framework, but the output probability is regarded as the probability that a node is infected. \textbf{(5) Supervised (+weighted degree).} Same as \#4, but the loss is modified and nodes are weighted by their degree. (See the supplemental). Indeed, we wish to favour models that are more accurate on high-degree nodes, because they may infect a greater number of nodes. \textbf{(6) Supervised (+weighted degree +GNN).} Like \#4 above, using degree-weighted loss like \#5. \textbf{C. RL algorithms:} \textbf{\RLGN{}} is our algorithm described in \secref{sec:approach}. The input to \textbf{(7) RL-vanilla} is the same as in (\#1) and (\#4) above. Correspondingly, the GNN module of described in \secref{sec:approach} is replaced by a DNN similar to (\#4), while the rest of the RL algorithm remains intact. \subsection{Experiment details and evaluations} \textbf{Training.} We train the RL and SL by generating random networks, and selecting for each instance a random subset of $m_{0}$ initially infected nodes. We propagate the epidemic until it spans at least $k_{0}$ infected nodes (for at least $t_{0}$ steps), and randomly detect a subset of the infected nodes of size $<k_{0}$. The simulation then follows the agent-network dynamics described in \secref{sec:problem_formulation}. \textbf{Evaluation Metrics.} We use two success metrics: (1) \textbf{\% healthy:} The percent of nodes kept healthy throughout the simulation. (2) \textbf{\%contained:} The probability of containing the epidemic. This was computed as the fraction of simulations having cumulative infected nodes smaller than a fraction $\alpha$. We focus on this metric because it captures the important notion of the capacity of a health system. See suppl. for discussion. \subsection{The dataset and complex-network models.} We study three types of networks which differ by their connectivity patterns. More details in the suppl. material. \textbf{Community-based networks} have nodes clustered into densely-connected communities, with sparse connections across communities. We use the \textit{Stochastic Block Model} (SBM, \cite{abbe2017community}), for 2 and 3 communities. \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{figs/three_communtities.png} \caption{Supervised vs RL with 3-community networks. \textbf{Left:} RLGN successfully learns to contain the epidemic 60\% of the time, while SL fails. \textbf{Right:} SL isolates many more infected nodes, but less important ones.} \label{fig:three_communities} \end{figure} \textbf{Preferential attachment (PA)} networks exhibit a node-degree distribution that follows a power-law (scale-free), like those found in many real-world networks. We use the dual Barbarsi-Albert model \cite{Moshiri2018}, which allows for continuously varying the mean node degree. \textbf{Generating temporal graphs.} Static networks generated using PA or SBM are converted to a temporal graph by first selecting a random subset of edges $\mathcal{E}(t)$ at each time step $t$, and then assigning to each edge a transmission probability $q_e(t)$ sampled uniformly $U[a,b]$. \textbf{Contact-tracing.} We received anonymized high-level statistical information about real contact tracing networks that included the distribution of node degree, transmission probability and mean number of interactions per day, collected during April 2020. \begin{table} \setlength{\tabcolsep}{3pt} \scalebox{0.97}{\small{\sc{ \begin{tabular}{|l|c|c|} \hline \%contained & 2 communities & 3 communities \\ \hline \hline Tree-based model & $15\pm 35$ & $0\pm0$ \\ \hline Counter model & $19\pm39$ & $ 1\pm 4$ \\ \hline Supervised (vanilla) & $24\pm 11$ & $2\pm 2$ \\ \hline Supervised +GNN & $27\pm 10$ & $ 2\pm 2$ \\ \hline Supervised +degree & $29\pm 10$ & $ 1\pm 2$\\ \hline Supervised +GNN+deg & $24\pm 10$ & $2\pm 02$\\ \hline \RLGN{} minimal & $66\pm 10$ & $7\pm 5$ \\ \hline \RLGN{} full (ours) & \textbf{$88\pm 7$} & \textbf{$53\pm 13$} \\ \hline \end{tabular} }}} \caption{Probability (in \%) of containing an epidemic in community-based networks. Each community has $30$ densely connected nodes. } \label{tab:comaprison-chart} \end{table} \begin{table} \centering \setlength{\tabcolsep}{3pt} \scalebox{0.99}{\small{\sc{ \centering \begin{tabular}{|l|c|c||c|c|} \hline & \multicolumn{2}{c}{\%contained} & \multicolumn{2}{c}{\%healthy} \\ \hline & PA & CT & PA & CT\\ \hline \hline Tree based model & $1\pm1$ & $0\pm0$ & $10\pm7$ & $11\pm3$\\ \hline Counter model & $0\pm0$ & $0\pm0$ & $7\pm7$ & $14\pm5$ \\ \hline SL (vanilla) & $2\pm2$ & $0\pm0$ & $13\pm3$ & $17\pm1$\\ \hline SL + GNN & $27\pm6$ & $15\pm4$ & $34\pm3$ & $32\pm$2\\ \hline SL + deg & $3\pm3$ & $0\pm1$ & $15\pm3$ & $18\pm1$\\ \hline SL + deg + GNN & $26\pm5$ & $16\pm5$ & $33\pm3$ & $32\pm1$\\ \hline RL (vanilla) & $2\pm2$ & $1\pm1$ & $17\pm1$ & $16\pm1$\\ \hline RLGN (ours) & \textbf{$\mathbf{78\pm4}$} & $\mathbf{45\pm6}$ & $\mathbf{52\pm2}$ & $\mathbf{40\pm1}$ \\ \hline \end{tabular} }}} \caption{\%contained epidemics and \%healthy nodes achieved on a preferential attachement (PA) network, and contact tracing (CT) network. In both cases, networks had $200$ nodes.} \label{tab:comaprison-chart-scale-free} \end{table} \subsection{Results} \label{sec:results} We compared 7 algorithmic approaches on 3 network types. The results reported in Table \ref{tab:comaprison-chart} and \ref{tab:comaprison-chart-scale-free} show that RLGN outperforms all baselines in all network types. To gain insight into this result, we first look more deeply into the case of 3-community networks. \figref{fig:three_communities}(a) traces the fraction of contained epidemics and \figref{fig:three_communities}(b) the fraction of infected nodes during training. The supervised learning algorithm detects substantially more infected nodes (right panel) than RLGN, but these tend to have lower future impact on the spread, and it fails to contain the epidemic (left). A closer look (in the supplemental) shows that RL, but not SL, successfully learns to identify and neutralize the critical nodes that connect communities and prevent the disease from spreading to another community. To further understand the solutions learned for PA networks, consider the following two extremes. First, when a network is very sparsely connected, it would be easy to cut long infection chains, and both approaches are expected to be successful. At the other extreme, for densely connected networks, there are no critical nodes, because there are many paths between any two nodes. To study this effect we generated networks with the preferential-attachment mechanism, while varying the mean node degree. This degree can also be viewed in terms of the $R_0$ coefficient, the mean number of nodes infected by a single diseased node. The greater $R_0$, the more difficult it is to contain the epidemic. \begin{figure} (a)\hspace{120pt} (b)\hspace{120pt}\\ \includegraphics[width=0.48\columnwidth]{figs/phase_shift.png} \includegraphics[width=0.48\columnwidth]{figs/stability_analysis} \caption{\textbf{Stability analysis:} \textbf{(a)} The contained epidemic fraction as a function of the basic reproduction number $R_0$ on a PA network. RLGN outperforms SL over a large range of $R_0$ values. \textbf{(b)} Stability against test-time shift in transmission probability. \textit{Orange:} The performance of RLGN deteriorates when the mean transmission probability at test time is higher more than $40\%$ than train time. \textit{Purple:} As a baseline, training and testing with the same higher transmission probability. \label{fig:stability} } \end{figure} Fig.~\ref{fig:stability}(a) quantifies this effect, showing the percent of contained epidemics as a function of the $R_0$ coefficient. RL has a significant advantage over supervised+GNN for a range of $R_0$ values between $2.0$ and $2.9$. Finally, \figref{fig:stability}(b) depicts a robustness analysis of \RLGN{} for variations in the epidemiological model. One of the most difficult quantities to assess is the probability for infection per social interaction. \figref{fig:stability}(b) shows that the trained model can sustain up to $\sim40\%$ deviation at test time in this key parameter. \ignore{ \begin{figure} \includegraphics[width=1\columnwidth]{figs/score_to_prob_ablation.png} \caption{\label{fig:score-to-prob} The obtained epidemic probability during training on a preferential attachment model with $200$ nodes and a mean degree $2.8$. Note that only one of the three seeds in the softmax distribution simulation completed due to numerical instability, while for the calibrated-scores method no stability issues occurred. } \end{figure} } \subsection{Ablation experiments and stability analysis} We performed ablation experiments to evaluate the contribution of the architectural improvements described in \secref{sec:ranking_module}. We found that (1) Without calibrating the score-to-prob function training of RLGN often failed to converge; (2) Normalizing hidden states is required, or their values diverge during training; (3) The information module is important for containing the epidemics. For example, without it, the fraction of contained epidemics drops from 74\% to 62\% on the contact tracing data; see the supplementary material. \ignore{ \begin{table} \centering \begin{tabular}{|c|c|c|} \hline & $\%contained$ & \# training epochs\\ \hline \hline Sigmoid & $0.84\pm0.05$ & 1210\\ \hline GRU & $0.91\pm0.03$ & 810\\ \hline $L_{2}$ norm. & $\mathbf{0.93\pm0.02}$ & \textbf{500}\\ \hline \end{tabular} \caption{\label{tab:norm-table} Training time and fraction of contained epidemic for three normalization schemes. The normalization scheme \eli{Need a name} is fastest and achieves the best performance.} \end{table}} \section{Extensions\label{sec:extensions}} The approach and model discussed in this paper can be applied to important problems other than epidemic control. {\bf Influence maximization (IM).} Unlike epidemic control, in IM, the decision maker the objective is to maximize the spread of some opinion on a social network graph. They act to select nodes to be influenced by presenting information, actively contacting them, or sending coupons etc. Given a budget, the IM agent can only contact a limited number of nodes over a period of time. Influence spreads over the social networks similar to the model described above. The overall cost has two terms: cost of spending budget on influencing individual nodes, and benefit from influencing a give portion of the network. Local effects such as high degree nodes are important to IM. {\bf Fake news detection and confinement.} Consider a social network where fake news can be maliciously distributed, and spread over the network. A decision maker can verify the authenticity of items, but only verify a limited number of items per a time period. Once a fake item is detected, it is erased from the network. The objective is to minimize the total number of nodes that observe fake items. The main difference from the epidemic problem is that once a fake item is discovered, it can be erased from the entire network. The trade-off is that the decision maker does not want to waste inspection resources on items that are likely to die out. \section{Conclusions} This paper shows that combining RL with GNNs provides a powerful approach for controlling spreading processes on graphs. In the context of COVID-19 spread, we demonstrated that using an RL+GNN approach allows us to confine the spread of an epidemic that is approximately 30\% more contagious (i.e., $R_0$ that is 30\% higher) with the same resources as a standard supervised learning-based approach. In addition, our results indicate that prioritizing tests using RL on temporal graphs can increase the number of healthy people by $25\%$ \gal{revise} and contain the epidemic $30\%$ more often than supervised approaches and $2.5\times$ more often than non-learned baselines using the same resources. \bibliographystyle{aaai21} \section{Introduction} \ignore{ \begin{table*} \begin{tabular}{|c|c|c|c|c|} \hline & 2 communities & 3 communities & Preferential \\ attachment & contact tracing\tabularnewline \hline \hline Tree based model & $0.15\pm0.35$ & & & \tabularnewline \hline Counter model & $0.19\pm0.39$ & & & \tabularnewline \hline Supervised (minimal) & $0.24\pm0.11$ & $0.02\pm0.02$ & $0.38\pm0.1$ & $0.05\pm0.05$\tabularnewline \hline Supervised (full) & $0.27\pm0.1$ & $0.02\pm0.02$ & $0.76\pm0.1$ & $0.52\pm0.1$\tabularnewline \hline Supervised + \\ degree weighted loss & $0.29\pm0.1$ & $0.01\pm0.02$ & $0.77\pm0.09$ & \tabularnewline \hline Supervised + class \& \\ degree weighted loss & $0.24\pm0.1$ & $0.02\pm0.02$ & $0.87\pm0.07$ & \tabularnewline \hline RL (minimal) & $0.66\pm0.10$ & $0.07\pm0.05$ & $0.39\pm0.06$ & \tabularnewline \hline RL (full) & $\mathbf{0.876\pm0.07}$ & \textbf{$\mathbf{0.53\pm0.13}$ } & \textbf{$\mathbf{0.93\pm0.05}$ } & \textbf{$\mathbf{0.74\pm0.1}$ }\tabularnewline \hline \end{tabular} \caption{\gal{Keep only communities. Add caption}} \label{tab:comaprison-chart} \end{table*} } \begin{table} \setlength{\tabcolsep}{3pt} \scalebox{0.99}{\small{ \centering \begin{tabular}{|l|c|c|} \hline & Preferential & contact \\ & attachment & tracing\\ \hline \hline Tree based model & $0.20\pm0.02$ & $0.00\pm0.00$ \\ \hline Counter model & $0.31\pm0.02$ & $0.02\pm0.01$\\ \hline Supervised (vanilla) & $0.38\pm0.10$ & $0.05\pm0.05$\\ \hline RL minimal (ours) & $0.39\pm0.06$ & \\ \hline Supervised +GNN & $0.76\pm0.10$ & $0.52\pm0.1$\\ \hline Supervised +GNN+deg & $0.77\pm0.09$ & $0.54\pm0.11$\\ \hline RL full (ours) & \textbf{$0.93\pm0.05$} & \textbf{$0.74\pm0.1$}\\ \hline \end{tabular} }} \caption{Percentage of epidemics contained, in PA and contact-tracing Comparison across methods on scale-free network models of $200$ nodes. Values are the probability of containing an epidemic in percents $\pm$ is empirical standard deviation.} \label{tab:comaprison-chart-scale-free} \end{table} \begin{table} \centering \setlength{\tabcolsep}{3pt} \scalebox{0.99}{\small{\sc{ \centering \begin{tabular}{|l|c|c|c|c|} \hline & \multicolumn{2}{c}{\%contained} & \multicolumn{2}{c}{\%healthy} \\ \hline & PA & CT & PA & CT\\ \hline \hline Tree based model & & $0\pm0$ & & $11\pm3$\\ \hline Counter model & $ & 0\pm0$ & & $14\pm5$ \\ \hline SL (vanilla) & $2\pm2$ & $0\pm0$ & $13\pm3$ & $17\pm1$\\ \hline SL + GNN & $27\pm6$ & $15\pm4$ & $34\pm3$ & $32\pm$2\\ \hline SL + deg & $3\pm3$ & $0\pm1$ & $15\pm3$ & $18\pm1$\\ \hline SL + deg + GNN & $26\pm5$ & $16\pm5$ & $33\pm3$ & $32\pm1$\\ \hline RL (vanilla) & $2\pm2$ & $1\pm1$ & $17\pm1$ & $16\pm1$\\ \hline RLGN (ours) & \textbf{$\mathbf{78\pm4}$} & $\mathbf{45\pm6}$ & $\mathbf{52\pm2}$ & $\mathbf{40\pm1}$\\ \hline \end{tabular} }}} \caption{Percent of contained epidemics and percent of healthy nodes achieved using all methods on a PA network (n=$200$ nodes), and CT network.} \label{tab:comaprison-chart-scale-free} \end{table} \section{Large-scale experiments} We extend the experiments presented in the paper, conducted on graphs with 200 nodes, to larger graphs. Specifically, here we compare the two best algorithms RLGN (\#8) and SL+GNN (\#4), using graphs with various sizes, from 300 nodes to 1000 nodes. Table \ref{tab:300-nodes-pa} compares RLGN with the SL+GNN algorithm on preferential attachment (PA) networks (mean degree $=2.8$). We provide results for various sizes of initial infection $i_{0}$ and number of available tests $k$ at each step. The experiments show that there is a considerable gap between the performance of the RL and the second-best baseline. Furthermore, RLGN achieves better performance than the SL+GNN algorithm with 40\%-100\% more tests. Namely, it increases the effective number of tests by a factor of $1.4X-2X$. \begin{table} \centering \setlength{\tabcolsep}{3pt} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=300$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $27\pm2$ & $15\pm5$ & $21\pm2$ & $4\pm2$ & $18\pm1$ & $1\pm1$\\ \hline SL, $k=1.33\%$ & $41\pm3$ & $37\pm6$ & $27\pm2$ & $12\pm4$ & $24\pm2$ & $6\pm3$\\ \hline SL, $k=2\%$ & ${66\pm4}$ & $76\pm6$ & ${48\pm3}$ & $55\pm7$ & $37\pm2$ & $32\pm6$\\ \hline RLGN, $k=1\%$ & $50\pm2$ & ${78\pm7}$ & {$43\pm2$} & ${58\pm1}$ & ${40\pm1}$ & ${48\pm6}$\\ \hline \end{tabular} \vspace*{0.2 cm} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=500$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $24\pm2$ & $7\pm4$ & $20\pm1$ & $2\pm1$ & $19\pm1$ & $0\pm1$\\ \hline SL, $k=1.6\%$ & $48\pm3$ & $54\pm6$ & $35\pm2$ & $27\pm7$ & $29\pm1$ & $11\pm1$\\ \hline SL, $k=2\%$ & ${67\pm3}$ & $83\pm5$ & ${46\pm2}$ & $53\pm4$ & $38\pm2$ & $37\pm7$\\ \hline {RLGN, ${k=1\%}$} & $52\pm1$ & ${97\pm2}$ & ${44\pm2}$ & ${75\pm11}$ & ${42\pm1}$ & ${66\pm6}$\\ \hline \end{tabular} \vspace*{0.2 cm} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=1000$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. Infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $25\pm2$ & $5\pm3$ & $21\pm1$ & $0\pm1$ & $19\pm1$ & $0\pm0$\\ \hline SL, $k=1.5\%$ & $42\pm2$ & $49\pm6$ & $30\pm1$ & $10\pm3$ & $27\pm1$ & $4\pm2$\\ \hline SL, $k=2\%$ & ${66\pm1}$ & $84\pm5$ & ${45\pm2}$ & $59\pm5$ & $37\pm1$ & $30\pm1$\\ \hline {RLGN, ${k=1\%}$} & $52\pm1$ & ${97\pm2}$ & ${44\pm2}$ & ${75\pm11}$ & ${42\pm1}$ & ${66\pm6}$\\ \hline \end{tabular} \caption{A comparison between RLGN and SL+GNN (the best baseline). RLGN performance is highlighted. The number of additional resources needed to surpass the RLGN performance in a given metric is also highlighted. In many cases, even using SL+GNN with twice as many resources than RLGN performs worse than RLGN. The evaluation was performed on a preferential attachment network with mean degree $2.8$. The number of nodes is indicated at the top of each table.} \label{tab:300-nodes-pa} \end{table} We further evaluated how models trained on medium-sized graphs generalize well when performing inference on much larger graphs. We trained RLGN and SL+GNN (three model initializations for each) on a preferential attachment network with $1000$ nodes and evaluated its performance of a network with $50,000$ nodes (with the same mean degree $=2.8$). RLGN successfully contained the epidemic in all $150$ evaluation episodes, while the SL+GNN was unable to block the epidemic even once. The mean percentile of healthy nodes at the end of the episode was $51\pm1$ for RLGN, while for the SL+GNN it was only $21\pm2$, a difference of more than $15$ STDs. \section{Ablation Studies} \subsection{Robustness to size of initial infection} We tested the sensitivity of the results to the relative size of the initial infection. Table \ref{tab:300-nodes-pa} shows results when 4\% of the the network was initially infected, as well as for 7.5\% and 10\%. The results show that RLGN outperforms the baselines in this wide range of infection sizes. \subsection{Mapping scores to action distribution.} Usually, node scores are converted to a distribution over actions using a softmax. This approach is problematic for our case because node probabilities decay exponentially with their scores, leading to two major drawbacks. It discourages exploration of low-score nodes, and limits sensitivity to the top of the distribution, instead of at the top-k selected. Instead, we define the probability to sample an action $a_{i}$ to be $\Pr(a_{i})=\frac{x_{i}'}{\sum x_{i}'}$, with \begin{equation} x_{i}'=x_{i}-\min_{i}x_{i}+\epsilon \quad , \label{eq: score-to-prob} \end{equation} where $\{x_{i}\}$ be the set of scores and $\epsilon$ a constant. The fact that we do not use the exponential functions as in softmax, attenuates the probability differences between low-scoring nodes and high-scoring nodes. Furthermore, the parameter $\epsilon$ controls the initial exploration ratio. In standard DNN initialization schemes (like XAVIER), the initial value of $x_{i}$ is expected to be in [-1,1]. If $\epsilon\gg1$ than the dominant term in \eqref{eq: score-to-prob} is $\epsilon$. This promotes exploration initially, as all actions are likely to be sampled in the early training stages. \paragraph{Ablation study.} We compare the performance of our score-to-probability function (calibrated-scores) to the popular softmax (Boltzmann) distribution. In practice, in most instances, we were unable to train a model using the softmax distribution as the neural network weights diverge. Fig.~\ref{fig:score-to-prob} presents the training curve in one of the few instances that did converge. It is clear that the model was not able to learn a useful policy while using the calibrated-scores probability function resulted in a corresponding value of more than $0.75$. \begin{figure} \centering \includegraphics[width=0.6\columnwidth]{figs/score_to_prob_ablation.png} \caption{The fraction of contained epidemics during training on a preferential attachment model with $200$ nodes and a mean degree $2.8$. For non-normalized mapping, only one of the three seeds in the softmax distribution simulation completed training due to numerical instability. No stability issues were observed when using the calibrated scores normalization scheme described by Eq. \eqref{eq: score-to-prob}. \label{fig:score-to-prob}} \end{figure} \begin{table} \centering \begin{tabular}{|c|c|c|} \hline & $\%contained$ & \# training epochs\\ \hline \hline Sigmoid & $0.84\pm0.05$ & 1210\\ \hline GRU & $0.91\pm0.03$ & 810\\ \hline $L_{2}$ norm. & $\mathbf{0.93\pm0.02}$ & \textbf{500}\\ \hline \end{tabular} \caption{\label{tab:norm-table} Training time and fraction of contained epidemic for three normalization schemes. The $L_2$ normalization scheme is fastest and achieves the best performance.} \end{table} \subsection{Normalization in scale-free networks.} RNN are known to suffer from the problem of exploding or vanishing gradients. This problem is exacerbated in a RNN-GNN framework used for RL algorithms, because they may be applied for arbitrary long episodes, causing internal state to grow unbounded. This problem is particularly severe if the underlying graph contains hubs (highly connected nodes). One approach to alleviate this problem, is by including an RNN like a GRU module, where the hidden state values pass through a sigmoid layer. As the magnitude of the input grows, gradient become smaller and training slows down. We found that the problem can be solved by directly normalize each node hidden state ($L_2$ norm). Scale-free network contain high-degree nodes (``hubs") with $O(n)$ neighbors with high probability. As a simple case, consider a star graph with a large number of nodes. In a GNN framework, it receives updates from a large number of neighbors and its internal state increases in magnitude. At the next time that the GNN module is applied (e.g., next RL step), the growing internal state increases the magnitude of the internal state of its neighbors. This leads to a positive-feedback loop that causes the internal state representation to diverge. Since RL algorithms may be applied for arbitrary long periods, the internal state may grow unbounded unless corrected. \paragraph{Ablation experiment.} We compared the suggested normalization to a number of other alternative normalization methods. (1) Applying a sigmoid layer after the hidden state update module $G$. (2) Replace the hidden state update module with a GRU layer. (3) Apply $L_2$ normalization to each feature vector $h_v(t)$ (similarly to \cite{Hamilton2017}) (4) Normalize the feature vector matrix by its $L_2$ norm. These four normalization schemes span three different types of normalization: single-feature normalization (1+2), vector normalization (3), and matrix normalization (4). Table \ref{tab:norm-table} presents the score after training and the number of training steps required to achieve it (see supplementary information for definitions). Method (4) was unstable and the training did not converge, therefore it was omitted from the table. The main reason for the training time difference is that without normalization, the DNN weights' magnitude increases. In a GRU module, or with a direct application of a sigmoid layer, the features pass through a sigmoid activation function. When the magnitude of the input to this layer is large, the gradient is very small due to the sigmoid plateau. This substantially slows down the learning process. \subsection{Information processing module. } Our experiments showed the information module has a critical role in improving the performance of the RL-GNN framework. We performed an ablation study by removing it completely from our DNN module, keeping only the epidemic module. The full DNN module achieved a contained epidemic score of $0.77\pm0.06$, while the ablated DNN module corresponding score was $0.62\pm0.10$, a degradation of more than $20\%$. \section{Implementation and experiment details} \subsection{Evaluation metrics} The end goal of quarantining and epidemiological testing is to minimize the spread of the epidemic. As it is unreasonable to eradicate the epidemic using social distancing alone, the hope is to ``flatten the curve'', namely, to slow down the epidemic progress. To measure the probability of containing the epidemic, we evaluated the percentage of scenarios in which the epidemic spanned less than $\alpha n$ nodes, where $\alpha n$ can represent the public health system capacity. In the 2-community setup, where each community has half of the nodes, a natural choice of $\alpha$ is slightly greater than $0.5$, capturing those cases where the algorithm contains the epidemic within the infected community. In all the experiments we set $\alpha=0.6$. The only exception is the three-communities experiments, in which we set the bar slightly higher than $1/3$, and fixed $\alpha=0.4$. \subsection{Network architecture} The architecture of the ranking module is shared by algorithms \#4, \#6 and \#8 with slight variations indicated below. \paragraph{Input.} We encode the dynamic node features $\zeta_{v}^{d}(t)$ as a one hot vector of dimension $4$. Each of the first three elements corresponds to one of the three mutually exclusive options, which depends on the action and node state in the previous step: untested, tested positive, tested negative. The last entry indicates whether a node was found positive in the past, namely, if it is quarantined and disconnected from the graph. The static node features, $\zeta_{v}^{s}(t)$, are as described in the main paper, topological graph centralities (betweenness, closeness, eigenvector, and degree centralities) and random node features. The graph centralities were calculated using NetworKit. The total number of node features is 9. \paragraph{Epidemic GNN. }This module $M_{e}$ is composed of a single graph convolutional layer. The input features are the last time step node features. The number of output features is 64. \paragraph{Information GNN. }Each message passing module $M^{l}$ contains one hidden layer, where the number of hidden features is 64. After both the hidden and last layer we apply a leaky ReLu layer with leakage constant $0.01$. After aggregating the result using the addition aggregation function, we apply an additional MLP with one layer (linear+ReLu) on the resulting feature vector. The number of output features is 64. We experimented with the numbers of stacked modules $l$ (layers). We found that $l=3$ performed slightly better than $l=2$ but training was considerably slower because the batch size had to be reduced. We therefore used $l=2$ in all experiments reported. \paragraph{Hidden state update.} The hidden state MLP $G$ is composed of a single linear layer follows by a ReLu activation layer. To keep the resulting hidden feature vector (of dimension 64) norm under check, an additional normalization scheme is then applied. This module was replaced by a GRU layer in the ablation studies. \paragraph{Output layer.} The last module is a single linear layer, with an output dimension as the number of the nodes in the graph. \paragraph{Learning framework}. We used Pytorch \citep{paszke2017automatic} and Pytorch Geometric \citep{fey2019fast} to construct the ranking module. We used ADAM with default parameters as our optimizer. \subsection{Training protocol} As mentioned in the main paper, we train the RL and SL by generating random networks and initializing each network by selecting for each instance a random subset of $m_{0}$ infected nodes. We propagate the epidemic until it spans at least $i_0$ infected nodes (for at least $t_0$ steps), and randomly detect a subset of the infected nodes of size $k_0<i_0$. At each step, in all algorithms but RL, we pick the top $k$ rated nodes. Each of these nodes is tested, and if detected is positive it is effectively removed from the graph. Otherwise, it is not modified. In RL, we perform the same procedure during the evaluation phase, while during training we sample $k$ nodes using the score-to-probability distribution. Each model was training for at most 1500 episodes, but usually, training was completed after 1000 episodes. Each episode contained 1024 steps, collected by 4 different workers. As our network contains a recurrent module, we propagate each sample in the buffer for three steps, in a similar fashion to R2D2. For each setup we described, at least three models were trained using different seeds, and the results are the average over the performance of all models. The errors are the standard deviation of the mean. over at least 100 evaluation episodes for each model. Each episode lasted for 25 steps, each corresponds conceptually to a day. The transition time from the latent to the infectious state was normally distributed with a mean of two steps and a standard deviation of 1 step, corresponding to real-world values. The advantage was calculated using the Generalized Advantage framework with parameters $\gamma=0.99,\lambda=0.97.$ Table \ref{table:parameters} presents the simulation parameters used in the main paper. We shall make the repository and code available online. \begin{table} \centering \begin{tabular}{|l|c|} \hline minimal \#propagation steps ($t_{0}$) & 4\\ \hline \multirow{3}{*}{minimal \#infected component size ($i_{0}$)} & communities: 4 (same community)\\ \cline{2-2} & preferential attachment: 5\%\\ \cline{2-2} & contact tracing: 7\%\\ \hline Learning rate & $3\cdot10^{-4}$\\ \hline $\lambda$ & 0.97\\ \hline $\gamma$ & 0.99\\ \hline Entropy loss weight & 0.01\\ \hline Value loss weight & 0.5\\ \hline Batch size & 256 (128 if \#nodes>200)\\ \hline 3-communites SBM matrix & $\left(\begin{array}{ccc} 0.6 & 0.001 & 0\\ 0.001 & 0.6 & 0.001\\ 0 & 0.001 & 0.6 \end{array}\right)$\\ \hline 2-communites SBM matrix & $\left(\begin{array}{cc} 0.6 & 0.0022\\ 0.0022 & 0.6 \end{array}\right)$\\ \hline \end{tabular} \caption{Parameters table} \label{table:parameters} \end{table} \section{Complex Network datasets} \subsection{Community-based graphs} The Stochastic Block Model (SBM) is defined by (1) A partition of nodes to $m$ disjoint communities $C_{i}$, $i=1\dots m$; and (2) a matrix $P$ of size $m\times m$, which represents the edge probabilities between nodes in different communities, namely, the matrix entry $P_{i,j}$ determines the probability of an edge $(v,v')$ between $v\in C_{i}$ and $v'\in C_{j}$. The diagonal elements in $P$ are often much larger than the off-diagonal elements, representing the dense connectivity in a community, compared to the intra-connectivity between communities. \begin{figure} \centering \begin{tabular}{cc} \includegraphics[width=0.5\columnwidth]{figs/fig1}& \includegraphics[width=0.5\columnwidth]{figs/fig2}\\ (a) & (b) \end{tabular} \caption{Statistics of a real-world contact-tracing graph. (a) The empirical transition probability $P(p_e)$ on a contact tracing network and our suggested curve fit. (b) The degree distribution on the contact tracing network, along with its fit.} \label{fig:transmission_prob} \end{figure} \subsection{Contact-tracing graphs} We used anonymized information about a real-world contact tracing effort collected by the health authorities of our country. Fig. \ref{fig:transmission_prob}(a) presents the degree distribution in this data, and the transmission probability is presented in Fig. \ref{fig:transmission_prob}(b). The latter was derived based on the contact properties, such as the length and the proximity of the interaction. On average, $1.635\pm0.211$ interactions with a significant transmission probability were recorded per-person per-day. We generated random networks based on these distributions using a configuration model framework \citep{Newman2010a}. The fitted model for the degree distribution is a mixture of a Gaussian and a power-law distribution \begin{align} P(degree=x)=0.47\cdot\mathcal{N}(0.41,0.036)+0.53\cdot Beta(5.05,20.02). \end{align} The fitted model for the transmission probability is a mixture of a Gaussian and a Beta distribution \begin{align} P(p_{e}=x)=2.68\cdot\mathcal{N}(-4.44,11.18)+3.2\cdot10^{-3}\cdot x^{-0.36}. \end{align} \section{The rational behind out RL Framework} Since the action space is combinatorial and huge, action-value methods are prohibitively hard to learn. Instead, we pose the problem as a ranking problem. Our models process the partial observation $$O(t)=\left\{ P(t=0),\left\{ G(t')|t'<t\right\} ,\left\{ T(t')|t'<t\right\} \right\},$$ and output a score over $k$ nodes. During inference, we select the top-$k$ highest score nodes. During training, we convert the score to probabilities using a score-to-probability mapping, and sample $k$ nodes from the resulting probability distribution. \section{The tree model} We describe here our tree model baseline (algorithm \#1). This baseline assumes that the underlying network is a tree. In this case, we can analytically solve for the probability a node is infected, given that the root of the tree was infected at time $t_0$. Our goal is to calculate the probability that each node $j$ will be infected \[ \Pr\left(ST_{j}(T)\in\left\{ \mathcal{I},\mathcal{L}\right\} \right) \] We start with a simple case. \subsection{Simple case: No latent state} Let us first consider a simple model in which the epidemic spreads on a tree like structure with a single epidemic source, a.k.a. patient-zero, as the root. For now, let us assume there is no latent state. For every node $j$ there is a single path from the node to the root, which we shall denote as node $r$. Let us assume the path follows $\{y_{0}=r,y_{1},y_{2},..y_{n-1},y_{n}=j\}$. Assume that a sequence of interaction between node $y_{n}$ and $y_{n-1}$ happened during $[0,T]$ at discrete times $(t_{1},t_{2},...t_{m})$, and each interaction is characterized by an infection probability $(p_{1},p_{2},...p_{m})$. We shall evaluate the expression: \[ F_{n}(T)=\Pr\left(ST_{n}(T)=\mathcal{\mathcal{I}}|ST_{r}(0)=\mathcal{I}\right) \] by induction. For abbreviation, we shall write $ST_{y_{i}}(t)=Y_{i}(t)$ and denote the event $ST_{r}(0)=\mathcal{I}$ as $A$. This can analytically calculated using dynamic programming. In short, the state of node $n$ at the time of interaction $m$ is a function of its state at penultimate interaction time $F_{n}(t_{m-1})$, the interaction transmission probability $p_{m}$, and the predecessor node $n-1$ state at time $m$, $F_{n}(t_{m-1})$. \begin{align*} F_{n}(t_{m}) & =F_{n}(t_{m-1})+p_{m}\left(F_{n-1}(t_{m})-F_{n}(t_{m-1})\right)\\ & =p_{m}F_{n-1}(t_{m})+F_{n}(t_{m-1})\left(1-p_{m}\right) \end{align*} The first term is the probability to get infected at the $m$ interaction, and the second term is the probability to get infected before hand. We set $\Pr\left(Y_{n-}(t_{m})=\mathcal{\mathcal{I}}|A\right)$ We can write the conditional probability using the graphical model decomposition and obtain \begin{align} & \Pr\left(Y_{n}(T)=\mathcal{\mathcal{I}}|A\right) = & \nonumber \\ & \Pr\left(Y_{n}(t_{m})=\mathcal{\mathcal{I}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right)\Pr\left(Y_{n-1}(t_{m})=\mathcal{\mathcal{I}}|A\right) =& \label{eq:conditional on previous}\\ & \Pr\left(Y_{n}(t_{m})=\mathcal{\mathcal{I}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right)F_{n-1}(t_{m})\nonumber \end{align} since if the ancestor node is not in an infectious state, the decedent can not be infected. Denote the indicator that interaction $l$ was able to transmit the epidemic as $I_{l}$. We have, \begin{align*} & \Pr\left(Y_{n}(t_{m})=\mathcal{\mathcal{I}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right) & =\\ & \sum_{l=1}^{m}\Pr\left(\text{\ensuremath{y_{n}}'s infection time is \ensuremath{t_{l}}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right) & =\\ & \sum_{l=1}^{m}\Pr\left(Y_{n}(t_{l-1})=\mathcal{H},I_{l},Y_{n-1}(t_{l})=\mathcal{\mathcal{I}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right) \end{align*} As, for an infection event to take place at it must be that node $y_{n-1}$ was infected at $t_{l}$, node $y_{n}$ was healthy beforehand, and that the interaction resulted in an infection. We can now write this as \begin{align} & \Pr\left(Y_{n}(t_{l-1})=\mathcal{H},I_{l},Y_{n-1}(t_{l})=\mathcal{\mathcal{I}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right) & =\nonumber \\ & p_{l}\Pr\left(Y_{n}(t_{l-1})=\mathcal{H},Y_{n-1}(t_{l})=\mathcal{\mathcal{I}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right) & =\nonumber \\ & p_{l}\Pr\left(Y_{n}(t_{l-1})=\mathcal{H},Y_{n-1}(t_{m})=\mathcal{\mathcal{I}}|Y_{n-1}(t_{l})=\mathcal{\mathcal{I}},A\right)\frac{\Pr\left(Y_{n-1}(t_{l})=\mathcal{\mathcal{I}}|A\right)}{\Pr\left(Y_{n-1}(t_{m})=\mathcal{\mathcal{I}}|A\right)} & =\label{eq:time-shift}\\ & p_{l}\Pr\left(Y_{n}(t_{l-1})=\mathcal{H}|Y_{n-1}(t_{l})=\mathcal{I},A\right)\frac{F_{n-1}(t_{l})}{F_{n-1}(t_{m})} & =\nonumber \\ & p_{l}\left(1-\Pr\left(Y_{n}(t_{l-1})=\mathcal{I}|Y_{n-1}(t_{l})=\mathcal{I},A\right)\right)\frac{F_{n-1}(t_{l})}{F_{n-1}(t_{m})}\nonumber \end{align} The transition from the first line to the second is due to the independence of the interaction infection probability with the history of the participating parties. The third line is simple Bayes' theorem. If a node is infected at time $t_{l}$, it will be infected later on at $t_{m}$, as expressed in line 4. The last line is the complete probability formula. We can rewrite $\Pr\left(Y_{n}(t_{l-1})=\mathcal{I}|Y_{n-1}(t_{l})=\mathcal{I},A\right)$ as \begin{align*} & \Pr\left(Y_{n}(t_{l-1})=\mathcal{I}|Y_{n-1}(t_{l})=\mathcal{I},A\right) =& \\ & \frac{\Pr\left(Y_{n}(t_{l-1})=\mathcal{I}|A\right)-\Pr\left(Y_{n}(t_{l-1})=\mathcal{I},Y_{n-1}(t_{l})=\mathcal{H}|A\right)}{\Pr\left(Y_{n-1}(t_{l})=\mathcal{I}|A\right)} = & \\ & \frac{\Pr\left(Y_{n}(t_{l-1})=\mathcal{I}|A\right)}{\Pr\left(Y_{n-1}(t_{l})=\mathcal{I}|A\right)} =& \\ & \frac{F_{n}(t_{l-1})}{F_{n-1}(t_{l})} \end{align*} The transition from the first line to the second line is a complete probability transition. The third line is due to the fact that is $y_{n-1}$ was not infected at time $t_{l}$, clearly $y_{n}$ could not be infected before $t_{l}$. We have \begin{align*} F_{n}(t_{m})=\Pr\left(Y_{n-1}(t_{m})=\mathcal{\mathcal{I}}|A\right) & =\sum_{l=1}^{m}p_{l}\left(1-\frac{F_{n}(t_{l-1})}{F_{n-1}(t_{l})}\right)\frac{F_{n-1}(t_{l})}{F_{n-1}(t_{m})}F_{n-1}(t_{m})\\ & =\sum_{l=1}^{m}p_{l}\left(F_{n-1}(t_{l})-F_{n}(t_{l-1})\right) \end{align*} Therefore, given $F_{n-1}(t_{l})$ for all $l\in\{1..n-1\}$ and $F_{n}(t_{l})$ for all $l\in\{1..n\}$, we can directly calculate the infection probabilities, given the initial condition: $F_{i}(0)=\delta_{i,0}$. We can write the partial density function of $F_{i}(t_{l})$ as $f_{i}(t_{l}) = F_{i}(t_{l})-F_{i}(t_{l-1})$, and obtain: $ f_{n}(t_{m}) = p_{m}\left(F_{n-1}(t_{m})-F_{n}(t_{m-1})\right)$. This allows us to write this with an intuitive formulation \begin{align*} F_{n}(t_{m}) & =F_{n}(t_{m-1})+p_{m}\left(F_{n-1}(t_{m})-F_{n}(t_{m-1})\right)\\ & =p_{m}F_{n-1}(t_{m})+F_{n}(t_{m-1})\left(1-p_{m}\right) \end{align*} The first term is the probability to get infected at the $m$ interaction, and the second term is the probability to get infected before hand. \subsection{Full analysis with latent states} The main difference is that the complement of the infectious state is composed of two states, healthy $\mathcal{H}$, latent $\mathcal{L}$. We shall designated all the non-infecting states as $\mathcal{H}^{+}=\{\mathcal{\mathcal{H}},\mathcal{L}\}$ and all the infected states as $\mathcal{I}^{+}=\{\mathcal{\mathcal{I}},\mathcal{L}\}$, and sometime abuse the notation by writing $S_{i}(t)=\mathcal{H}^{+}$. The transmission from the latent to infectious state follows is a random variable $L(\tau)$. As before, we are interested in the probability that \[ \Pr\left(Y_{n}(T)=\mathcal{\mathcal{I}^{+}}|S_{r}(0)=\mathcal{I}\right) \] The derivation below shows that, similar to the previous case, we can solve for this probability using dynamic programming. We have \begin{align*} \Pr\left(Y_{n}(T)=\mathcal{\mathcal{I}^{+}}|ST_{r}(0)=\mathcal{I}\right) & =\sum_{l=1}^{m}p_{l}\left(F_{n-1}(t_{l})-F_{n}(t_{l-1})-\Pr\left(Y_{n}(t_{l-1})=\mathcal{L}|A\right)\right) \end{align*} with $\Pr\left(Y_{n}(t_{l}) = \mathcal{L}|A\right)=\sum_{t_{i}<t_{l}}\left(1-L(t_{i}-t_{l})\right)q_{n}(t_{i})$, and $ q_{n}(t_{m}) = p_{m}\left(F_{n-1}(t_{m})-F_{n}(t_{m-1})-\Pr\left(Y_{n}(t_{l-1})=\mathcal{L}|A\right)\right)$. Therefore, as before, given $F_{n-1}(t_{m})$ and $q_{n}(t_{i})$ for all $i<m$, we can propagate and calculate $q_{n}(t_{m})$ and $F_{n}(t_{m})$. The modified Eq. \ref{eq:conditional on previous} is \begin{align*} & \Pr\left(Y_{n}(T)=\mathcal{\mathcal{I^{+}}}|A\right) =&\\ & \Pr\left(Y_{n}(t_{m})=\mathcal{\mathcal{\mathcal{I^{+}}}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right)\Pr\left(Y_{n-1}(t_{m})=\mathcal{\mathcal{I}}|A\right) =&\\ & \Pr\left(Y_{n}(t_{m})=\mathcal{I^{+}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right)F_{n-1}(t_{m}) & \end{align*} where we kept the definition of $F_{j}(t)$. Therefore, almost identically, \begin{align*} & \Pr\left(Y_{n}(t_{m})=\mathcal{\mathcal{I^{+}}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right) =& \\ & \sum_{l=1}^{m}\Pr\left(\text{\ensuremath{y_{n}}'s infection time is \ensuremath{t_{l}}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right) =&\\ &\sum_{l=1}^{m}\Pr\left(Y_{n}(t_{l-1})=\mathcal{H},I_{l},Y_{n-1}(t_{l})=\mathcal{\mathcal{I}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right) & \end{align*} So Eq. \ref{eq:time-shift} follows up to the last line, where: \begin{align*} & \Pr\left(Y_{n}(t_{l-1})=\mathcal{H},I_{l},Y_{n-1}(t_{l})=\mathcal{\mathcal{I}}|Y_{n-1}(t_{m})=\mathcal{\mathcal{I}},A\right) =&\\ & p_{l}\Pr\left(Y_{n}(t_{l-1})=\mathcal{H}|Y_{n-1}(t_{l})=\mathcal{I},A\right)\frac{F_{n-1}(t_{l})}{f_{n-1}(t_{m})} =&\\ & p_{l}\left(1-\Pr\left(Y_{n}(t_{l-1})=\mathcal{I^{+}}|Y_{n-1}(t_{l})=\mathcal{I},A\right)\right)\frac{F_{n-1}(t_{l})}{F_{n-1}(t_{m})} & \end{align*} and, \begin{align*} &\Pr\left(Y_{n}(t_{l-1})=\mathcal{I^{+}}|Y_{n-1}(t_{l})=\mathcal{I},A\right) =&\\ & \frac{\Pr\left(Y_{n}(t_{l-1})=\mathcal{I^{+}}|A\right)-\Pr\left(Y_{n}(t_{l-1})=\mathcal{I},Y_{n-1}(t_{l})=\mathcal{H^{+}}|A\right)}{\Pr\left(Y_{n-1}(t_{l})=\mathcal{I}|A\right)} =&\\ & \frac{\Pr\left(Y_{n}(t_{l-1})=\mathcal{I}^{+}|A\right)}{\Pr\left(Y_{n-1}(t_{l})=\mathcal{I}|A\right)} =&\\ & \frac{\Pr\left(Y_{n}(t_{l-1})=\mathcal{I}^{+}|A\right)}{F_{n-1}(t_{l} )} \end{align*} To summarize, we obtain: \begin{align*} \Pr\left(Y_{n}(T)=\mathcal{\mathcal{I}^{+}}|S_{r}(0)=\mathcal{I}\right) & =\sum_{l=1}^{m}p_{l}\left(1-\frac{\Pr\left(Y_{n}(t_{l-1})=\mathcal{I}^{+}|A\right)}{F_{n-1}(t_{l})}\right)\frac{F_{n-1}(t_{l})}{F_{n-1}(t_{m})}F_{n-1}(t_{m})\\ & =\sum_{l=1}^{m}p_{l}\left(F_{n-1}(t_{l})-\Pr\left(Y_{n}(t_{l-1})=\mathcal{I}^{+}|A\right)\right)\\ & =\sum_{l=1}^{m}p_{l}\left(F_{n-1}(t_{l})-F_{n}(t_{l-1})-\Pr\left(Y_{n}(t_{l-1})=\mathcal{L}|A\right)\right) \end{align*} Let us denote the partial density function that an infection occurred during interaction $m$ as $ q_{n}(t_{m}) = \Pr\left(Y_{n}(t_{m}) = \mathcal{I}^{+}|A\right)-\Pr\left(Y_{n}(t_{m-1}) = \mathcal{I}^{+}|A\right)$. We have, \begin{align*} q_{n}(t_{m}) = p_{m}\left(F_{n-1}(t_{m})-F_{n}(t_{m-1})-\Pr\left(Y_{n}(t_{l-1}) = \mathcal{L}|A\right)\right). \end{align*} The transition from the latent state to the infected state follows: $ F_{n}(t_{l}) = \Pr\left(Y_{n}(t_{l}) = \mathcal{I}|A\right) = \sum_{t_{i}<t_{l}}L(t_{i}-t_{l})q_{n}(t_{i})$, while $ \Pr\left(Y_{n}(t_{l}) = \mathcal{L}|A\right) = \sum_{t_{i}<t_{l}}\left(1-L(t_{i}-t_{l})\right)q_{n}(t_{i})$. Therefore, given $F_{n-1}(t_{m})$ and $q_{n}(t_{i})$ for all $i<m$, we can propagate and calculate $q_{n}(t_{m})$ and $F_{n}(t_{m})$. \bibliographystyle{aaai21} \section{Introduction} Consider the problem of an epidemic spreading in the population, without any known cure or vaccination procedure. To contain the disease and prevent it from spreading, it becomes critical to detect infected carriers and isolate them; see Fig.~\ref{fig:viralinfection} for an illustration. As the epidemic spreads, the demand for tests outgrows their availability, and not all potential carriers can be tested. It becomes necessary to identify the most likely epidemic carriers using limited testing resources. This raises a major question: How can we rank candidates and prioritize testing to prevent the disease from spreading? This prioritization problem is an important example of a family of problems: learning to control diffusive processes over networks through nodal interventions. Other examples include opinions spreading on social network, product adaption, viruses inflicting computer networks and cascades of failures in server farms. In all these cases, the dynamics of the system can be steered using interventions that modify the states of a (relatively) small number of nodes. For instance, infected people can be asked to self-quarantine, preventing the spread of a disease, at-risk computers can be patched by security updates, and users may be selected and be exposed to new information to influence their opinion. \begin{figure}[t] \centering \includegraphics[width=0.60\columnwidth]{figs/RL_graphs_fig1_trimmed.png} \caption{A viral infection process on a graph and an intervention aimed to stop its spread. Here, graph nodes represent people and edges represent interactions. At $t=1$ only two people are infected (red). At $t=2$ several interactions resulted in new \textit{exposed} people (yellow); At $t=3$ the blue node was selected to be quarantined to stop the viral spread. This paper presents a framework for learning how to select which nodes should be quarantined. }\label{fig:viralinfection} \end{figure} The problem of controlling the dynamics of a system using localized interventions is very hard, and for several reasons. First, it requires to make decision in a continuously changing environment with complex dependencies. Second, to solve the problem one must assess the potential downstream ripple effect for any specific node that becomes infected, and balance it with the probability that the node indeed becomes infected. Finally, models must handle noise and partial observability. We pose the problem of controlling a diffusive process on a temporally evolving graph as a sequential decision making problem in the context of a partially-observed Markov decision process. We then formulate the problem of selecting a subset of nodes for dynamical intervention as a {\em ranking } problem, and design an actor-critic RL algorithm to solve it. We use the observed changes of nodes states and connections to construct a temporal multi-graph, which has time-stamped interactions over edges, and describe a deep architecture based on GNNs to process it. To the best of our knowledge, this work is the first work that consider Deep RL in the context of a temporally evolving graph. \eli{ The current work combines three research fields: dynamic processes on temporal graphs, deep graph learning and reinforcement learning. Combining these three into a cohesive model raises several new challenges. Most importantly, the model must learn to handle two types of dynamics: learn to infer the potential risk of not removing a node, and learn to predict the probability that a node becomes infected. As explained below, these two processes operate on different time scales. To address this issue, our architecture contains two separate GNN modules, taking as input a multi-graph over the nodes, where edges are time-stamped with the time of interactions. Also, we show below that combining RL with temporal graphs requires to stabilize how information is aggregated from neighbors when updating nodes hidden states, and control how actions are sampled during training to ensure sufficient exploration. We show empirically the beneficial effects of these components. This paper demonstrates that combining RL with GNNs provides a powerful approach for controlling spreading processes on graphs. In the context of COVID-19 spread, we show that using the RL-GNN approach increases the fraction of healthy by $25\%$ and allows for confining the spread of an epidemic $30\%$ more often, and $3\times$ times more often that using non-learned approaches. ~\newline This paper makes the following contributions:\\ {\bf (1)}~A new framework for controlling the dynamics of diffusive processes over graphs. Namely, learning to perform local interventions to steer the global dynamics of a graph-based dynamical system. \\ {\bf (2)}~A new architecture for this problem, and a way to train a decision-making agent using reinforcement learning to prioritize interventions on the temporal multi-graph. \\ {\bf (3)}~An observation of the interplay between the dynamics of graph states and how information flows over the graph for a decision making agent, which motivates the design of our deep network architecture. \\ {\bf (4)}~A set of benchmarks and strong baselines for this problem. This includes statistics collected from real-world contact tracing data for COVID-19. Our RL approach achieves superior performance over these datasets, often significantly. \section{Previous work} Our work is in the intersection of a few disciplines. We tackle the problem of \emph{controlling a dynamic process} by considering it as \emph{ranking problem on a temporal graph}. As a particular example, we address the problem of a controlling a viral epidemic spreading on a social graph. \textbf{Deep Learning on graphs.} Graph neural networks (GNNs) are deep neural networks that can process graph-structured data. GNNs became very popular and were shown useful for solving a variety of tasks including social network analysis \cite{kipf,fan2019graph} and molecule property prediction \cite{Gilmer2017,Duvenaud2015}. Perhaps the most popular GNN models are Message Passing Neural Networks (MPNN) \cite{Gilmer2017, Hamilton2017, Velickovic2017}, which operate by repeatedly updating the feature vector of each node by aggregating information from its neighbourhood. Several works combine recurrent mechanisms with GNNs to learn temporal graph data, e.g., \cite{guo2019attention, zhao2019t, fang2019gstnet,yu2017spatio} tackled the traffic forecasting problem . \cite{li2019study,kapoor2020examining} proposed a graph-structured RNN for coarse spatial prediction of epidemic spread. Unlike this work, these works model the epidemic spread and do not try to intervene with the diffusive process. More generally, several recent studies \cite{liu2019towards, rossi2020temporal, liu2020towards, pareja2020evolvegcn} tackle a setup in which both nodes and edges vary over time, with applications in social network analysis and other fields. Further information can be found in \cite{kazemi2020representation}. \textbf{Ranking on graphs.} The problem of ranking on graphs is a fundamental problem in Computer Science, in which the task is to rank the nodes of a given graph according to some criteria. It has various applications such as web page ranking \cite{page1999pagerank,agarwal2006ranking} and knowledge graph search \cite{xiong2017explicit}. \textbf{Reinforcement learning and graphs.} Recently, a surge of work combining Reinforcement Learning and graphs emerged. These works can be split into two main categories: leveraging graph structure for general RL problems (e.g., \cite{Zhang2018,Jiang2018}), and applying reinforcement learning methods for graph problems. Our work falls into the latter. An important line of work utilizes Reinforcement Learning in order to solve NP-hard combinatorial optimization problems defined on a graph \citep{Zhu,Dai}. Another common application is the usage of RL for path searching in a knowledge graph \citep{xiong2017explicit,Das}. Reinforcement learning was also shown in a few other graph problems, such as chemical reaction prediction \cite{Do2018}. \textbf{Dynamic processes on graphs. } Modelling diffusive processes is an active research field. Key models such as SIR (Suscpetible-Infected-Removed) and SIS (Suscpetible-Infected-Suscpetible) \cite{Newman2010a} to the recent SEIR (Suscpetible-Exposed-Infectious-Removed) COVID-19 epidemic model \cite{Lin2020,Lopez2020} have proven useful in modelling the spread of contagions. The application of these models is extended, and varies from early epidemic detection \cite{Meirom2015}, to influence maximization \cite{Kempe2003} and network security \cite{Gourdin2011}. The control of such processes on graphs was less discussed, and mostly focused on simple networks models and asymptotic results \citep{Tennenholtz2017, Hoffmann2020}. \section{A motivating example} We begin with an example to illustrate the trade-offs of the problem. A natural algorithmic choice would be to act upon nodes that are most likely infected. The following example shows why this approach is suboptimal. We form a time-varying graph from a list of interactions between nodes at various times. If $u,v$ interacted at time $t$ then the edge $(u,v)$ exists at time $t$. Each interaction is characterized by a transmission probability $p_e(t)$. If a node was infected at time $t$ and its neighbor was healthy, then the healthy node is infected with probability $p_e(t)$. \eli {For the purpose of this example, assume }we can test a single node at odd timesteps. If the node is identified as infected, it is sent to quarantine and cannot further interact with other nodes. Otherwise, we do not perturb the dynamics and it may interact freely with its neighbors. Our goal is to minimize the number of infected nodes. Consider the "two stars" network in \figref{fig:toy-example}. The left hub (node $v_1$) has $m_1$ neighbors, and $m_2$ nodes are attached to the right hub $v_2$. At $t=0,$ only the edge $e=(v_{1},v_{2})$ is present with $p_e(t=0)=p$. Then, for all $t\geq1$, all edges depicted in \figref{fig:toy-example} exist with $p_e(t)=1$. Assume that this information is known to the agent, and that at $t=1$ it is revealed that node $v_{1}$ was infected at $t=0$. In this example, we clearly should test either $v_{1}$ or $v_{2}$. We can compute the expected cost of each option exactly. \textbf{Alternative I:} Test ${v_2}$. With probability $p$, $v_{2}$ becomes infected at $t=1$, and we block the epidemic from spreading. However, we forfeit protecting $v_{1}$ neighbors, as all of them will be infected in the next step. With probability $1\!-\!p$ test is negative, and we fail to affect the dynamics. At $t=2$ node $v_{2}$ will get infected and at $t=3$ all of $v_{2}$'s neighbors become infected too, ending up with a total of $\left(m_{2}+1\right)$ infections. The expected cost in choosing to test $v_{2}$ is $(1-p)\cdot m_{2}+m_{1}$. \textbf{Alternative II:} Test $v_{1}$. We block the spread to $v_{1}$'s neighbors, but sacrifice all $m_{2}$ neighbors of $v_{2}$ with probability $p$. The expected cost in choosing $v_2$ is $p\cdot m_{2}$. The decision would therefore be to test for $v_{2}$ if $2p\geq1+m_{1}/m_{2}$. This example illustrates that an optimal policy must balance two factors: \emph{the probability that the dynamics is affected} - that a test action yields a ``positive", and the future consequences of our action - the \emph{strategic importance} of selecting\emph{ $v_{1}$ vs. $v_{2}$}, expressed by the ratio $m_{1}/m_{2}$. A policy targeting likely-infected nodes will always pick node $v_1$, but since it only focuses on the first term and ignores the second term, it is clearly suboptimal. \begin{figure} \begin{minipage}[c]{0.4\columnwidth} \includegraphics[width=0.9\columnwidth]{figs/toy_example.png} \end{minipage} \hfill \begin{minipage}[c]{0.5\columnwidth} \caption{ A double star configuration. The state of $v_{2}$ is unknown at the $t=1$. $v_1$ is infected at $t=0$.} \label{fig:toy-example} \end{minipage} \end{figure} An immediate question arise: How can we develop methods that address both terms? It is difficult to measure the strategic importance of a node in a large dynamical process with constant external interventions directly. Instead, one may use simulations and try to learn from the collected experience and the interplay between dynamics and actions a method that finds the optimal policy end-to-end and internally weighs the two terms optimally. This calls for a reinforcement learning framework. \begin{figure}[t] \centering \includegraphics[width=0.7\columnwidth]{figs/RL_graphs_fig2.png} \caption{Schematic of our approach. The Ranking module receives as input a sequence of graphs and outputs scores over nodes. Scores are then used to sample actions, selecting nodes for intervention. Here, the person circled in blue is selected for quarantine and its connections are cancelled (dashed blue lines). The downstream effect on epidemic progression is then fed as a loss to the ranking module.} \label{fig:Approachsechematics} \end{figure} \section{Problem Formulation} \label{sec:problem_formulation} We first discuss the general framework, and then present a concrete example focusing on the spread of epidemics. \secref{sec:extensions} provides additional use cases and applications of the general framework. Consider a diffusive process on a temporal graph $G(t)=(\mathcal{V},\mathcal{E}(t))$ whose structure changes in time. $\mathcal{V}$ is the set of nodes and $\mathcal{E}(t)=\{e_{uv}(t)\}$ is the set of edges at time step $t$. An edge $(u,v)$ between two nodes exists at time $t$ iff the two nodes interacted at time $t$. Each edge $e_{uv}(t)$ is associated with features $\phi_{uv}(t)$ which may vary in time, and each node $v$ is characterized with features $\zeta_{v}(t)$. The state of a node $v\in\mathcal{V}$ is a random variable $ST_v(t)$ which can have values in $\mathcal{Y}=\{y_{1},y_{2},..\}$. The node's state $ST_v(t)$ depends on the interactions between $v$ and its neighbors at time $t$ and on the state of those neighbors, We aggregate all neighborhood information to a random variable $$N_{v}(t)=\left\{ \left(\phi_{vu}(t),\zeta_{u}(t),ST_u(t)(t-1)\right)|u,e_{vu}\in\mathcal{E}(t)\right\} .$$ Additionally, $ST_v(t)$ depends on the previous state $ST_v(t-1)$ and on node features. In other words, \[ ST_v(t)=f\left(ST_v(t-1),\zeta_{v}(t),N_{v}(t)\right). \] At each step, we may select a subset $A(t)$ of $k$ nodes, and change the state of any selected node $v\in A(t)$. Selecting nodes and setting their states defines the space of actions for the agent, and plays the role of a knob for controlling the global dynamics of the process over the graph. Formally we apply a transformation $h(\cdot)$ on node $v$, setting $ST_v(t)=h\left(ST_v(t)\right),\forall v\in A(t)$. The optimization objective should be invariant to permuting (relabeling) of the nodes. We assume it depends only on the total number of nodes in state $i$, $c_{i}(t)=\sum_{v}\mathbb{I}_{SV(t)=s_{i}}$, where $I$ is the indicator function. The objective is therefore of the form \[ \sum_{t,v\in\mathcal{V}}\gamma^{t-t_{0}}g(c_{1}(t),c_{2}(t),..), \] where future evaluation are weighted by a discount factor $\gamma \le 1$. Additionally, the agent may be subject to constraints written in a similar manner $\sum_{i}f_{i}(c_{1}(t),c_{2}(t),..)\geq y_{i}(t)$. \subsection{Epidemic test prioritization} We consider the recent COVID-19 outbreak that spreads through social contacts. The temporal graph $G$ is defined over a group of people $\mathcal{V}$, and its edges $\mathcal{E}(t)$ are determined by their daily social interactions. Each of these interactions is characterized by various features, including its duration, distancing and environment (indoors or outdoors). \textbf{The SEIR model}. We follow the widely-used SEIR model \cite{Lopez2020}. Every node (person) can be in one of the following states, $\mathcal{Y}={S, L, I, R}$, namely: \textit{susceptible} -- a healthy, yet uninfected person, \textit{exposed/latent} -- infected but cannot infect others, \textit{infectious} -- may infect other nodes, or \textit{removed/recovered} -- self-quarantined and removed from the graph . \textbf{Node state dynamics}. In our model, a healthy node can become infected with a probability that depends on its interactions with its neighbors. Once infected, transitioning from \textit{Exposed/Latent} to \textit{Infected} is defined by a probabilistic process. A node becomes \textit{Removed} if it is selected for self-quarantine (tests positive); see Fig.~\ref{fig:viralinfection} for an illustration. Formally, let $\mathcal{I}(t)\subset V$ be the set of infectious nodes at time $t$, and similarly $\mathcal{L}(t)$, $\mathcal{R}(t)$ and $\mathcal{S}(t)$ be the sets of latent(exposed), removed and susceptible (healthy) nodes. Each edge that is active at time $t$, $e\in\mathcal{E}(t)$, carries a transmission probability $p_{e}(t)$. Denote the set of impinging edges on node $v$ with an infectious counterpart at time $t$ by $E_{v}(t)=\left\{ e\in\mathcal{E}(t)|e=(v,u),SV_u(t-1)=I\right\} .$ The probability of a healthy node to remain healthy at time $t$ is $1-\prod_{e\in E_{v}(t)}\left(1-p_{e}(t)\right)$, otherwise it becomes infected, but still in a latent state. We denote the time of infection of node $v$ as $T_{v}.$ A node in a latent state will stay in this state at time $t$ if $t<T_{v}+D_{v}$, where $D_{v}$ is a RV representing the latency period length, otherwise its state changes to infectious. The testing intervention $h(\cdot)$ changes the state of a node. If infected or exposed, its state is set to $R$, otherwise it remains as it is. \textbf{Optimization goal and action space.} The objective is to minimize the spread of the epidemic, namely, minimize the number of infected people over time, $\mathbb{I}_{ST_v(t)\in\{L,D\}}$. Assuming that testing is limited to a fixed capacity of $k$ tests per day, the optimization goal becomes $ \min\sum_{t,v}\gamma^{t}\mathbb{I}_{ST_v(t)\in\{L,D\}}, $ where $\gamma\in(0,1]$ is a discount factor representing the relative importance of the future compared to the present. We used $\gamma=0.99$ throughout the paper. Of course, this is but one particular optimization goal and other goals that weigh different states differently, or add additional aspects are possible. The action space consists of all possible selections of a subset of $k$ nodes $\mathcal{T}_{t}\subset V$. Even for moderate graph, with $\sim100-1000$ and small $k$ the action space ${k \choose |\mathcal{V}|}$ is huge. \textbf{Observation space.} At each time $t$, the agent is exposed to all past interactions between network nodes $\left\{ \mathcal{E}(t')|t'<t\right\} $. In addition, we are given partial information on the nodes state. The agent is provided with information on a subset of the infectious nodes at $t=0$. At every $t>0$, the agent observes all past test results. Formally, for every $v\in a(t)$ we observe if $ST_v(t)\in\mathcal{I}(t)\cup\mathcal{L}(t) $ or not. \section{Approach} \label{sec:approach} Our approach is depicted in Figure \ref{fig:Approachsechematics}. The RL agent receives as input the node and edge features of the temporal graph, and processes them using its ranking module. A probability distribution over graph nodes is generated from the ranking module’s scores, and the agent samples a subset of $k$ nodes for testing. Namely, the scores encode the agent's policy. We use Proximal Policy Optimization algorithm (PPO, \cite{Schulman2017}) as to optimize our agent. We sequentially apply the suggested action, log the (state, action) tuple in an experience replay buffer, and train our model based on the PPO loss term. Next, we describe the ranking module and sampling procedure. \subsection{RL Agent Ranking Module} \label{sec:ranking_module} \paragraph{Overview} Our GNN-RNN module serves to update the internal representation of a node $v$, denoted $h_v(t)$, and its score $s_v(t)$ (\figref{fig:ranking}). This score is later used for selecting nodes to be acted on. The ranking module is applied in a recurrent fashion at each time step. The ranking module contains two GNNs: (1) $E$, which updates the epidemic state, and (2) $I$, which updates the information state. It also contains two other networks, $G$ and $F$, which update node representations and node scores by using the epidemic state and information state as well as the previous node representations. \textbf{Input.} The input to the ranking module consists of three feature types (See \figref{fig:ranking}): (1) \textit{Static node features} $\zeta^s_v(t)$: topological graph centralities (betweeness, closeness, eigenvector and degree centralities) and random node features. (2) \textit{Dynamic node features} $\zeta^d_v(t)$ : All test results that were performed up the current timestamp (including positive and negative test results). We denote all nodes features as a concatenation $\zeta_v(t)=[\zeta^s_v(t),\zeta^d_v(t)]$. (3) \textit{Edge features} and the structure of the temporal graph $\mathcal{E}(t)$: All previous interactions up to the current step, including the transmission probability for each interaction. Figure \ref{fig:ranking} illustrates the basic data flow in the ranking module. \begin{figure}[t] \centering \includegraphics[width=0.7\columnwidth]{figs/RL_graphs_fig3.png} \caption{Block diagram of our suggested ranking module. It is composed of 4 neural networks $I$,$E$,$G$,$F$, which update the nodes scores and hidden states at each time step.} \label{fig:ranking} \end{figure} \textbf{Epidemic GNN.} The spread of epidemic through point contact is modeled by a GNN $E$. As the epidemic cannot spread by more than one hop per step, it is sufficient to model the spread with a single GNN layer. Formally, denote by $p_{vu}$ the probability of transmission during the interaction between $(v,u)$ at time $t$. For each $v$, the output of $E(\cdot)$ is a feature vector denoted by $e_v(t)$: \begin{align*} e_{v}(t) & =\sum_{u\sim_{t}v}p_{vv'}(t)\cdot M_{e}(\zeta_{v}(t),\zeta_{v'}(t);\theta_{m_e}), \end{align*} where $M$ is multilayer perceptron (MLP). \textbf{Information GNN.} The score of a node is affected both by the propagation dynamics, and by the information available to the agent. One may hope that since the former has a known timescale (days), on a short time scale (single day) the score of node would only be affected by its neighboring nodes. This, however, is not the true because information can propagate long distance in the graph almost instantaneously. As a simple example, consider nodes in a connected chain of (untested) nodes and note that they are statistically dependent. As a result, revealing the state of one node immediately affects the distribution over all nodes in the chain. With this consideration in mind, we designed an \textit{information GNN}, $I$, which represents the {\em information state} of each node. As discussed above, updated information on a node $u$ a few hops away from node $v$ may abruptly change our beliefs on the state of $v$. Furthermore, this change may occur even if $v$ and $u$ did not interact in the last time step but rather a while ago. To update the information state, we construct a cumulative multi-graph $G'$ where the set of edges between nodes $v$ and $u$ at time $t$ are all the interactions that occurred during the last $\tau$ steps, $\mathcal{E}_{G'}$=$\cup_{t'\in[t-\tau,t]}\mathcal{E}_{G}(t)$. The features of each edge in $\mathcal{E}_{G'}$, $\phi_{vu}(t')$, are the interaction delay $t-t'$ and the transmission probability $p_{v,v'}(t')$. The information features are the output of $k$-layer GNN; the $l^{th}$ layer is: \[ x_{v}^{l}(t)=\sum_{v'\sim_{t}v}M^{l}(x_v^{l-1}(t),x_{v'}^{l-1}(t),\phi_{vv'\text{\rq}(t)};\theta_M^l). \] As before, $M^l$ is an MLP, with $x_{v}^{0}(t)=\zeta_{v}(t)$ and $x_{v}^{k}(t)=i_{v}(t)$ are the final node features. The value of $\tau$, the information window size, was 7 in all our experiments. \textbf{Score and hidden state update.} For every node we hold a hidden state $h_{v}(t)$, which is updated following \begin{equation} h_{v}(t)=G(h_{v}(t-1),\zeta_{v}(t),e_{v}(t), i_{v}(t) ;\theta_{g}) \end{equation} After updating the new node hidden state, we use them to calculate the node score using a neural network $F$, \begin{equation} s_{v}(t)= F(h_{v}(t),h_{v}(t-1),\zeta_{v}(t);\theta_{f}) \end{equation} Here, $F$ is an MLP, while $G$ can be either an MLP or recurrent module such as GRU. \textbf{Sampling.} Given the score per node $s_v(t)$, we sample without replacement $k$ nodes iteratively. We (1) map the score of $n$ nodes to a probability distribution using a score-to-probability distribution function, (2) sample a node, and (3) adjust the distribution by removing its weight. We repeat this process $k$ iterations. \subsection{Design choices} \textbf{RL framework.} The action space of choosing a subset of $k$ nodes out of $n$ nodes is large even for small $n$ and $k$. Using an action-value approach like Q-learning implies that an approximate value is assigned to every possible action, but the action space size is prohibitively too large for action-value methods. Instead, we use a policy-gradient algorithm and model the problem as a ranking problem. The algorithm learns to rank nodes using a parameterized model, and then uses a sampling procedure to choose a subset of $k$ nodes. Many on-policy gradient algorithms use entropy to define a trust region. Computing the entropy requires summing ${k \choose |\mathcal{V}|}$ terms at each step, and it is computationally expensive. A more scalable solution is the unbiased entropy estimator of \citet{Zhang2018a}, but the variance of that estimator is high. As an alternative, PPO trust region is not based on an explicit evaluation of the entropy, and performed better in our experiments. We also evaluated A2C, which did not perform as well as PPO in our experiments. \textbf{Critic module.} PPO, as an actor-critic algorithm, requires a critic module to estimate the value function in a given state. We construct the actor using an architecture that is similar to the ranking module, but apply to element-wise max operation on the rows (representing the nodes) of the input to the score module $F$ (\figref{fig:ranking}). This reduces $F$'s input to a single row of features, and the output is then a scalar rather than a vector. Importantly, the critic is parametrized by a different set of weights than the ranking module (actor). \textbf{Score-to-probability distribution.} Usually, node scores are converted to a distribution over actions using a softmax. This approach is problematic for our case because node probabilities decay exponentially with their scores, leading to two major drawbacks. It discourages exploration of low-score nodes, and limits sensitivity to the top of the distribution, instead of at the top-k selected. Instead, we define the probability to sample an action $a_{i}$ to be \begin{equation} \Pr(a_{i})=\frac{x_{i}'}{\sum x_{i}'}\quad \textrm{, with } x_{i}'=x_{i}-\min_{i}x_{i}+\epsilon, \label{eq: score-to-prob} \end{equation} where $\{x_{i}\}$ is the set of scores and $\epsilon$ a constant. By not using an exponential as in softmax, the probability differences between low scoring nodes and high scoring nodes become less extreme. Furthermore, the parameter $\epsilon$ controls the initial exploration ratio. In standard DNN initialization schemes (e.g., XAVIER), the initial value of $x_{i}$ is expected to be in [-1,1]. If $\epsilon\gg1$ than the dominant term in \eqref{eq: score-to-prob} is $\epsilon$. This promotes exploration initially, as all actions are likely to be sampled in the early training stages. \textbf{Normalization in scale-free networks.} RNN are well-known to suffer from the problem of exploding or vanishing gradients. This problem is exacerbated in a RNN-GNN framework used for RL algorithms, because they may be applied for arbitrary long episodes, causing internal state to grow unbounded. This problem is particularly severe if the underlying graph contains hubs (highly connected nodes). One approach to alleviate this problem, is by including an RNN like a GRU module, where the hidden state values pass through a sigmoid layer. As the magnitude of the input grows, gradient become smaller and training slows down. Scale-free networks contain with high probability "hub" nodes that have high-degree, namely $O(n)$ neighbors. As a simple case, consider a star graph with a large number of nodes. In a GNN framework, it receives updates from a large number of neighbors and its internal state increases in magnitude. The next time that the GNN module is applied (e.g., at the next RL step), the growing internal state increases the magnitude of the internal state of its neighbors. This leads to a positive-feedback loop that causes the internal state representation to diverge. Since RL algorithms may be applied for arbitrary long periods, the internal state may grow unbounded unless corrected. This problem can be solved by directly normalizing each node hidden state. We have experimented with various normalization methods, and found that $L_2$ normalization worked best, as shown in the next section. \section{Experiments} \subsection{Compared approaches} We compare methods from three categorizes: A) programmed; B) supervised learning (SL) C) Reinforcement learning (RL). Each experiment was performed with at least three random seeds. Additional experimental and implementation details, including network architecture, appear in Appendix \ref{sec:experimental details}. \textbf{A. Programmed baselines.} Most countries currently prioritize their testing based on fixed procedures determined in advance and not learned form data. We compare with two such methods to rank nodes. \textbf{(1) Infected neighbors.} Rank nodes based on the number of known infected nodes in their 2-hop neighborhood (neighbors and their neighbors). Each node $v$ is assigned a tuple $(I_{v}^{(1)},I_{v}^{(2)})$, and tuples are sorted in a decreasing lexicographical order. A similar algorithm was used in \cite{Meirom2015, 8071015} to detect infected nodes in a noisy environment. \textbf{(2) Probabilistic risk.} Each node keeps an estimate of the probability it is infected at time $t-1$. To estimate infection probability at time $t$, beliefs are propagated from neighbors, and dynamic programming is used to analytically solve the probability update. See Appendix \ref{sec:tree model} for details. \textbf{B. Supervised learning.} Algorithms that learn the risk per node using features of the temporal graph, its connectivity and infection state. Then, $k$ nodes with the highest risk are selected. \textbf{(3) Supervised (vanilla).} We treat each time step $t$ and each node $v_i$ as a sample, and train a 3-layer deep network using a cross entropy loss against the ground truth state of that node at time $t$. The input of the DNN has two components: A static component described in \secref{sec:ranking_module}, and a dynamic part that contains the number of infected neighbors and their neighbors (like \#1 above). \textbf{(4) Supervised (+GNN).} Like \#3, but the input to the model is the set of all historic interactions of $v_i$'s and its $d$-order neighbours and their time stamps as an edge feature. The architecture is a GNN that operates on node and edge features. We used the same ranking module as our GNN framework, but the output probability is regarded as the probability that a node is infected. \textbf{(5) Supervised (+weighted degree).} Same as \#4, but the loss is modified and nodes are weighted by their degree. Indeed, we wish to favour models that are more accurate on high-degree nodes, because they may infect a greater number of nodes. \textbf{(6) Supervised (+weighted degree +GNN).} Like \#4 above, using degree-weighted loss like \#5. \textbf{C. RL algorithms:} \textbf{\RLGN{}} is our algorithm described in \secref{sec:approach}. The input to \textbf{(7) RL-vanilla} is the same as in (\#1) and (\#4) above. Correspondingly, the GNN module of described in \secref{sec:approach} is replaced by a DNN similar to (\#4), while the rest of the RL algorithm remains intact. \subsection{Experiment details and evaluations} \textbf{Training.} We train the RL and SL by generating random networks, and selecting for each instance a random subset of $m_{0}$ initially infected nodes. We propagate the epidemic until it spans at least $k_{0}$ infected nodes (for at least $t_{0}$ steps), and randomly detect a subset of the infected nodes of size $<k_{0}$. The simulation then follows the agent-network dynamics described in \secref{sec:problem_formulation}. \textbf{Evaluation Metrics.} The end goal of quarantining and epidemiological testing is to minimize the spread of the epidemic. As it is unreasonable to eradicate the epidemic using social distancing alone, the hope is to ``flatten the curve'', namely, to slow down the epidemic progress. We use two success metrics: (1) \textbf{\% healthy:} The percent of nodes kept healthy throughout the simulation. (2) \textbf{\%contained:} The probability of containing the epidemic. This was computed as the fraction of simulations having cumulative infected nodes smaller than a fraction $\alpha$. We focus on this metric because it captures the important notion of the capacity of a health system. In the 2-community setup, where each community has half of the nodes, a natural choice of $\alpha$ is slightly greater than $0.5$, capturing those cases where the algorithm contains the epidemic within the infected community. In all the experiments we set $\alpha=0.6$. The only exception is the three-communities experiments, in which we set the bar slightly higher than $1/3$, and fixed $\alpha=0.4$. \subsection{The dataset and complex-network models} We study three types of networks which differ by their connectivity patterns. \textbf{(1) Community-based networks} have nodes clustered into densely-connected communities, with sparse connections across communities. We use the \textit{Stochastic Block Model} (SBM, \cite{abbe2017community}), for 2 and 3 communities. The Stochastic Block Model (SBM) is defined by (1) A partition of nodes to $m$ disjoint communities $C_{i}$, $i=1\dots m$; and (2) a matrix $P$ of size $m\times m$, which represents the edge probabilities between nodes in different communities, namely, the matrix entry $P_{i,j}$ determines the probability of an edge $(v,v')$ between $v\in C_{i}$ and $v'\in C_{j}$. The diagonal elements in $P$ are often much larger than the off-diagonal elements, representing the dense connectivity in a community, compared to the intra-connectivity between communities. \begin{figure} \centering \includegraphics[width=0.6\columnwidth]{figs/three_communtities.png} \caption{Supervised vs RL with 3-community networks. \textbf{Left:} RLGN successfully learns to contain the epidemic 60\% of the time, while SL fails. \textbf{Right:} SL isolates many more infected nodes, but less important ones.} \label{fig:three_communities} \end{figure} \textbf{(2) Preferential attachment (PA)} networks exhibit a node-degree distribution that follows a power-law (scale-free), like those found in many real-world networks. We use the dual Barbarsi-Albert model \cite{Moshiri2018}, which allows for continuously varying the mean node degree. \textbf{Generating temporal graphs.} Static networks generated using PA or SBM are converted to a temporal graph by first selecting a random subset of edges $\mathcal{E}(t)$ at each time step $t$, and then assigning to each edge a transmission probability $q_e(t)$ sampled uniformly $U[a,b]$. \textbf{(3) Contact-tracing networks.} We received anonymized high-level statistical information about real contact tracing networks that included the distribution of node degree, transmission probability and mean number of interactions per day, collected during April 2020. \begin{figure} \centering \begin{tabular}{cc} \includegraphics[width=0.5\columnwidth]{figs/fig1}& \includegraphics[width=0.5\columnwidth]{figs/fig2}\\ (a) & (b) \end{tabular} \caption{Statistics of a real-world contact-tracing graph. (a) The empirical transition probability $P(p_e)$ on a contact tracing network and our suggested curve fit. (b) The degree distribution on the contact tracing network, along with its fit.} \label{fig:transmission_prob} \end{figure} Fig. \ref{fig:transmission_prob}(a) presents the degree distribution in this data, and the transmission probability is presented in Fig. \ref{fig:transmission_prob}(b). The latter was derived based on the contact properties, such as the length and the proximity of the interaction. On average, $1.635\pm0.211$ interactions with a significant transmission probability were recorded per-person per-day. We generated random networks based on these distributions using a configuration model framework \citep{Newman2010a}. The fitted model for the degree distribution is a mixture of a Gaussian and a power-law distribution \begin{align} P(degree=x)=0.47\cdot\mathcal{N}(0.41,0.036)+0.53\cdot Beta(5.05,20.02). \end{align} The fitted model for the transmission probability is a mixture of a Gaussian and a Beta distribution \begin{align} P(p_{e}=x)=2.68\cdot\mathcal{N}(-4.44,11.18)+3.2\cdot10^{-3}\cdot x^{-0.36}. \end{align} \begin{table} \centering \setlength{\tabcolsep}{3pt} \scalebox{0.97}{{\sc{ \begin{tabular}{|l|c|c|} \hline \%contained & 2 communities & 3 communities \\ \hline \hline Tree-based model & $15\pm 35$ & $0\pm0$ \\ \hline Counter model & $19\pm39$ & $ 1\pm 4$ \\ \hline Supervised (vanilla) & $24\pm 11$ & $2\pm 2$ \\ \hline Supervised +GNN & $27\pm 10$ & $ 2\pm 2$ \\ \hline Supervised +degree & $29\pm 10$ & $ 1\pm 2$\\ \hline Supervised +GNN+deg & $24\pm 10$ & $2\pm 02$\\ \hline \RLGN{} minimal & $66\pm 10$ & $7\pm 5$ \\ \hline \RLGN{} full (ours) & \textbf{$88\pm 7$} & \textbf{$53\pm 13$} \\ \hline \end{tabular} }}} \caption{Probability (in \%) of containing an epidemic in community-based networks. Each community has $30$ densely connected nodes. } \label{tab:comaprison-chart} \end{table} \begin{table} \centering \setlength{\tabcolsep}{3pt} \scalebox{0.99}{{\sc{ \centering \begin{tabular}{|l|c|c||c|c|} \hline & \multicolumn{2}{c}{\%contained} & \multicolumn{2}{c}{\%healthy} \\ \hline & PA & CT & PA & CT\\ \hline \hline Tree based model & $1\pm1$ & $0\pm0$ & $10\pm7$ & $11\pm3$\\ \hline Counter model & $0\pm0$ & $0\pm0$ & $7\pm7$ & $14\pm5$ \\ \hline SL (vanilla) & $2\pm2$ & $0\pm0$ & $13\pm3$ & $17\pm1$\\ \hline SL + GNN & $27\pm6$ & $15\pm4$ & $34\pm3$ & $32\pm$2\\ \hline SL + deg & $3\pm3$ & $0\pm1$ & $15\pm3$ & $18\pm1$\\ \hline SL + deg + GNN & $26\pm5$ & $16\pm5$ & $33\pm3$ & $32\pm1$\\ \hline RL (vanilla) & $2\pm2$ & $1\pm1$ & $17\pm1$ & $16\pm1$\\ \hline RLGN (ours) & \textbf{$\mathbf{78\pm4}$} & $\mathbf{45\pm6}$ & $\mathbf{52\pm2}$ & $\mathbf{40\pm1}$ \\ \hline \end{tabular} }}} \caption{\%contained epidemics and \%healthy nodes achieved on a preferential attachement (PA) network, and contact tracing (CT) network. In both cases, networks had $200$ nodes.} \label{tab:comaprison-chart-scale-free} \end{table} \subsection{Results} \label{sec:results} We compared 7 algorithmic approaches on 3 network types. The results reported in Table \ref{tab:comaprison-chart} and \ref{tab:comaprison-chart-scale-free} show that RLGN outperforms all baselines in all network types. A video highlighting the results can be found \href{https://youtu.be/js9v7_LKppg}{online} \footnote{Link: \url{https://youtu.be/js9v7_LKppg}} To gain insight into this result, we first look more deeply into the case of 3-community networks. \figref{fig:three_communities}(a) traces the fraction of contained epidemics and \figref{fig:three_communities}(b) the fraction of infected nodes during training. The supervised learning algorithm detects substantially more infected nodes (right panel) than RLGN, but these tend to have lower future impact on the spread, and it fails to contain the epidemic (left). A closer look shows that RL, but not SL, successfully learns to identify and neutralize the critical nodes that connect communities and prevent the disease from spreading to another community. To further understand the solutions learned for PA networks, consider the following two extremes. First, when a network is very sparsely connected, it would be easy to cut long infection chains, and both approaches are expected to be successful. At the other extreme, for densely connected networks, there are no critical nodes, because there are many paths between any two nodes. To study this effect we generated networks with the preferential-attachment mechanism, while varying the mean node degree. This degree can also be viewed in terms of the $R_0$ coefficient, the mean number of nodes infected by a single diseased node. The greater $R_0$, the more difficult it is to contain the epidemic. \begin{figure} (a)\hspace{120pt} (b)\hspace{120pt}\\ \includegraphics[width=0.48\columnwidth]{figs/phase_shift.png} \includegraphics[width=0.48\columnwidth]{figs/stability_analysis} \caption{\textbf{Stability analysis:} \textbf{(a)} The contained epidemic fraction as a function of the basic reproduction number $R_0$ on a PA network. RLGN outperforms SL over a large range of $R_0$ values. \textbf{(b)} Stability against test-time shift in transmission probability. \textit{Orange:} The performance of RLGN deteriorates when the mean transmission probability at test time is higher more than $40\%$ than train time. \textit{Purple:} As a baseline, training and testing with the same higher transmission probability. \label{fig:stability} } \end{figure} Fig.~\ref{fig:stability}(a) quantifies this effect, showing the percent of contained epidemics as a function of the $R_0$ coefficient. RL has a significant advantage over supervised+GNN for a range of $R_0$ values between $2.0$ and $2.9$. Finally, \figref{fig:stability}(b) depicts a robustness analysis of \RLGN{} for variations in the epidemiological model. One of the most difficult quantities to assess is the probability for infection per social interaction. \figref{fig:stability}(b) shows that the trained model can sustain up to $\sim40\%$ deviation at test time in this key parameter. \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{figs/moving_histogram.png} \caption{The fraction of infected nodes as a function of time step $t$. The epidemic propagtes more slowly under RLGN compared with the best baseline (supervised+GNN, \#4). Shaded areas represent one standard deviation around the mean. Experiment was performed on a preferential attachment network with $300$ nodes and mean degree $2.8$. \label{fig:epidemic-speed} } \end{figure} We investigated the progression of the epidemic under testing assignments provided by either RLGN or supervised+GNN algorithms. Figure \ref{fig:epidemic-speed} shows that the epidemic spread speed is considerably slower under the learnt RLGN policy. \subsection{Results Robustness} We have tested the robustness of our results to the underlying graph size. Specifically, we compare the two best algorithms RLGN (\#8) and SL+GNN (\#4), using graphs with various sizes, from 300 nodes to 1000 nodes. Table \ref{tab:300-nodes-pa} compares RLGN with the SL+GNN algorithm on preferential attachment (PA) networks (mean degree $=2.8$). We provide results for various sizes of initial infection $i_{0}$ and number of available tests $k$ at each step. The experiments show that there is a considerable gap between the performance of the RL and the second-best baseline. Furthermore, RLGN achieves better performance than the SL+GNN algorithm with 40\%-100\% more tests. Namely, it increases the effective number of tests by a factor of $\times1.4-\times2$. We also tested the sensitivity of the results to the relative size of the initial infection. Table \ref{tab:300-nodes-pa} shows results when 4\% of the the network was initially infected, as well as for 7.5\% and 10\%. The results show that RLGN outperforms the baselines in this wide range of infection sizes. \begin{table} \centering \setlength{\tabcolsep}{3pt} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=300$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $27\pm2$ & $15\pm5$ & $21\pm2$ & $4\pm2$ & $18\pm1$ & $1\pm1$\\ \hline SL, $k=1.33\%$ & $41\pm3$ & $37\pm6$ & $27\pm2$ & $12\pm4$ & $24\pm2$ & $6\pm3$\\ \hline SL, $k=2\%$ & ${66\pm4}$ & $76\pm6$ & ${48\pm3}$ & $55\pm7$ & $37\pm2$ & $32\pm6$\\ \hline RLGN, $k=1\%$ & $50\pm2$ & ${78\pm7}$ & {$43\pm2$} & ${58\pm1}$ & ${40\pm1}$ & ${48\pm6}$\\ \hline \end{tabular} \vspace*{0.2 cm} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=500$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $24\pm2$ & $7\pm4$ & $20\pm1$ & $2\pm1$ & $19\pm1$ & $0\pm1$\\ \hline SL, $k=1.6\%$ & $48\pm3$ & $54\pm6$ & $35\pm2$ & $27\pm7$ & $29\pm1$ & $11\pm1$\\ \hline SL, $k=2\%$ & ${67\pm3}$ & $83\pm5$ & ${46\pm2}$ & $53\pm4$ & $38\pm2$ & $37\pm7$\\ \hline {RLGN, ${k=1\%}$} & $52\pm1$ & ${97\pm2}$ & ${44\pm2}$ & ${75\pm11}$ & ${42\pm1}$ & ${66\pm6}$\\ \hline \end{tabular} \vspace*{0.2 cm} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=1000$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. Infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $25\pm2$ & $5\pm3$ & $21\pm1$ & $0\pm1$ & $19\pm1$ & $0\pm0$\\ \hline SL, $k=1.5\%$ & $42\pm2$ & $49\pm6$ & $30\pm1$ & $10\pm3$ & $27\pm1$ & $4\pm2$\\ \hline SL, $k=2\%$ & ${66\pm1}$ & $84\pm5$ & ${45\pm2}$ & $59\pm5$ & $37\pm1$ & $30\pm1$\\ \hline {RLGN, ${k=1\%}$} & $52\pm1$ & ${97\pm2}$ & ${44\pm2}$ & ${75\pm11}$ & ${42\pm1}$ & ${66\pm6}$\\ \hline \end{tabular} \caption{A comparison between RLGN and SL+GNN (the best baseline). RLGN performance is highlighted. The number of additional resources needed to surpass the RLGN performance in a given metric is also highlighted. In many cases, even using SL+GNN with twice as many resources than RLGN performs worse than RLGN. The evaluation was performed on a preferential attachment network with mean degree $2.8$. The number of nodes is indicated at the top of each table.} \label{tab:300-nodes-pa} \end{table} \subsection{Inference on large graphs} We further evaluated how models trained on medium-sized graphs generalize when performing inference on much larger graphs. Specifically, we trained RLGN and SL+GNN (three model initializations for each) on a preferential attachment network with $1000$ nodes and evaluated its performance of a network with $50,000$ nodes (with the same mean degree $=2.8$). We found that RLGN successfully contained the epidemic in all $150$ evaluation episodes, while the SL+GNN was unable to block the epidemic even once. The mean percentile of healthy nodes at the end of the episode was $51\pm1$ for RLGN, while for the SL+GNN it was only $21\pm2$, a difference of more than $15$ STDs. \subsection{Ablation Studies} \subsubsection{Mapping scores to action distribution.} We compare the performance of our score-to-probability function (calibrated-scores) to the popular softmax (Boltzmann) distribution. In practice, in most instances, we were unable to train a model using the softmax distribution as the neural network weights diverge. Fig.~\ref{fig:score-to-prob} presents the training curve in one of the few instances that did converge. It is clear that the model was not able to learn a useful policy while using the calibrated-scores probability function resulted in a corresponding value of more than $0.75$. \begin{figure} \centering \includegraphics[width=0.55\columnwidth]{figs/score_to_prob_ablation.png} \caption{The fraction of contained epidemics during training on a preferential attachment model with $200$ nodes and a mean degree $2.8$. For non-normalized mapping, only one of the three seeds in the softmax distribution simulation completed training due to numerical instability. No stability issues were observed when using the calibrated scores normalization scheme described by Eq. \eqref{eq: score-to-prob}. \label{fig:score-to-prob}} \end{figure} \begin{table} \centering \begin{tabular}{|c|c|c|} \hline & $\%contained$ & \# training epochs\\ \hline \hline Sigmoid & $0.84\pm0.05$ & 1210\\ \hline GRU & $0.91\pm0.03$ & 810\\ \hline $L_{2}$ norm. & $\mathbf{0.93\pm0.02}$ & \textbf{500}\\ \hline \end{tabular} \caption{\label{tab:norm-table} Training time and fraction of contained epidemic for three normalization schemes. The $L_2$ normalization scheme is fastest and achieves the best performance.} \end{table} \subsubsection{Normalization in scale-free networks.} We compared the suggested normalization to a number of other alternative normalization methods. (1) Applying a sigmoid layer after the hidden state update module $G$. (2) Replace the hidden state update module with a GRU layer. (3) Apply $L_2$ normalization to each feature vector $h_v(t)$ (similarly to \cite{Hamilton2017}) (4) Normalize the feature vector matrix by its $L_2$ norm. These four normalization schemes span three different types of normalization: single-feature normalization (1+2), vector normalization (3), and matrix normalization (4). Table \ref{tab:norm-table} presents the score after training and the number of training steps required to complete training. Method (4) was unstable and training did not converge, therefore it was omitted from the table. The main reason for the training time difference is that without normalization, the DNN weights' magnitude increases. In a GRU module, or with a direct application of a sigmoid layer, the features pass through a sigmoid activation function. When the magnitude of the input to this layer is large, the gradient is very small due to the sigmoid plateau. This substantially slows down the learning process. \subsubsection{Information processing module. } Our experiments showed the information module has a critical role in improving the performance of the RL-GNN framework. We performed an ablation study by removing it completely from our DNN module, keeping only the epidemic module. The full DNN module achieved a contained epidemic score of $0.77\pm0.06$, while the ablated DNN module corresponding score was $0.62\pm0.10$, a degradation of more than $20\%$. \section{Extensions\label{sec:extensions}} The approach and model discussed in this paper can be applied to important problems other than epidemic control. {\bf Influence maximization (IM).} Unlike epidemic control, in IM, the decision maker the objective is to maximize the spread of some opinion on a social network graph. They act to select nodes to be influenced by presenting information, actively contacting them, or sending coupons etc. Given a budget, the IM agent can only contact a limited number of nodes over a period of time. Influence spreads over the social networks similar to the model described above. The overall cost has two terms: cost of spending budget on influencing individual nodes, and benefit from influencing a give portion of the network. Local effects such as high degree nodes are important to IM. {\bf Fake news detection and confinement.} Consider a social network where fake news can be maliciously distributed, and spread over the network. A decision maker can verify the authenticity of items, but only verify a limited number of items per a time period. Once a fake item is detected, it is erased from the network. The objective is to minimize the total number of nodes that observe fake items. The main difference from the epidemic problem is that once a fake item is discovered, it can be erased from the entire network. The trade-off is that the decision maker does not want to waste inspection resources on items that are likely to die out. The fake new control and confinement problem can be therefore naturally cast within the framework outlined here. {\bf Epidemic Control: Beyond Node Selection}. While this paper addressed the important problem of deciding which nodes to examine given a certain umber of tests, we can also ask what if not only the subset of nodes to be tested, but also \emph{the number of tests.} to be performed can be controlled. Increasing the number of tests will help us contain the epidemic, however, it may be expensive to increase the number of tests and economy of scale may not work here. Another form of control is imposing a partial quarantine that reduces the number of interactions and resulting infections. Such a quarantine would come with a cost, of course. Both variations, and others, can be easily modeled within the framework presented in this paper. The crucial aspects of the model is having a objective that is cumulative reward structure, an action space that depends only on the information states, and a relatively short horizon for the relevant information to propagate so that the GNN approach works. Other important variations to the test kit allocation problems such partial quarantines, or using less accurate but more abundant tests can be easily modeled within the framework presented in this paper. The crucial aspects of the model is having an objective that has a cumulative reward structure, an action space that depends only on the information states, and a relatively short horizon for the relevant information to propagate so that the GNN approach works. \section{Conclusions} This paper shows that combining RL with GNNs provides a powerful approach for controlling spreading processes on graphs. In the context of COVID-19 spread, we demonstrated that using an RL+GNN approach allows us to confine the spread of an epidemic that is approximately 30\% more contagious (i.e., $R_0$ that is 30\% higher) with the same resources as a standard supervised learning-based approach. In addition, our results indicate that prioritizing tests using RL on temporal graphs can increase the number of healthy people by $25\%$ and contain the epidemic $30\%$ more often than supervised approaches and $2.5\times$ more often than non-learned baselines using the same resources. \bibliographystyle{aaai21} \section{Introduction} Consider an epidemic spreading in the population, without any known cure or vaccination procedure. To contain the disease and prevent it from spreading, it becomes critical to detect infected carriers and isolate them; see Fig.~\ref{fig:viralinfection} for an illustration. As the epidemic spreads, the demand for tests outgrows their availability, and not all potential carriers can be tested. It becomes necessary to identify the most likely epidemic carriers using limited testing resources. This raises a major question: How can we rank candidates and prioritize testing to prevent the disease from spreading? \eli{Consider a seemingly unrelated problem, where one would like to promote the spread of an opinion, or support product adaption, either by advertisements or information sharing on a social graph. If an impactful node is convinced, it may influence other nodes towards the desired opinion, creating a cascade of information diffusion. Given a limited budget, one has to choose which nodes to target at each point in time. A key difficulty of the campaign manager is that it may have only partial information: it may not know if the targeted nodes were influenced and whether they further propagated this information in private or unobserved communication. There are only partial observations, such as coupon usages or ad clicks, and often there may be large delay from promotion time to an indication that the promotion was successful.} These two problems are important examples of a larger family of problems: learning to control diffusive processes over networks through nodal interventions. Other examples include viruses inflicting computer networks or cascades of failures in power networks. In all these cases, the dynamics of the system can be steered using interventions that modify the states of a (relatively) small number of nodes. For instance, infected people can be asked to self-quarantine, preventing the spread of a disease, and key twitters may be targeted with coupons.% \begin{figure}[t] \centering \includegraphics[width=0.60\columnwidth]{figs/RL_graphs_fig1_trimmed.png} \caption{A viral infection process on a graph and an intervention aimed to stop its spread. Here, graph nodes represent people and edges represent interactions. At $t=1$ only two people are infected (red). At $t=2$ several interactions resulted in new \textit{exposed} people (yellow); At $t=3$ the blue node was selected to be quarantined to stop the viral spread. This paper presents a framework for learning how to select which nodes should be quarantined. }\label{fig:viralinfection} \end{figure} The problem of controlling the dynamics of a system using localized interventions is very hard, and for several reasons. First, it requires to make decision in a continuously changing environment with complex dependencies. Second, to solve the problem one must assess the potential downstream ripple effect for any specific node that becomes infected, and balance it with the probability that the node indeed becomes infected. Finally, models must handle noise and partial observability. We pose the problem of controlling a diffusive process on a temporally evolving graph as a sequential decision making problem in the context of a partially-observed Markov decision process. We then formulate the problem of selecting a subset of nodes for dynamical intervention as a {\em ranking } problem, and design an actor-critic RL algorithm to solve it. We use the observed changes of nodes states and connections to construct a temporal multi-graph, which has time-stamped interactions over edges, and describe a deep architecture based on GNNs to process it. To the best of our knowledge, this work is the first work that consider Deep RL in the context of a temporally evolving graph. The current work combines three research fields: dynamic processes on temporal graphs, deep graph learning and reinforcement learning. Combining these three into a cohesive model raises several new challenges. We show that combining RL with temporal graphs requires stabilizing information aggregation from other neighbors when updating nodes hidden states, and control how actions are sampled during training to ensure sufficient exploration. We show empirically the beneficial effects of these components. \eli{Most importantly, the underlying dynamics is not directly observed. Instead, partial information on the state of some nodes is given at each point in time. While the diffusive process spreads by point contacts, new node information, such as detecting an infected person or a coupon use, directly modifies the state probability for nodes that are connected to it by a path in temporal graph. Such change occurs immediately and may impact our belief on the state of nodes a few hops away from the source of new information. To address this issue, our architecture contains two separate GNN modules, taking as input a multi-graph over the nodes, where edges are time-stamped with the time of interactions.} This paper demonstrates that combining RL with GNNs provides a powerful approach for controlling spreading processes on graphs. In the context of COVID-19 spread, we show that using the RL-GNN approach increases the fraction of healthy by $25\%$ and allows for confining the spread of an epidemic $30\%$ more often, and $3\times$ times more often that using non-learned approaches. ~\newline This paper makes the following contributions:\\ {\bf (1)}~A new framework for controlling the dynamics of diffusive processes over graphs. Namely, learning to perform local interventions to steer the global dynamics of a graph-based dynamical system. \\ {\bf (2)}~A new architecture for this problem, and a way to train a decision-making agent using reinforcement learning to prioritize interventions on the temporal multi-graph. We demonstrate the interplay between the dynamics of graph states and the information flow, which motivates the design of our deep network architecture. \\ {\bf (3)}~A set of benchmarks and strong baselines for this problem, including real-world contact tracing statistical data for COVID-19. Our RL approach achieves superior performance over these datasets, often significantly. \\ {\bf (4)}~We define the dynamical influence maximization problem, an extension of the classical influence maximization problem. \\ \eli{ {\bf (5)}~We propose a novel sampling scheme for actions in large discrete action spaces, and demonstrate it outperform the state-of-the-art sampling techniques. \\} \section{Previous work \label{sec:related_work}} Our work is in the intersection of a few disciplines. We tackle the problem of \emph{controlling a dynamic process} by considering it as \emph{ranking problem on a temporal graph}. As a particular example, we address the problem of a controlling a viral epidemic spreading on a social graph. \textbf{Deep Learning on graphs.} Graph neural networks (GNNs) are deep neural networks that can process graph-structured data. GNNs became very popular and were shown useful for solving a variety of tasks including social network analysis \cite{kipf,fan2019graph} and molecule property prediction \cite{Gilmer2017,Duvenaud2015}. Perhaps the most popular GNN models are Message Passing Neural Networks (MPNN) \cite{Gilmer2017, Hamilton2017, Velickovic2017}, which operate by repeatedly updating the feature vector of each node by aggregating information from its neighbourhood. Several works combine recurrent mechanisms with GNNs to learn temporal graph data, e.g., \cite{guo2019attention, zhao2019t, fang2019gstnet,yu2017spatio} tackled the traffic forecasting problem . \cite{li2019study,kapoor2020examining} proposed a graph-structured RNN for coarse spatial prediction of epidemic spread. Unlike this work, these works model the epidemic spread and do not try to intervene with the diffusive process. More generally, several recent studies \cite{liu2019towards, rossi2020temporal, liu2020towards, pareja2020evolvegcn} tackle a setup in which both nodes and edges vary over time, with applications in social network analysis and other fields. Further information can be found in \cite{kazemi2020representation}. \textbf{Ranking on graphs.} The problem of ranking on graphs is a fundamental problem in Computer Science, in which the task is to rank the nodes of a given graph according to some criteria. It has various applications such as web page ranking \cite{page1999pagerank,agarwal2006ranking} and knowledge graph search \cite{xiong2017explicit}. \textbf{Reinforcement learning and graphs.} Recently, a surge of work combining Reinforcement Learning and graphs emerged. These works can be split into two main categories: leveraging graph structure for general RL problems (e.g., \cite{Zhang2018,Jiang2018}), and applying reinforcement learning methods for graph problems. Our work falls into the latter. An important line of work uses Reinforcement Learning to solve NP-hard combinatorial optimization problems defined on a graph \cite{Zhu,Dai}. Another common application is the usage of RL for path searching in a knowledge graph \cite{xiong2017explicit,Das}. Reinforcement learning was also shown in a few other graph problems, such as chemical reaction prediction \cite{Do2018}. \textbf{Dynamic processes on graphs. } Modelling diffusive processes is an active research field. Key models such as SIR (Suscpetible-Infected-Removed) and SIS (Suscpetible-Infected-Suscpetible) \cite{Newman2010a} to the recent SEIR (Suscpetible-Exposed-Infectious-Removed) COVID-19 epidemic model \cite{Lin2020,Lopez2020} have proven useful in modelling the spread of contagions. The application of these models is extended, and varies from early epidemic detection \cite{Meirom2015}, to influence maximization \cite{Kempe2003} and network security \cite{Gourdin2011}. Recently, researchers have also used deep learning to forecast epidemic growth, e.g., \cite{Adhikari2019, Rodriguez2020}. The problem of node manipulation (e.g., vaccination) for controlling epidemic processes on graphs was intensively studied \cite{Hoffmann2020, Medlock2009}. This problem is often addressed in the setup of the fire-fighter problem and its extensions \cite{firefighter_survey, Tennenholtz2017, Sambaturu}. Common approaches include include developing centrality measures designed to highlight bottleneck nodes \cite{Yang2020}, or using spectral methods for allocating resources \cite{Saha2015, Preciado2014, Ogura2017}. Alternative line of research \cite{MILLER2007780, Cohen2002} developed heuristics for the same task. Our setup differs from these work in three important aspects. First, we do not assume a node can be vaccinated or immunized against the epidemic. In a realistic scenario, once a vaccination is discovered it will be rapidly distributed to the masses. For example, in the context of a computer malware, distributing the vaccine can be easily applied to every node by means of a software patch. In other cases, such as human epidemics, it is likely that factors such as underlying personal health condition (e.g, if a person is at increased risk) will be the dominant factor in prioritizing vaccination. Therefore, here we consider the problem at its pre-vaccination stage, where every node is susceptible to the disease. Second, we do not assume a node can be quarantined or disconnected from the graph without justification, namely, without a positive test result. It may be tempting to isolate a high-degree node from the network, like putting a bus-driver in quarantine or disconnecting a hub computer from the network, but we view this solution as problematic. Nodes perform required network functionality. Removing a load balancer without a proper replacement will substantially impair the computer network functionality. Quarantining a bus driver due to her connectivity pattern will result in either replacing the bus driver with another driver with the same interactions pattern, or the transportation network functionality will deteriorate. In other words, a preemptive node removal would either not affect the network connectivity or impair the network functionality. Therefore, we assume that a node can be put in isolation only {\em after} it tests positive for infection. Finally, most previous works considered a setup in which a single vaccination decision is taken at $t=0$ (with a possible delay execution), based only on the information available at $t=0$ . In our setup, the agent needs to decide at each time step $t$ on its testing policy, given the information available at $t\ge 0$, which include the results of past actions. Furthermore, the agent \emph{is aware to the fact that it may take additional action at later times}. The agent needs to balance between retrieving information (for better informed future decisions), maximizing the probability that the immediate intervention will be successful, and optimizing the long-term goal that depends the stochastic epidemic evolution, current action and future actions. The agent needs to optimize the trajectory of test allocations, where each decision is taken under different information setting. In contrast to other work, the agent need not only know where to test, but also when to test each node, in a partially observed setup with little information. \section{A motivating example} We begin with an example to illustrate the trade-offs of the problem. A natural algorithmic choice would be to act upon nodes that are most likely infected. The following example shows why this approach is suboptimal. We form a time-varying graph from a list of interactions between nodes at various times. If $u,v$ interacted at time $t$ then the edge $(u,v)$ exists at time $t$. Each interaction is characterized by a transmission probability $p_e(t)$. If a node was infected at time $t$ and its neighbor was healthy, then the healthy node is infected with probability $p_e(t)$. For the purpose of this example, assume that our goal is to prevent the spread of the epidemic, and that we can test a single node at odd timesteps. If the node is identified as infected, it is sent to quarantine and cannot further interact with other nodes. Otherwise, we do not perturb the dynamics and it may interact freely with its neighbors. Our goal is to minimize the number of infected nodes. Consider the "two stars" network in \figref{fig:toy-example}. The left hub (node $v_1$) has $m_1$ neighbors, and $m_2$ nodes are attached to the right hub $v_2$. At $t=0,$ only the edge $e=(v_{1},v_{2})$ is present with $p_e(t=0)=p$. Then, for all $t\geq1$, all edges depicted in \figref{fig:toy-example} exist with $p_e(t)=1$. Assume that this information is known to the agent, and that at $t=1$ it is revealed that node $v_{1}$ was infected at $t=0$. In this example, we clearly should test either $v_{1}$ or $v_{2}$. We can compute the expected cost of each option exactly. \textbf{Alternative I:} Test ${v_2}$. With probability $p$, $v_{2}$ becomes infected at $t=1$, and we block the epidemic from spreading. However, we forfeit protecting $v_{1}$ neighbors, as all of them will be infected in the next step. With probability $1\!-\!p$ test is negative, and we fail to affect the dynamics. At $t=2$ node $v_{2}$ will get infected and at $t=3$ all of $v_{2}$'s neighbors become infected too, ending up with a total of $\left(m_{2}+1\right)$ infections. The expected cost in choosing to test $v_{2}$ is $(1-p)\cdot m_{2}+m_{1}$. \textbf{Alternative II:} Test $v_{1}$. We block the spread to $v_{1}$'s neighbors, but sacrifice all $m_{2}$ neighbors of $v_{2}$ with probability $p$. The expected cost in choosing $v_2$ is $p\cdot m_{2}$. The decision would therefore be to test for $v_{2}$ if $2p\geq1+m_{1}/m_{2}$. This example illustrates that an optimal policy must balance two factors: \emph{the probability that the dynamics is affected} - that a test action yields a ``positive", and the future consequences of our action - the \emph{strategic importance} of selecting\emph{ $v_{1}$ vs. $v_{2}$}, expressed by the ratio $m_{1}/m_{2}$. A policy targeting likely-infected nodes will always pick node $v_1$, but since it only focuses on the first term and ignores the second term, it is clearly suboptimal. \begin{figure} \begin{minipage}[c]{0.4\columnwidth} \includegraphics[width=0.9\columnwidth]{figs/toy_example.png} \end{minipage} \hfill \begin{minipage}[c]{0.5\columnwidth} \caption{ A double star configuration. The state of $v_{2}$ is unknown at the $t=1$. $v_1$ is infected at $t=0$.} \label{fig:toy-example} \end{minipage} \end{figure} An immediate question arise: How can we develop methods that address both terms? It is difficult to measure the strategic importance of a node in a large dynamical process with constant external interventions directly. Instead, one may use simulations and try to learn from the collected experience and the interplay between dynamics and actions a method that finds the optimal policy end-to-end and internally weighs the two terms optimally. This calls for a reinforcement learning framework. \begin{figure}[t] \centering \includegraphics[width=0.7\columnwidth]{figs/RL_graphs_fig2.png} \caption{Schematic of our approach. The Ranking module receives as input a sequence of graphs and outputs scores over nodes. Scores are then used to sample actions, selecting nodes for intervention. Here, the person circled in blue is selected for quarantine and its connections are cancelled (dashed blue lines). The downstream effect on epidemic progression is then fed as a loss to the ranking module.} \label{fig:Approachsechematics} \end{figure} \section{Problem Formulation} \label{sec:problem_formulation} We start our discussion with a general formulation of the control problem, and then give two concrete examples from different domains: Epidemic test prioritization, and dynamic influence maximization. \subsection{General formalism} Consider a graph $G(t)=(\mathcal{V},\mathcal{E}(t))$ whose structure changes in time. $\mathcal{V}$ is the set of nodes and $\mathcal{E}(t)=\{e_{uv}(t)\}$ is the set of edges at step $t$. Each edge $e_{uv}(t)$ is associated with features $\phi_{uv}(t)$ which may vary in time, and each node $v$ is characterized with features $\zeta_{v}(t)$. The state of a node $v\in\mathcal{V}$ is a random variable $ST_v(t)$ which can have values in $\mathcal{Y}=\{y_{1},y_{2},..\}$. The node's state $ST_v(t)$ depends on the interactions between $v$ and its neighbors, its state and the state of those neighbors, all at time $t-1$. At each step, we may select a subset $A(t)$ of $k$ nodes, and attempt to change the state of any selected node $v\in A(t)$, namely, apply a stochastic transformation on a subset of the nodes. Selecting nodes and setting their states defines the space of actions for the agent, and plays the role of a knob for controlling the global dynamics of the process over the graph. The optimization objective should be invariant to permuting (relabeling) of the nodes. We assume it depends only on the total number of nodes in state $y_i$, The objective is therefore of the form \[ \max \sum_{t}\gamma^{t-t_{0}}g(c_{1}(t),c_{2}(t),..), \] where future evaluation are weighted by a discount factor $\gamma \le 1$. Additionally, the agent may be subject to constraints written in a similar manner $\sum_{i}f_{i}(c_{1}(t),c_{2}(t),..)\geq z_{i}(t)$. \subsection{Epidemic test prioritization} We consider the recent COVID-19 outbreak that spreads through social contacts. The temporal graph $G$ is defined over a group of nodes (people) $\mathcal{V}$, and its edges $\mathcal{E}(t)$ are determined by their daily social interactions. An edge $(u,v)$ between two nodes exists at time $t$ iff the two nodes interacted at time $t$. Each of these interactions is characterized by various features $e_{uv}(t)$, including its duration, distancing and environment (e.g., indoors or outdoors). Additionally, each node $v$ is characterized with features $\zeta_{v}(t)$ (e.g., age, sex etc.). \textbf{The SEIR model}. We follow the widely-used SEIR model \cite{Lopez2020}. Every node (person) can be in one of the following states, $\mathcal{Y}={S, L, I, R}$, namely: \textit{susceptible} -- a healthy, yet uninfected person ($S$ state), \textit{exposed/latent} -- infected but cannot infect others ($L$ state), \textit{infectious} -- may infect other nodes ($I$ state), or \textit{removed} -- self-quarantined and isolated from the graph ($R$ state). The state of a node $v\in\mathcal{V}$ at time $t$ is a random variable denoted by $ST_v(t)$ \textbf{Node state dynamics}. A healthy node can become infected with a probability that depends on its interactions with its neighbors. Once infected, transitioning from \textit{Exposed/Latent} to \textit{Infected} is defined by a probabilistic process. A node becomes \textit{Removed} if it is selected for self-quarantine (tests positive); see Fig.~\ref{fig:viralinfection} for an illustration. Formally, let $\mathcal{I}(t)\subset V$ be the set of infectious nodes at time $t$, and similarly $\mathcal{L}(t)$, $\mathcal{R}(t)$ and $\mathcal{S}(t)$ be the sets of latent(exposed), removed and susceptible (healthy) nodes. Each active edge at time $t$, $e\in\mathcal{E}(t)$, carries a transmission probability $p_{e}(t)$. Denote the set of impinging edges on node $v$ with an infectious counterpart at time $t$ by $E_{v}(t)=\left\{ e\in\mathcal{E}(t)|e=(v,u),SV_u(t-1)=I\right\} .$ The probability of a healthy node to remain healthy at time $t$ is $\prod_{e\in E_{v}(t)}\left(1-p_{e}(t)\right)$, otherwise it becomes infected, but still in a latent state. We denote the time of infection of node $v$ as $T_{v}.$ A node in a latent state will stay in this state at time $t$ if $t<T_{v}+D_{v}$, where $D_{v}$ is a random variable representing the latency period length, otherwise its state changes to infectious. The testing intervention $h(\cdot)$ changes the state of a node. If infected or exposed, its state is set to $R$, otherwise it remains as it is. \textbf{Optimization goal and action space.} The objective is to minimize the spread of the epidemic, namely, minimize the number of infected people, $\left\lVert \mathcal{L}(t) \cup \mathcal{R}(t) \right\rVert$ over time. Assuming that testing is limited to a fixed capacity of $k$ tests per day, the optimization goal becomes $ \min\sum_{t,v}\gamma^{t}\left\lVert \mathcal{L}(t) \cup \mathcal{R}(t) \right\rVert, $ where $\gamma\in(0,1]$ is a discount factor representing the relative importance of the future compared to the present. We used $\gamma=0.99$ throughout the paper. Of course, this is but one particular optimization goal and other goals that weigh different states differently, or add additional aspects are possible. The action space consists of all possible selections of a subset $a(t)$ of $k$ nodes $a(t)\subset V$. Even for moderate graph, with $\sim100-1000$ and small $k$ the action space ${|\mathcal{V}| \choose k }$ is huge. \textbf{Observation space.} At each time $t$, the agent is exposed to all past interactions between network nodes $\left\{ \mathcal{E}(t')|t'<t\right\} $. In addition, we are given partial information on the nodes state. The agent is provided with information on a subset of the infectious nodes at $t=0$. At every $t>0$, the agent observes all past test results. Formally, for every $v\in a(t)$ we observe if the node was infected, $ST_v(t)\in\mathcal{I}(t)\cup\mathcal{L}(t) $, or not. \subsection{Dynamic influence maximization} We extend the classical influence maximization [] problem to dynamic setup with partial observability. In this setup, each node is either \emph{Influenced} or \emph{Susceptible}, the latter is the initial state of all nodes. At each time the agent selects a seed set $A(t)$ of $k$ nodes, and attempt to influence them to its cause. This succeeds with probability $q$ independently for each node. Influenced nodes then propagate this cause, following an dynamic generalization to two canonical dynamics: Linear Threshold (LT) and Independent Cascades (IC). In a linear threshold dynamical model, each node $v$ is associated with a threshold $w_v$, and each edge $e$ carries an impact weight of $q_e$. The "peer pressure" on a node is the total weight of active edges in the last $T_{peer}$ steps connecting influenced neighboring nodes and node $v$. If the "peer pressure" on node $v$ exceeds $w_v$, node $v$ state is changed to \emph{Influenced}. In an Independent Cascades model, if $u$ is Influenced and $(u,v)\in \mathcal{E}_t$, then $u$ attempts to influence $v$. We explored two variations, IC(plain) and IC(geometric). In IC(plain), the success probability of each attempt is $p$, while in IC(geometric), the success probability decays with the number of influence attempts $m_{(u,v)}$ and is $p^{m_{(u,v)}}$. This mimics the reduced effect of presenting the same information multiple times. \section{Approach} \label{sec:approach} \eli{If the statistical characteristics of the dynamics can be estimated, a naive approach would suggest performing Monte Carlo simulations of the epidemic propagation, and estimate the optimal result. However, as each decision affect the dynamics, such estimation need to be performed for every decision sequence (i.e., trajectory). If the number of Monte Carlo simulations required to perform a reasonable estimation is $\Upsilon$, typically $o(10^4)$, and the trajectory length is $\rho$, then the number of Monte Carlo simulation for choosing the optimal action is in excess of $o(\Upsilon \rho {k \choose |\mathcal{V}|})$, which is prohibitly large []. Instead, Our approach is based on RL, and depicted in Figure \ref{fig:Approachsechematics}.} The RL agent receives as input the node and edge features of the temporal graph, and processes them using its ranking module. A probability distribution over graph nodes is generated from the ranking module’s scores, and the agent samples a subset of $k$ nodes for testing. Namely, the scores encode the agent's policy. We use Proximal Policy Optimization algorithm (PPO, \cite{Schulman2017}) as to optimize our agent. We sequentially apply the suggested action, log the (state, action) tuple in an experience replay buffer, and train our model based on the PPO loss term. Next, we describe the ranking module and sampling procedure. \subsection{RL Agent Ranking Module} \label{sec:ranking_module} \paragraph{Overview} Our GNN-RNN module serves to update the internal representation of a node $v$, denoted $h_v(t)$, and its score $s_v(t)$ (\figref{fig:ranking}). This score is later used for selecting nodes to be acted on. The ranking module is applied in a recurrent fashion at each time step. The ranking module contains two GNNs: (1) $E$, which updates the epidemic state, and (2) $I$, which updates the information state. It also contains two other networks, $G$ and $F$, which update node representations and node scores by using the epidemic state and information state as well as the previous node representations. \textbf{Input.} The input to the ranking module consists of three feature types (See \figref{fig:ranking}): (1) \textit{Static node features} $\zeta^s_v(t)$: topological graph centralities (betweeness, closeness, eigenvector and degree centralities) and random node features. (2) \textit{Dynamic node features} $\zeta^d_v(t)$ : All test results that were performed up the current timestamp (including positive and negative test results). We denote all nodes features as a concatenation $\zeta_v(t)=[\zeta^s_v(t),\zeta^d_v(t)]$. (3) \textit{Edge features} and the structure of the temporal graph $\mathcal{E}(t)$: All previous interactions up to the current step, including the transmission probability for each interaction. Figure \ref{fig:ranking} illustrates the basic data flow in the ranking module. \begin{figure}[t] \centering \includegraphics[width=0.7\columnwidth]{figs/RL_graphs_fig3.png} \caption{Block diagram of our suggested ranking module. It is composed of 4 neural networks $I$,$E$,$G$,$F$, which update the nodes scores and hidden states at each time step.} \label{fig:ranking} \end{figure} \textbf{Epidemic GNN.} The spread of epidemic through point contact is modeled by a GNN $E$. As the epidemic cannot spread by more than one hop per step, it is sufficient to model the spread with a single GNN layer. Formally, denote by $u\sim_{t}v$ an interaction beteen $u$ and $v$ at time $t$, and by $p_{vu}$ the probability of transmission during this interaction. For each $v$, the output of $E(\cdot)$ is a feature vector denoted by $e_v(t)$: \begin{align*} e_{v}(t) & =\sum_{u\sim_{t}v}p_{vu}(t)\cdot M_{e}(\zeta_{v}(t),\zeta_{u}(t);\theta_{m_e}), \end{align*} where $M$ is multilayer perceptron (MLP). Rather than considering the probability as an edge feature, this module mimics the epidemic transition rule to accelerate learning. \textbf{Information GNN.} The score of a node is affected both by the propagation dynamics, and by the information available to the agent. One may hope that since the former has a known timescale (days), on a short time scale (single day) the score of node would only be affected by its neighboring nodes. This, however, is not the true because information can propagate long distance in the graph almost instantaneously. As a simple example, consider nodes in a connected chain of (untested) nodes and note that they are statistically dependent. As a result, revealing the state of one node immediately affects the distribution over all nodes in the chain. With this consideration in mind, we designed an \textit{information GNN}, $I$, which represents the {\em information state} of each node. As discussed above, updated information on a node $u$ a few hops away from node $v$ may abruptly change our beliefs on the state of $v$. Furthermore, this change may occur even if $v$ and $u$ did not interact in the last time step but rather a while ago. To update the information state, we construct a cumulative multi-graph $G'$ where the set of edges between nodes $v$ and $u$ at time $t$ are all the interactions that occurred during the last $\tau$ steps, $\mathcal{E}_{G'}$=$\cup_{t'\in[t-\tau,t]}\mathcal{E}_{G}(t)$. The features of each edge in $\mathcal{E}_{G'}$, $\phi_{vu}(t')$, are the interaction delay $t-t'$ and the transmission probability $p_{v,v'}(t')$. The information features are the output of $k$-layer GNN; the $l^{th}$ layer is: \[ x_{v}^{l}(t)=\sum_{v'\sim_{t}v}M^{l}(x_v^{l-1}(t),x_{v'}^{l-1}(t),\phi_{vv'\text{\rq}(t)};\theta_M^l). \] As before, $M^l$ is an MLP, with $x_{v}^{0}(t)=\zeta_{v}(t)$ and $x_{v}^{k}(t)=i_{v}(t)$ are the final node features. The value of $\tau$, the information window size, was 7 in all our experiments. \textbf{Score and hidden state update.} For every node we hold a hidden state $h_{v}(t)$, which is updated following \begin{equation} h_{v}(t)=G(h_{v}(t-1),\zeta_{v}(t),e_{v}(t), i_{v}(t) ;\theta_{g}) \end{equation} After updating the new node hidden state, we use them to calculate the node score using a neural network $F$, \begin{equation} s_{v}(t)= F(h_{v}(t),h_{v}(t-1),\zeta_{v}(t);\theta_{f}) \end{equation} Here, $F$ is an MLP, while $G$ can be either an MLP or recurrent module such as GRU. \textbf{Sampling.} Given the score per node $s_v(t)$, we sample without replacement $k$ nodes iteratively. We (1) map the score of $n$ nodes to a probability distribution using a score-to-probability distribution function, (2) sample a node, and (3) adjust the distribution by removing its weight. We repeat this process $k$ iterations. \subsection{Design choices} \textbf{RL framework.} The action space of choosing a subset of $k$ nodes out of $n$ nodes is large even for small $n$ and $k$. Using an action-value approach like Q-learning implies that an approximate value is assigned to every possible action, but the action space size is prohibitively too large for action-value methods. Instead, we use a policy-gradient algorithm and model the problem as a ranking problem. The algorithm learns to rank nodes using a parameterized model, and then uses a sampling procedure to choose a subset of $k$ nodes. Many on-policy gradient algorithms use entropy to define a trust region. Computing the entropy requires summing ${ |\mathcal{V}| \choose k }$ terms at each step, and it is computationally expensive. A more scalable solution is the unbiased entropy estimator of \cite{Zhang2018a}, but the variance of that estimator is high. As an alternative, PPO trust region is not based on an explicit evaluation of the entropy, and performed better in our experiments. We also evaluated A2C, which did not perform as well as PPO in our experiments. \textbf{Critic module.} PPO, as an actor-critic algorithm, requires a critic module to estimate the value function in a given state. We construct the actor using an architecture that is similar to the ranking module, but apply to element-wise max operation on the rows (representing the nodes) of the input to the score module $F$ (\figref{fig:ranking}). This reduces $F$'s input to a single row of features, and the output is then a scalar rather than a vector. Importantly, the critic is parametrized by a different set of weights than the ranking module (actor). \textbf{Score-to-probability distribution.} Usually, node scores are converted to a distribution over actions using a softmax. As demonstrated in \cite{mei2020}, this approach is problematic as node probabilities decay exponentially with their scores, leading to two major drawbacks. It discourages exploration of low-score nodes, and in our case also limits sensitivity to the top of the distribution, instead of at the top-k selected. Instead, we define the probability to sample an action $a_{i}$ to be \begin{equation} \Pr(a_{i})=\frac{x_{i}'}{\sum x_{i}'}\quad \textrm{, with } x_{i}'=x_{i}-\min_{i}x_{i}+\epsilon, \label{eq: score-to-prob} \end{equation} where $\{x_{i}\}$ is the set of scores and $\epsilon$ a constant. By not using an exponential as in softmax, the probability differences between low scoring nodes and high scoring nodes become less extreme. Furthermore, the parameter $\epsilon$ controls the initial exploration ratio. In standard DNN initialization schemes (e.g., XAVIER), the initial value of $x_{i}$ is expected to be in [-1,1]. If $\epsilon\gg1$ than the dominant term in \eqref{eq: score-to-prob} is $\epsilon$. This promotes exploration initially, as all actions are likely to be sampled in the early training stages. \eli{We compare our approach with the recent escort transform \cite{mei2020}, which was shown to have good theoretical performance and is considered to be the state-of-the-art score to probability method. As shown in Sec. \ref{sec: Experiments}, our method outperforms the escort transform in this problem.} \textbf{Normalization in scale-free networks.} RNN are well-known to suffer from the problem of exploding or vanishing gradients. This problem is exacerbated in a RNN-GNN framework used for RL algorithms, because they may be applied for arbitrary long episodes, causing internal state to grow unbounded. This problem is particularly severe if the underlying graph contains hubs (highly connected nodes). One approach to alleviate this problem, is by including an RNN like a GRU module, where the hidden state values pass through a sigmoid layer. As the magnitude of the input grows, gradient become smaller and training slows down. Scale-free networks contain with high probability "hub" nodes that have high-degree, namely $O(n)$ neighbors. The presence of these hubs further aggravates this problem. As a simple case, consider a star graph with a large number of nodes. In a GNN framework, it receives updates from a large number of neighbors and its internal state increases in magnitude. The next time that the GNN module is applied (e.g., at the next RL step), the growing internal state increases the magnitude of the internal state of its neighbors. This leads to a positive-feedback loop that causes the internal state representation to diverge. Since RL algorithms may be applied for arbitrary long periods, the internal state may grow unbounded unless corrected. This problem can be solved by directly normalizing each node hidden state. We have experimented with various normalization methods, and found that $L_2$ normalization worked best, as shown in the next section. \textbf{Transition probabilities}. In the case of the COVID-19 pandemic, the transition probabilities can be estimated using the interaction properties, such as duration and inter-personal distance, using known epidemiological models. This was done by the government agency which provided our contact tracing network (see below). Alternatively, one can learn the transmission probability as a regression problem from known interactions (e.g, using data from post-infection questioning). Finally, if this information is not accessible, it is possible to omit the epidemic model \emph{E} from the proposed framework and use only the feature vector created by the information module \emph{I}. \section{Experiments \label{sec: Experiments}} \subsection{Compared approaches} We compare methods from three categorizes: A) programmed; B) supervised learning (SL) C) Reinforcement learning (RL). Each experiment was performed with at least three random seeds. There exist additional approaches designed for the vaccination problem, but, as discussed in Section~\ref{sec:related_work}, they are not appropriate for the setup studied here. More details about experiments and implementation, including network architecture, are given in Appendix \ref{sec:experimental details}. \textbf{A. Programmed baselines.} Most countries currently prioritize their testing based on fixed procedures determined in advance and not learned form data. We compare with two such methods to rank nodes. \textbf{(1) Infected neighbors.} Rank nodes based on the number of known infected nodes in their 2-hop neighborhood (neighbors and their neighbors). Each node $v$ is assigned a tuple $(I_{v}^{(1)},I_{v}^{(2)})$, and tuples are sorted in a decreasing lexicographical order. A similar algorithm was used in \cite{Meirom2015, 8071015} to detect infected nodes in a noisy environment. \textbf{(2) Probabilistic risk.} Each node keeps an estimate of the probability it is infected at time $t-1$. To estimate infection probability at time $t$, beliefs are propagated from neighbors, and dynamic programming is used to analytically solve the probability update. See Appendix \ref{sec:tree model} for details. \textbf{(3) Degree centrality.} In this baselines high degree nodes are prioritized. This is an intuitive heuristic and it is used frequently \cite{Salathe2010}. It was found empirically to provide good results \cite{Sambaturu}. \textbf{(4) Eigenvalue centrality.} Another common approach it to select nodes using spectral graph properties, such as the eigenvalue centrality (e.g., \cite{Preciado2014,Yang2020}). The main drawback of these programmed algorithms is that they do not exploit all available information about dynamics. Specifically, they do not use negative test results, which contain information about the true distribution of the epidemic over network nodes. \textbf{B. Supervised learning.} Algorithms that learn the risk per node using features of the temporal graph, its connectivity and infection state. Then, $k$ nodes with the highest risk are selected. \textbf{(5) Supervised (vanilla).} We treat each time step $t$ and each node $v_i$ as a sample, and train a 3-layer deep network using a cross entropy loss against the ground truth state of that node at time $t$. The input of the DNN has two components: A static component described in \secref{sec:ranking_module}, and a dynamic part that contains the number of infected neighbors and their neighbors (like \#1 above). Note that the static features include the, amongst other features, the degree and eigenvector centralities. Therefore, if learning is successful, this baseline may derive an improved use of centralities based on local epidemic information. \textbf{(6) Supervised (+GNN).} Like \#5, but the input to the model is the set of all historic interactions of $v_i$'s and its $d$-order neighbours and their time stamps as an edge feature. The architecture is a GNN that operates on node and edge features. We used the same ranking module as our GNN framework, but the output probability is regarded as the probability that a node is infected. \textbf{(7) Supervised (+weighted degree).} Same as \#6, but the loss is modified and nodes are weighted by their degree. Indeed, we wish to favour models that are more accurate on high-degree nodes, because they may infect a greater number of nodes. \textbf{(8) Supervised (+weighted degree +GNN).} Like \#6 above, using degree-weighted loss like \#7. \textbf{C. RL algorithms:} \textbf{\RLGN{}} is our algorithm described in \secref{sec:approach}. The input to \textbf{(9) RL-vanilla} is the same as in (\#1) and (\#6) above. Correspondingly, the GNN module of described in \secref{sec:approach} is replaced by a DNN similar to (\#6), while the rest of the RL algorithm remains intact. \subsection{Experiment details and evaluations} \textbf{Training.} We train the RL and SL by generating random networks, and selecting for each instance a random subset of $m_{0}$ initially infected nodes. We propagate the epidemic until it spans at least $k_{0}$ infected nodes (for at least $t_{0}$ steps), and randomly detect a subset of the infected nodes of size $<k_{0}$. The simulation then follows the agent-network dynamics described in \secref{sec:problem_formulation}. \textbf{Evaluation Metrics.} The end goal of quarantining and epidemiological testing is to minimize the spread of the epidemic. As it is unreasonable to eradicate the epidemic using social distancing alone, the hope is to ``flatten the curve'', namely, to slow down the epidemic progress. \eli{Equivalently, for a simulation with fixed length, the goal is to reduce the number of infected nodes.} We use two success metrics: (1) \textbf{\% healthy:} The percent of nodes kept healthy throughout the simulation. (2) \textbf{\%contained:} The probability of containing the epidemic. This was computed as the fraction of simulations having cumulative infected nodes smaller than a fraction $\alpha$. We focus on this metric because it captures the important notion of the capacity of a health system. In the 2-community setup, where each community has half of the nodes, a natural choice of $\alpha$ is slightly greater than $0.5$, capturing those cases where the algorithm contains the epidemic within the infected community. In all the experiments we set $\alpha=0.6$. The only exception is the three-communities experiments, in which we set the bar slightly higher than $1/3$, and fixed $\alpha=0.4$. \subsection{Network datasets and models} We study three types of networks which differ by their connectivity patterns. \textbf{(1) Community-based networks} have nodes clustered into densely-connected communities, with sparse connections across communities. We use the \textit{Stochastic Block Model} (SBM, \cite{abbe2017community}), for 2 and 3 communities. The Stochastic Block Model (SBM) is defined by (1) A partition of nodes to $m$ disjoint communities $C_{i}$, $i=1\dots m$; and (2) a matrix $P$ of size $m\times m$, which represents the edge probabilities between nodes in different communities, namely, the matrix entry $P_{i,j}$ determines the probability of an edge $(v,v')$ between $v\in C_{i}$ and $v'\in C_{j}$. The diagonal elements in $P$ are often much larger than the off-diagonal elements, representing the dense connectivity in a community, compared to the intra-connectivity between communities. \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{figs/three_communtities.png} \caption{Supervised vs RL with 3-community networks. \textbf{Left:} RLGN successfully learns to contain the epidemic 60\% of the time, while SL fails. \textbf{Right:} SL isolates many more infected nodes, but less important ones.} \label{fig:three_communities} \end{figure} \textbf{(2) Preferential attachment (PA)} networks exhibit a node-degree distribution that follows a power-law (scale-free), like those found in many real-world networks. We use the dual Barbarsi-Albert model \cite{Moshiri2018}, which allows for continuously varying the mean node degree. \textbf{Generating temporal graphs.} Static networks generated using PA or SBM are converted to a temporal graph by first selecting a random subset of edges $\mathcal{E}(t)$ at each time step $t$, and then assigning to each edge a transmission probability $q_e(t)$ sampled uniformly $U[a,b]$. \textbf{(3) Contact-tracing networks.} We received anonymized high-level statistical information about real contact tracing networks that included the distribution of node degree, transmission probability and mean number of interactions per day, collected during April 2020. \begin{figure} \centering \begin{tabular}{cc} \includegraphics[width=0.5\columnwidth]{figs/fig1}& \includegraphics[width=0.5\columnwidth]{figs/fig2}\\ (a) & (b) \end{tabular} \caption{Statistics of a real-world contact-tracing graph. (a) The empirical transition probability $P(p_e)$ on a contact tracing network and our suggested curve fit. (b) The degree distribution on the contact tracing network, along with its fit.} \label{fig:transmission_prob} \end{figure} Fig. \ref{fig:transmission_prob}(b) presents the degree distribution in this data, and the transmission probability is presented in Fig. \ref{fig:transmission_prob}(a). The latter was derived based on the contact properties, such as the length and the proximity of the interaction. On average, $1.635\pm0.211$ interactions with a significant transmission probability were recorded per-person per-day. We generated random networks based on these distributions using a configuration model framework \cite{Newman2010a}. The fitted model for the degree distribution is a mixture of a Gaussian and a power-law distribution \begin{align} P(degree=x)=2.68\cdot\mathcal{N}(-4.44,11.18)+3.2\cdot10^{-3}\cdot x^{-0.36}. \end{align} The fitted model for the transmission probability is a mixture of a Gaussian and a Beta distribution \begin{align} P(p_{e}=x)=0.47\cdot\mathcal{N}(0.41,0.036)+0.53\cdot Beta(5.05,20.02). \end{align} \begin{table} \centering \begin{tabular}{|l|c|c|} \hline & \#Nodes & \#Edges\\ \hline \hline CA-GrQc & 5242 & 14496\\ \hline Montreal & 103425 & 630893\\ \hline Portland & 10000 & 199167\\ \hline Enron & 32430 & 54397\\ \hline GEMSEC-RO & 41773 & 222887\\ \hline \end{tabular}\caption{\label{tab:datasets-info}Number of edges and nodes in the large-scale datasets} \end{table} \textbf{(4) large-scale datasets.} We consider graphs of different sizes and sources: (A) A research collaboration network (CA-GrQc), representing social interactions between researchers. In addition to social interaction, information also diffuses on this network \cite{network_database}. (B) The Montreal dataset (Montreal), based on WiFi hotspot tracing, collected in Montreal, Canada over three years, representing a proximity network \cite{Hoen2015}. (C) a compartment-based synthetic network, derived from first principles, using a population census in Portland, Oregon (Portland) \cite{Wells2013,Eubank2004}. (D) An email network (Enron), representing a computer network on which malwares spread, (E) An online social network. We used the recent GEMSEC-RO \cite{rozemberczki2019gemsec}, presenting friendship relations in the Deezer music service in Romania. This accommodates for a graph on which preferences and product adaption (songs) propagate. All these networks have been extensively used in previous work, in particular epidemiological studies, as key networks models \cite{Sambaturu, Yang2020, Hoen2015, Herrera2016,Wells2013,Eubank2004}. Table \ref{tab:datasets-info} summarizes the various datasets, spanning graphs with 5K nodes to graphs with more than 100K nodes. \begin{table} \centering \setlength{\tabcolsep}{3pt} \scalebox{0.97}{{\sc{ \begin{tabular}{|l|c|c|} \hline \%contained & 2 communities & 3 communities \\ \hline \hline Tree-based model & $15\pm 35$ & $0\pm0$ \\ \hline Counter model & $19\pm39$ & $ 1\pm 4$ \\ \hline Degree centrality & $23\pm1$ & $0\pm0$ \\ \hline Eigenvector centrality & $19\pm3$ & $0\pm0$\\ \hline Supervised (vanilla) & $24\pm 11$ & $2\pm 2$ \\ \hline Supervised +GNN & $27\pm 10$ & $ 2\pm 2$ \\ \hline Supervised +degree & $29\pm 10$ & $ 1\pm 2$\\ \hline Supervised +GNN+deg & $24\pm 10$ & $2\pm 02$\\ \hline \RLGN{} (Vanilla) & $66\pm 10$ & $7\pm 5$ \\ \hline \RLGN{} full (ours) & \textbf{88}{$\boldsymbol{\pm}$}\textbf{1} & \textbf{53}{$\boldsymbol{\pm}$}\textbf{13} \\ \hline \end{tabular} }}} \caption{Probability (in \%) of containing an epidemic in community-based networks. Each community has $30$ densely connected nodes, and the test budget is $k=2$. } \label{tab:comaprison-chart} \end{table} \begin{table} \centering \setlength{\tabcolsep}{3pt} \scalebox{0.99}{{\sc{ \centering \begin{tabular}{|l|c|c||c|c|} \hline & \multicolumn{2}{c}{\%contained} & \multicolumn{2}{c}{\%healthy} \\ \hline & PA & CT & PA & CT\\ \hline \hline Tree based model & $1\pm1$ & $0\pm0$ & $10\pm7$ & $11\pm3$\\ \hline Counter model & $0\pm0$ & $0\pm0$ & $7\pm7$ & $14\pm5$ \\ \hline Degree centrality & $22\pm4$ & $0\pm1$ & $30\pm2$ & $16\pm1$ \\ \hline Eigenvector centrality & $21\pm1$ & $0\pm1$ & $30\pm1$ & $16\pm1$ \\ \hline SL (vanilla) & $2\pm2$ & $0\pm0$ & $13\pm3$ & $17\pm1$\\ \hline SL + GNN & $27\pm6$ & $15\pm4$ & $34\pm3$ & $32\pm$2\\ \hline SL + deg & $3\pm3$ & $0\pm1$ & $15\pm3$ & $18\pm1$\\ \hline SL + deg + GNN & $26\pm5$ & $16\pm5$ & $33\pm3$ & $32\pm1$\\ \hline RL (vanilla) & $2\pm2$ & $1\pm1$ & $17\pm1$ & $16\pm1$\\ \hline RLGN (ours) & \textbf{78}{$\boldsymbol{\pm}$}\textbf{4} & \textbf{45}{$\boldsymbol{\pm}$}\textbf{6} & \textbf{52}{$\boldsymbol{\pm}$}\textbf{2} & \textbf{40}{$\boldsymbol{\pm}$}\textbf{1} \\ \hline \end{tabular} }}} \caption{\%contained epidemics and \%healthy nodes achieved on a preferential attachment (PA) network, and contact tracing (CT) network. In both cases, networks had $200$ nodes.} \label{tab:comaprison-chart-scale-free} \end{table} \subsection{Results} \label{sec:results} In a first set of experiments, we compared 7 approaches for learning and inference on 3 network types. The results reported in Table \ref{tab:comaprison-chart} and \ref{tab:comaprison-chart-scale-free} show that RLGN outperforms all baselines in all network types. A video highlighting the results can be found \href{https://youtu.be/js9v7_LKppg}{online} \footnote{Link: \url{https://youtu.be/js9v7_LKppg}}. To gain insight into this result, we first look more deeply into the case of 3-community networks. \figref{fig:three_communities}(a) traces the fraction of contained epidemics and \figref{fig:three_communities}(b) the fraction of infected nodes during training. The supervised learning algorithm detects substantially more infected nodes (right panel) than RLGN, but these tend to have lower future impact on the spread, and it fails to contain the epidemic (left). A closer look shows that RL, but not SL, successfully learns to identify and neutralize the critical nodes that connect communities and prevent the disease from spreading to another community. To further understand the solutions learned for PA networks, consider the following two extremes. First, when a network is very sparsely connected, it would be easy to cut long infection chains, and both approaches are expected to be successful. At the other extreme, for densely connected networks, there are no critical nodes, because there are many paths between any two nodes. To study this effect we generated networks with the preferential-attachment mechanism, while varying the mean node degree. This degree can also be viewed in terms of the $R_0$ coefficient, the mean number of nodes infected by a single diseased node. The greater $R_0$, the more difficult it is to contain the epidemic. \begin{figure} (a)\hspace{120pt} (b)\hspace{120pt}\\ \includegraphics[width=0.48\columnwidth]{figs/phase_shift.png} \includegraphics[width=0.48\columnwidth]{figs/stability_analysis} \caption{\textbf{Stability analysis:} \textbf{(a)} The contained epidemic fraction as a function of the basic reproduction number $R_0$ on a PA network. RLGN outperforms SL over a large range of $R_0$ values. \textbf{(b)} Stability against test-time shift in transmission probability. \textit{Orange:} The performance of RLGN deteriorates when the mean transmission probability at test time is higher more than $40\%$ than train time. \textit{Purple:} As a baseline, training and testing with the same higher transmission probability. \label{fig:stability} } \end{figure} Fig.~\ref{fig:stability}(a) quantifies this effect, showing the percent of contained epidemics as a function of the $R_0$ coefficient. RL has a significant advantage over supervised+GNN for a range of $R_0$ values between $2.0$ and $2.9$. Finally, \figref{fig:stability}(b) depicts a robustness analysis of \RLGN{} for variations in the epidemiological model. One of the most difficult quantities to assess is the probability for infection per social interaction. \figref{fig:stability}(b) shows that the trained model can sustain up to $\sim40\%$ deviation at test time in this key parameter. \iffalse \begin{figure} \centering \includegraphics[width=1\columnwidth]{figs/moving_histogram.png} \caption{The fraction of infected nodes as a function of time step $t$. The epidemic propagtes more slowly under RLGN compared with the best baseline (supervised+GNN, \#4). Shaded areas represent one standard deviation around the mean. Experiment was performed on a preferential attachment network with $300$ nodes and mean degree $2.8$. \label{fig:epidemic-speed} } \end{figure} \fi \begin{figure} \begin{tabular}{ccc} (a) GamesecRO & (b) Enron & (c) ca-GrQc\\ \includegraphics[width=0.31\columnwidth]{figs/mean_per_step_soc-gemsec-RO.png} & \includegraphics[width=0.31\columnwidth]{figs/mean_per_step_ia-email-EU.png} & \includegraphics[width=0.31\columnwidth]{figs/mean_per_step_ca-GrQc.png} \end{tabular} \caption{The fraction of infected nodes as a function of time step $t$. Shaded areas represent one standard deviation around the mean. (a) The epidemic propagation on an online social (gemsec-RO) (b) The epidemic propagation on an email network (Enron). (c) The epidemic propagation on the collaboration graph ca-GrQc. In all cases the epidemic propagates more slowly under RLGN compared with the best baseline (supervised+GNN, \#4). \label{fig:epidemic-speed} } \end{figure} \subsection{Robustness of results} We have tested the robustness of our results to the underlying graph size. Specifically, we compare the two best algorithms RLGN (\#8) and SL+GNN (\#4), using graphs with various sizes, from 300 nodes to 1000 nodes. Table \ref{tab:300-nodes-pa} compares RLGN with the SL+GNN algorithm on preferential attachment (PA) networks (mean degree $=2.8$). We provide results for various sizes of initial infection $i_{0}$ and number of available tests $k$ at each step. The experiments show that there is a considerable gap between the performance of the RL and the second-best baseline. Furthermore, RLGN achieves better performance than the SL+GNN algorithm with 40\%-100\% more tests. Namely, it increases the effective number of tests by a factor of $\times1.4-\times2$. We also tested the sensitivity of the results to the relative size of the initial infection. Table \ref{tab:300-nodes-pa} shows results when 4\% of the the network was initially infected, as well as for 7.5\% and 10\%. The results show that RLGN outperforms the baselines in this wide range of infection sizes. \begin{table} \centering \setlength{\tabcolsep}{3pt} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=300$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $27\pm2$ & $15\pm5$ & $21\pm2$ & $4\pm2$ & $18\pm1$ & $1\pm1$\\ \hline SL, $k=1.33\%$ & $41\pm3$ & $37\pm6$ & $27\pm2$ & $12\pm4$ & $24\pm2$ & $6\pm3$\\ \hline SL, $k=2\%$ & ${66\pm4}$ & $76\pm6$ & ${48\pm3}$ & $55\pm7$ & $37\pm2$ & $32\pm6$\\ \hline RLGN, $k=1\%$ & $50\pm2$ & ${78\pm7}$ & {$43\pm2$} & ${58\pm1}$ & ${40\pm1}$ & ${48\pm6}$\\ \hline \end{tabular} \vspace*{0.2 cm} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=500$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $24\pm2$ & $7\pm4$ & $20\pm1$ & $2\pm1$ & $19\pm1$ & $0\pm1$\\ \hline SL, $k=1.6\%$ & $48\pm3$ & $54\pm6$ & $35\pm2$ & $27\pm7$ & $29\pm1$ & $11\pm1$\\ \hline SL, $k=2\%$ & ${67\pm3}$ & $83\pm5$ & ${46\pm2}$ & $53\pm4$ & $38\pm2$ & $37\pm7$\\ \hline {RLGN, ${k=1\%}$} & $52\pm1$ & ${97\pm2}$ & ${44\pm2}$ & ${75\pm11}$ & ${42\pm1}$ & ${66\pm6}$\\ \hline \end{tabular} \vspace*{0.2 cm} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=1000$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. Infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $25\pm2$ & $5\pm3$ & $21\pm1$ & $0\pm1$ & $19\pm1$ & $0\pm0$\\ \hline SL, $k=1.5\%$ & $42\pm2$ & $49\pm6$ & $30\pm1$ & $10\pm3$ & $27\pm1$ & $4\pm2$\\ \hline SL, $k=2\%$ & ${66\pm1}$ & $84\pm5$ & ${45\pm2}$ & $59\pm5$ & $37\pm1$ & $30\pm1$\\ \hline {RLGN, ${k=1\%}$} & $52\pm1$ & ${97\pm2}$ & ${44\pm2}$ & ${75\pm11}$ & ${42\pm1}$ & ${66\pm6}$\\ \hline \end{tabular} \caption{A comparison between RLGN and SL+GNN (the best baseline). RLGN performance is highlighted. The number of additional resources needed to surpass the RLGN performance in a given metric is also highlighted. In many cases, even using SL+GNN with twice as many resources than RLGN performs worse than RLGN. The evaluation was performed on a preferential attachment network with mean degree $2.8$. The number of nodes is indicated at the top of each table.} \label{tab:300-nodes-pa} \end{table} \subsection{Inference on large graphs and real-world networks} We further evaluated how models trained on medium-size graphs generalize to perform inference on much larger graphs. Specifically, we trained RLGN and SL+GNN (three model initialization for each) on a preferential attachment network with $1000$ nodes and evaluated its performance on various larger graphs. We investigated the progression of the epidemic under either RLGN or supervised+GNN algorithms. Figure \ref{fig:epidemic-speed} shows that the epidemic spread speed is slower under the RLGN policy in all graph. In general, there are two extreme configuration regimes. First, the ``too-hard" case, when the number of tests is insufficient to block the epidemic, and second, the ``too-easy" case when there is a surplus of tests such that every reasonable algorithm can contain it. The more interesting case is the intermediate regime, where some algorithms succeed to delay the epidemic progression, or block it completely, better than other algorithms. Fig. \ref{fig:epidemic-speed}(a) illustrates the case where the number of tests is insufficient for containing the epidemic, for all algorithms we tested. In Fig. \ref{fig:epidemic-speed}(b), the number of tests is insufficient for SL to block the epidemic. However, with same number of tests, RLGN algorithm successfully contains the epidemic. Fig. \ref{fig:epidemic-speed}(c) presents an interesting case where RLGN slows down the epidemic progression and reduces the number of total number of infected node, compared with SL, but RL does not contain it completely. \begin{table} \centering{}% \begin{tabular}{|l|c|c|c|c|c|} \hline & CA-GrQc & Montreal & Portland & Enron & GEMSEC-RO\\ \hline \hline Degree Centrality & $25.52\pm0.01$ & $12.83\pm0.01$ & $0.67\pm0.01$ & $71.14\pm0.02$ & $2.43\pm0.01$\\ \hline Eigenvector Centrality & $25.37\pm0.01$ & $8.06\pm0.01$ & $0.04\pm0.01$ & $55.10\pm0.02$ & $2.41\pm0.01$\\ \hline SL & $29.79\pm0.02$ & $23.09\pm0.03$ & $1.57\pm0.01$ & $68.45\pm0.05$ & $4.26\pm0.01$\\ \hline RLGN & \textbf{42.69}{$\boldsymbol{\pm}$}\textbf{0.03} & \textbf{39.68}{$\boldsymbol{\pm}$}\textbf{0.03} & \textbf{3.71}{$\boldsymbol{\pm}$}\textbf{0.01} & \textbf{89.19}{$\boldsymbol{\pm}$}\textbf{0.02} & \textbf{6.52}{$\boldsymbol{\pm}$}\textbf{0.01} \\ \hline \end{tabular}\caption{\label{tab:dataset-healthy}The mean percentile of healthy nodes after a 20 steps. RLGN perform better on all datasets with a statistically significant gap. } \end{table} Table \ref{tab:dataset-healthy} compares the performance of the RLGN and the best baseline (SL) on the large-scale datasets. We included the centralities baselines (\#3,\#4) in the comparison as they are heavily used in epidemiological studies. Table \ref{tab:dataset-healthy} shows that the RLGN consistently performs better than the baselines, and the gap is clearly statistically significant. Finally, we evaluated the performance of RLGN on a Preferential Attachment network with $50,000$ nodes (mean degree $=2.8$), as this random network model is considered a reasonable approximation for many other real world networks. We found that RLGN successfully contained the epidemic in all $150$ evaluation episodes, while the SL+GNN was unable to block the epidemic even once. The mean percentile of healthy nodes at the end of the episode was $51\pm1$ for RLGN, while for the SL+GNN it was only $21\pm2$, a difference of more than $15$ STDs. \subsection{Ablation Studies} \subsubsection{Mapping scores to action distribution.} We compare the performance of our score-to-probability function (calibrated-scores) to the popular softmax (Boltzmann) distribution. In practice, in most instances, we were unable to train a model using the softmax distribution as the neural network weights diverge. Fig.~\ref{fig:score-to-prob} presents the training curve in one of the few instances that did converge. It is clear that the model was not able to learn a useful policy while using the calibrated-scores probability function resulted in a corresponding value of more than $0.75$. \begin{figure} \centering \includegraphics[width=0.55\columnwidth]{figs/score_to_prob_ablation.png} \caption{The fraction of contained epidemics during training on a preferential attachment model with $200$ nodes and a mean degree $2.8$. For non-normalized mapping, only one of the three seeds in the softmax distribution simulation completed training due to numerical instability. No stability issues were observed when using the calibrated scores normalization scheme described by Eq. \eqref{eq: score-to-prob}. \label{fig:score-to-prob}} \end{figure} \begin{table} \centering \begin{tabular}{|c|c|c|} \hline & $\%contained$ & \# training epochs\\ \hline \hline Sigmoid & $0.84\pm0.05$ & 1210\\ \hline GRU & $0.91\pm0.03$ & 810\\ \hline $L_{2}$ norm. & $\mathbf{0.93\pm0.02}$ & \textbf{500}\\ \hline \end{tabular} \caption{\label{tab:norm-table} Training time and fraction of contained epidemic for three normalization schemes. The $L_2$ normalization scheme is fastest and achieves the best performance.} \end{table} \subsubsection{Normalization in scale-free networks.} We compared the suggested normalization to a number of other alternative normalization methods. (1) Applying a sigmoid layer after the hidden state update module $G$. (2) Replace the hidden state update module with a GRU layer. (3) Apply $L_2$ normalization to each feature vector $h_v(t)$ (similarly to \cite{Hamilton2017}) (4) Normalize the feature vector matrix by its $L_2$ norm. These four normalization schemes span three different types of normalization: single-feature normalization (1+2), vector normalization (3), and matrix normalization (4). Table \ref{tab:norm-table} presents the score after training and the number of training steps required to complete training. Method (4) was unstable and training did not converge, therefore it was omitted from the table. The main reason for the training time difference is that without normalization, the DNN weights' magnitude increases. In a GRU module, or with a direct application of a sigmoid layer, the features pass through a sigmoid activation function. When the magnitude of the input to this layer is large, the gradient is very small due to the sigmoid plateau. This substantially slows down the learning process. \subsubsection{Information processing module. } Our experiments showed the information module has a critical role in improving the performance of the RL-GNN framework. We performed an ablation study by removing it completely from our DNN module, keeping only the epidemic module. The full DNN module achieved a contained epidemic score of $0.77\pm0.06$, while the ablated DNN module corresponding score was $0.62\pm0.10$, a degradation of more than $20\%$. \section{Extensions\label{sec:extensions}} The approach and model discussed in this paper can be applied to important problems other than epidemic control. \eli{ We go into details for the Influence maximization problem. We show how it can be mapped to our general formalism, and present experimental results. We follow with sketches of additional extensions, but each of them is worthy of a study on its own} {\bf Influence maximization (IM).} Unlike epidemic control, in IM, the decision maker objective is to maximize the spread of some opinion on a social network graph. It acta to select nodes to be influenced by presenting information, actively contacting them, or sending coupons etc. Given a budget, the IM agent can only contact a limited number of nodes over a period of time. Specifically, in this setup all nodes are initially at the \emph{Susceptible} state. The agent choose $k$ nodes at each time step, and for each chosen node $v$, its state (opinion) is change to \emph{Infected} with probability $q$. If the node is infected, it may change its neighbors toward its opinion with probability $p_e(t)$, where $e\in \mathcal{E}(t)$. At each time step, influenced (infected) node may revealed their state with probability $\zeta$, for example, by clicking on ads or by registering with the influencing agent. The goal of the agent is to maximize its influence over the graph. Fig. present the result of the various algorithm in the problem, in which both the dynamics and goal are very distinguished from the previous setup. Here, too, the RLGN algorithm outperforms the other baselines. {\bf Fake news detection and confinement.} Consider a social network where fake news can be maliciously distributed, and spread over the network. A decision maker can verify the authenticity of items, but only verify a limited number of items per a time period. Once a fake item is detected, it is erased from the network. The objective is to minimize the total number of nodes that observe fake items. The main difference from the epidemic problem is that once a fake item is discovered, it can be erased from the entire network. The trade-off is that the decision maker does not want to waste inspection resources on items that are likely to die out. The fake new control and confinement problem can be therefore naturally cast within the framework outlined here. {\bf Epidemic Control: Beyond Node Selection}. While this paper addressed the important problem of deciding which nodes to examine given a certain umber of tests, we can also ask what if not only the subset of nodes to be tested, but also \emph{the number of tests} to be performed can be controlled. Increasing the number of tests will help us contain the epidemic, however, it may be expensive to increase the number of tests and economy of scale may not work here. Another form of control is imposing a partial quarantine that reduces the number of interactions and resulting infections. Such a quarantine would come with a cost, of course. Both variations, and others, can be easily modeled within the framework presented in this paper. The crucial aspects of the model is having a objective that is cumulative reward structure, and an action space that depends only on the information states. \section{Conclusions} This paper shows that combining RL with GNNs provides a powerful approach for controlling spreading processes on graphs. In the context of COVID-19 spread, we demonstrated that using an RL+GNN approach allows us to confine the spread of an epidemic that is approximately 30\% more contagious (i.e., $R_0$ that is 30\% higher) with the same resources as a standard supervised learning-based approach. In addition, our results indicate that prioritizing tests using RL on temporal graphs can increase the number of healthy people by $25\%$ and contain the epidemic $30\%$ more often than supervised approaches and $2.5\times$ more often than non-learned baselines using the same resources. \bibliographystyle{acm} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[acmsmall]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} Consider the problem of an epidemic spreading in the population, without any known cure or vaccination procedure. To contain the disease and prevent it from spreading, it becomes critical to detect infected carriers and isolate them; see Fig.~\ref{fig:viralinfection} for an illustration. As the epidemic spreads, the demand for tests outgrows their availability, and not all potential carriers can be tested. It becomes necessary to identify the most likely epidemic carriers using limited testing resources. This raises a major question: How can we rank candidates and prioritize testing to prevent the disease from spreading? This prioritization problem is an important example of a family of problems: learning to control diffusive processes over networks through nodal interventions. Other examples include opinions spreading on social network, product adaption, viruses inflicting computer networks and cascades of failures in server farms. In all these cases, the dynamics of the system can be steered using interventions that modify the states of a (relatively) small number of nodes. For instance, infected people can be asked to self-quarantine, preventing the spread of a disease, at-risk computers can be patched by security updates, and users may be selected and be exposed to new information to influence their opinion. \begin{figure}[t] \centering \includegraphics[width=0.60\columnwidth]{figs/RL_graphs_fig1_trimmed.png} \caption{A viral infection process on a graph and an intervention aimed to stop its spread. Here, graph nodes represent people and edges represent interactions. At $t=1$ only two people are infected (red). At $t=2$ several interactions resulted in new \textit{exposed} people (yellow); At $t=3$ the blue node was selected to be quarantined to stop the viral spread. This paper presents a framework for learning how to select which nodes should be quarantined. }\label{fig:viralinfection} \end{figure} The problem of controlling the dynamics of a system using localized interventions is very hard, and for several reasons. First, it requires to make decision in a continuously changing environment with complex dependencies. Second, to solve the problem one must assess the potential downstream ripple effect for any specific node that becomes infected, and balance it with the probability that the node indeed becomes infected. Finally, models must handle noise and partial observability. We pose the problem of controlling a diffusive process on a temporally evolving graph as a sequential decision making problem in the context of a partially-observed Markov decision process. We then formulate the problem of selecting a subset of nodes for dynamical intervention as a {\em ranking } problem, and design an actor-critic RL algorithm to solve it. We use the observed changes of nodes states and connections to construct a temporal multi-graph, which has time-stamped interactions over edges, and describe a deep architecture based on GNNs to process it. To the best of our knowledge, this work is the first work that consider Deep RL in the context of a temporally evolving graph. The current work combines three research fields: dynamic processes on temporal graphs, deep graph learning and reinforcement learning. Combining these three into a cohesive model raises several new challenges. Most importantly, the model must learn to handle two types of dynamics: learn to infer the potential risk of not removing a node, and learn to predict the probability that a node becomes infected. As explained below, these two processes operate on different time scales. To address this issue, our architecture contains two separate GNN modules, taking as input a multi-graph over the nodes, where edges are time-stamped with the time of interactions. Also, we show below that combining RL with temporal graphs requires to stabilize how information is aggregated from neighbors when updating nodes hidden states, and control how actions are sampled during training to ensure sufficient exploration. We show empirically the beneficial effects of these components. This paper demonstrates that combining RL with GNNs provides a powerful approach for controlling spreading processes on graphs. In the context of COVID-19 spread, we show that using the RL-GNN approach increases the fraction of healthy by $25\%$ and allows for confining the spread of an epidemic $30\%$ more often, and $3\times$ times more often that using non-learned approaches. ~\newline This paper makes the following contributions:\\ {\bf (1)}~A new framework for controlling the dynamics of diffusive processes over graphs. Namely, learning to perform local interventions to steer the global dynamics of a graph-based dynamical system. \\ {\bf (2)}~A new architecture for this problem, and a way to train a decision-making agent using reinforcement learning to prioritize interventions on the temporal multi-graph. \\ {\bf (3)}~An observation of the interplay between the dynamics of graph states and how information flows over the graph for a decision making agent, which motivates the design of our deep network architecture. \\ {\bf (4)}~A set of benchmarks and strong baselines for this problem. This includes statistics collected from real-world contact tracing data for COVID-19. Our RL approach achieves superior performance over these datasets, often significantly. \section{Previous work \label{sec:related_work}} Our work is in the intersection of a few disciplines. We tackle the problem of \emph{controlling a dynamic process} by considering it as \emph{ranking problem on a temporal graph}. As a particular example, we address the problem of a controlling a viral epidemic spreading on a social graph. \textbf{Deep Learning on graphs.} Graph neural networks (GNNs) are deep neural networks that can process graph-structured data. GNNs became very popular and were shown useful for solving a variety of tasks including social network analysis \cite{kipf,fan2019graph} and molecule property prediction \cite{Gilmer2017,Duvenaud2015}. Perhaps the most popular GNN models are Message Passing Neural Networks (MPNN) \cite{Gilmer2017, Hamilton2017, Velickovic2017}, which operate by repeatedly updating the feature vector of each node by aggregating information from its neighbourhood. Several works combine recurrent mechanisms with GNNs to learn temporal graph data, e.g., \cite{guo2019attention, zhao2019t, fang2019gstnet,yu2017spatio} tackled the traffic forecasting problem . \cite{li2019study,kapoor2020examining} proposed a graph-structured RNN for coarse spatial prediction of epidemic spread. Unlike this work, these works model the epidemic spread and do not try to intervene with the diffusive process. More generally, several recent studies \cite{liu2019towards, rossi2020temporal, liu2020towards, pareja2020evolvegcn} tackle a setup in which both nodes and edges vary over time, with applications in social network analysis and other fields. Further information can be found in \cite{kazemi2020representation}. \textbf{Ranking on graphs.} The problem of ranking on graphs is a fundamental problem in Computer Science, in which the task is to rank the nodes of a given graph according to some criteria. It has various applications such as web page ranking \cite{page1999pagerank,agarwal2006ranking} and knowledge graph search \cite{xiong2017explicit}. \textbf{Reinforcement learning and graphs.} Recently, a surge of work combining Reinforcement Learning and graphs emerged. These works can be split into two main categories: leveraging graph structure for general RL problems (e.g., \cite{Zhang2018,Jiang2018}), and applying reinforcement learning methods for graph problems. Our work falls into the latter. An important line of work uses Reinforcement Learning to solve NP-hard combinatorial optimization problems defined on a graph \citep{Zhu,Dai}. Another common application is the usage of RL for path searching in a knowledge graph \citep{xiong2017explicit,Das}. Reinforcement learning was also shown in a few other graph problems, such as chemical reaction prediction \cite{Do2018}. \textbf{Dynamic processes on graphs. } Modelling diffusive processes is an active research field. Key models such as SIR (Suscpetible-Infected-Removed) and SIS (Suscpetible-Infected-Suscpetible) \cite{Newman2010a} to the recent SEIR (Suscpetible-Exposed-Infectious-Removed) COVID-19 epidemic model \cite{Lin2020,Lopez2020} have proven useful in modelling the spread of contagions. The application of these models is extended, and varies from early epidemic detection \cite{Meirom2015}, to influence maximization \cite{Kempe2003} and network security \cite{Gourdin2011}. Recently, researchers have also used deep learning to forecast epidemic growth, e.g., \cite{Adhikari2019, Rodriguez2020}. The problem of node manipulation (e.g., vaccination) for controlling epidemic processes on graphs was intensively studied \cite{Hoffmann2020, Medlock2009}. This problem is often addressed in the setup of the fire-fighter problem and its extensions \cite{firefighter_survey, Tennenholtz2017, Sambaturu}. Common approaches include include developing centrality measures designed to highlight bottleneck nodes \cite{Yang2020}, or using spectral methods for allocating resources \cite{Saha2015, Preciado2014, Ogura2017}. Alternative line of research \cite{MILLER2007780, Cohen2002} developed heuristics for the same task. Our setup differs from these work in three important aspects. First, we do not assume a node can be vaccinated or immunized against the epidemic. In a realistic scenario, once a vaccination is discovered it will be rapidly distributed to the masses. For example, in the context of a computer malware, distributing the vaccine can be easily applied to every node by means of a software patch. In other cases, such as human epidemics, it is likely that factors such as underlying personal health condition (e.g, if a person is at increased risk) will be the dominant factor in prioritizing vaccination. Therefore, here we consider the problem at its pre-vaccination stage, where every node is susceptible to the disease. Second, we do not assume a node can be quarantined or disconnected from the graph without justification, namely, without a positive test result. It may be tempting to isolate a high-degree node from the network, like putting a bus-driver in quarantine or disconnecting a hub computer from the network, but we view this solution as problematic. Nodes perform required network functionality. Removing a load balancer without a proper replacement will substantially impair the computer network functionality. Quarantining a bus driver due to her connectivity pattern will result in either replacing the bus driver with another driver with the same interactions pattern, or the transportation network functionality will deteriorate. In other words, a preemptive node removal would either not affect the network connectivity or impair the network functionality. Therefore, we assume that a node can be put in isolation only {\em after} it tests positive for infection. Finally, most previous works considered a setup in which a single vaccination decision is taken at $t=0$ (with a possible delay execution), based only on the information available at $t=0$ . In our setup, the agent needs to decide at each time step $t$ on its testing policy, given the information available at $t\ge 0$, which include the results of past actions. Furthermore, the agent \emph{is aware to the fact that it may take additional action at later times}. The agent needs to balance between retrieving information (for better informed future decisions), maximizing the probability that the immediate intervention will be successful, and optimizing the long-term goal that depends the stochastic epidemic evolution, current action and future actions. The agent needs to optimize the trajectory of test allocations, where each decision is taken under different information setting. In contrast to other work, the agent need not only know where to test, but also when to test each node, in a partially observed setup with little information. \section{A motivating example} We begin with an example to illustrate the trade-offs of the problem. A natural algorithmic choice would be to act upon nodes that are most likely infected. The following example shows why this approach is suboptimal. We form a time-varying graph from a list of interactions between nodes at various times. If $u,v$ interacted at time $t$ then the edge $(u,v)$ exists at time $t$. Each interaction is characterized by a transmission probability $p_e(t)$. If a node was infected at time $t$ and its neighbor was healthy, then the healthy node is infected with probability $p_e(t)$. For the purpose of this example, assume we can test a single node at odd timesteps. If the node is identified as infected, it is sent to quarantine and cannot further interact with other nodes. Otherwise, we do not perturb the dynamics and it may interact freely with its neighbors. Our goal is to minimize the number of infected nodes. Consider the "two stars" network in \figref{fig:toy-example}. The left hub (node $v_1$) has $m_1$ neighbors, and $m_2$ nodes are attached to the right hub $v_2$. At $t=0,$ only the edge $e=(v_{1},v_{2})$ is present with $p_e(t=0)=p$. Then, for all $t\geq1$, all edges depicted in \figref{fig:toy-example} exist with $p_e(t)=1$. Assume that this information is known to the agent, and that at $t=1$ it is revealed that node $v_{1}$ was infected at $t=0$. In this example, we clearly should test either $v_{1}$ or $v_{2}$. We can compute the expected cost of each option exactly. \textbf{Alternative I:} Test ${v_2}$. With probability $p$, $v_{2}$ becomes infected at $t=1$, and we block the epidemic from spreading. However, we forfeit protecting $v_{1}$ neighbors, as all of them will be infected in the next step. With probability $1\!-\!p$ test is negative, and we fail to affect the dynamics. At $t=2$ node $v_{2}$ will get infected and at $t=3$ all of $v_{2}$'s neighbors become infected too, ending up with a total of $\left(m_{2}+1\right)$ infections. The expected cost in choosing to test $v_{2}$ is $(1-p)\cdot m_{2}+m_{1}$. \textbf{Alternative II:} Test $v_{1}$. We block the spread to $v_{1}$'s neighbors, but sacrifice all $m_{2}$ neighbors of $v_{2}$ with probability $p$. The expected cost in choosing $v_2$ is $p\cdot m_{2}$. The decision would therefore be to test for $v_{2}$ if $2p\geq1+m_{1}/m_{2}$. This example illustrates that an optimal policy must balance two factors: \emph{the probability that the dynamics is affected} - that a test action yields a ``positive", and the future consequences of our action - the \emph{strategic importance} of selecting\emph{ $v_{1}$ vs. $v_{2}$}, expressed by the ratio $m_{1}/m_{2}$. A policy targeting likely-infected nodes will always pick node $v_1$, but since it only focuses on the first term and ignores the second term, it is clearly suboptimal. \begin{figure} \begin{minipage}[c]{0.4\columnwidth} \includegraphics[width=0.9\columnwidth]{figs/toy_example.png} \end{minipage} \hfill \begin{minipage}[c]{0.5\columnwidth} \caption{ A double star configuration. The state of $v_{2}$ is unknown at the $t=1$. $v_1$ is infected at $t=0$.} \label{fig:toy-example} \end{minipage} \end{figure} An immediate question arise: How can we develop methods that address both terms? It is difficult to measure the strategic importance of a node in a large dynamical process with constant external interventions directly. Instead, one may use simulations and try to learn from the collected experience and the interplay between dynamics and actions a method that finds the optimal policy end-to-end and internally weighs the two terms optimally. This calls for a reinforcement learning framework. \begin{figure}[t] \centering \includegraphics[width=0.7\columnwidth]{figs/RL_graphs_fig2.png} \caption{Schematic of our approach. The Ranking module receives as input a sequence of graphs and outputs scores over nodes. Scores are then used to sample actions, selecting nodes for intervention. Here, the person circled in blue is selected for quarantine and its connections are cancelled (dashed blue lines). The downstream effect on epidemic progression is then fed as a loss to the ranking module.} \label{fig:Approachsechematics} \end{figure} \section{Problem Formulation} \label{sec:problem_formulation} We start our discussion with a concrete example focusing on the spread of epidemics, and then present the general formalism. \secref{sec:extensions} provides additional use-cases and applications of the general framework. \subsection{Epidemic test prioritization} We consider the recent COVID-19 outbreak that spreads through social contacts. The temporal graph $G$ is defined over a group of nodes (people) $\mathcal{V}$, and its edges $\mathcal{E}(t)$ are determined by their daily social interactions. An edge $(u,v)$ between two nodes exists at time $t$ iff the two nodes interacted at time $t$. Each of these interactions is characterized by various features $e_{uv}(t)$, including its duration, distancing and environment (indoors or outdoors). Additionally, each node $v$ is characterized with features $\zeta_{v}(t)$ (e.g, age, sex etc.). \textbf{The SEIR model}. We follow the widely-used SEIR model \cite{Lopez2020}. Every node (person) can be in one of the following states, $\mathcal{Y}={S, L, I, R}$, namely: \textit{susceptible} -- a healthy, yet uninfected person ($S$ state), \textit{exposed/latent} -- infected but cannot infect others ($L$ state), \textit{infectious} -- may infect other nodes ($I$ state), or \textit{removed} -- self-quarantined and isolated from the graph ($R$ state). The state of a node $v\in\mathcal{V}$ at time $t$ is a random variable denoted by $ST_v(t)$ \textbf{Node state dynamics}. A healthy node can become infected with a probability that depends on its interactions with its neighbors. Once infected, transitioning from \textit{Exposed/Latent} to \textit{Infected} is defined by a probabilistic process. A node becomes \textit{emoved} if it is selected for self-quarantine (tests positive); see Fig.~\ref{fig:viralinfection} for an illustration. Formally, let $\mathcal{I}(t)\subset V$ be the set of infectious nodes at time $t$, and similarly $\mathcal{L}(t)$, $\mathcal{R}(t)$ and $\mathcal{S}(t)$ be the sets of latent(exposed), removed and susceptible (healthy) nodes. Each active edge at time $t$, $e\in\mathcal{E}(t)$, carries a transmission probability $p_{e}(t)$. Denote the set of impinging edges on node $v$ with an infectious counterpart at time $t$ by $E_{v}(t)=\left\{ e\in\mathcal{E}(t)|e=(v,u),SV_u(t-1)=I\right\} .$ The probability of a healthy node to remain healthy at time $t$ is $1-\prod_{e\in E_{v}(t)}\left(1-p_{e}(t)\right)$, otherwise it becomes infected, but still in a latent state. We denote the time of infection of node $v$ as $T_{v}.$ A node in a latent state will stay in this state at time $t$ if $t<T_{v}+D_{v}$, where $D_{v}$ is a random variable representing the latency period length, otherwise its state changes to infectious. The testing intervention $h(\cdot)$ changes the state of a node. If infected or exposed, its state is set to $R$, otherwise it remains as it is. \textbf{Optimization goal and action space.} The objective is to minimize the spread of the epidemic, namely, minimize the number of infected people over time, $\mathbb{I}_{ST_v(t)\in\{L,D\}}$. Assuming that testing is limited to a fixed capacity of $k$ tests per day, the optimization goal becomes $ \min\sum_{t,v}\gamma^{t}\mathbb{I}_{ST_v(t)\in\{L,D\}}, $ where $\gamma\in(0,1]$ is a discount factor representing the relative importance of the future compared to the present. We used $\gamma=0.99$ throughout the paper. Of course, this is but one particular optimization goal and other goals that weigh different states differently, or add additional aspects are possible. The action space consists of all possible selections of a subset $a(t)$ of $k$ nodes $a(t)\subset V$. Even for moderate graph, with $\sim100-1000$ and small $k$ the action space ${|\mathcal{V}| \choose k }$ is huge. \textbf{Observation space.} At each time $t$, the agent is exposed to all past interactions between network nodes $\left\{ \mathcal{E}(t')|t'<t\right\} $. In addition, we are given partial information on the nodes state. The agent is provided with information on a subset of the infectious nodes at $t=0$. At every $t>0$, the agent observes all past test results. Formally, for every $v\in a(t)$ we observe if the node was infected, $ST_v(t)\in\mathcal{I}(t)\cup\mathcal{L}(t) $, or not. \subsection{General Formalism} Consider a diffusive process on a temporal graph $G(t)=(\mathcal{V},\mathcal{E}(t))$ whose structure changes in time. $\mathcal{V}$ is the set of nodes and $\mathcal{E}(t)=\{e_{uv}(t)\}$ is the set of edges at time step $t$. Each edge $e_{uv}(t)$ is associated with features $\phi_{uv}(t)$ which may vary in time, and each node $v$ is characterized with features $\zeta_{v}(t)$. The state of a node $v\in\mathcal{V}$ is a random variable $ST_v(t)$ which can have values in $\mathcal{Y}=\{y_{1},y_{2},..\}$. The node's state $ST_v(t)$ depends on the interactions between $v$ and its neighbors at time $t$ and on the state of those neighbors, We aggregate all neighborhood information to a random variable $$N_{v}(t)=\left\{ \left(\phi_{vu}(t),\zeta_{u}(t),ST_u(t)(t-1)\right)|u,e_{vu}\in\mathcal{E}(t)\right\} .$$ Additionally, $ST_v(t)$ depends on the previous state $ST_v(t-1)$ and on node features. In other words, \[ ST_v(t)=f\left(ST_v(t-1),\zeta_{v}(t),N_{v}(t)\right). \] At each step, we may select a subset $A(t)$ of $k$ nodes, and change the state of any selected node $v\in A(t)$. Selecting nodes and setting their states defines the space of actions for the agent, and plays the role of a knob for controlling the global dynamics of the process over the graph. Formally we apply a transformation $h(\cdot)$ on node $v$, setting $ST_v(t)=h\left(ST_v(t)\right),\forall v\in A(t)$. The optimization objective should be invariant to permuting (relabeling) of the nodes. We assume it depends only on the total number of nodes in state $i$, $c_{i}(t)=\sum_{v}\mathbb{I}_{SV(t)=s_{i}}$, where $I$ is the indicator function. The objective is therefore of the form \[ \sum_{t,v\in\mathcal{V}}\gamma^{t-t_{0}}g(c_{1}(t),c_{2}(t),..), \] where future evaluation are weighted by a discount factor $\gamma \le 1$. Additionally, the agent may be subject to constraints written in a similar manner $\sum_{i}f_{i}(c_{1}(t),c_{2}(t),..)\geq y_{i}(t)$. \section{Approach} \label{sec:approach} Our approach is depicted in Figure \ref{fig:Approachsechematics}. The RL agent receives as input the node and edge features of the temporal graph, and processes them using its ranking module. A probability distribution over graph nodes is generated from the ranking module’s scores, and the agent samples a subset of $k$ nodes for testing. Namely, the scores encode the agent's policy. We use Proximal Policy Optimization algorithm (PPO, \cite{Schulman2017}) as to optimize our agent. We sequentially apply the suggested action, log the (state, action) tuple in an experience replay buffer, and train our model based on the PPO loss term. Next, we describe the ranking module and sampling procedure. \subsection{RL Agent Ranking Module} \label{sec:ranking_module} \paragraph{Overview} Our GNN-RNN module serves to update the internal representation of a node $v$, denoted $h_v(t)$, and its score $s_v(t)$ (\figref{fig:ranking}). This score is later used for selecting nodes to be acted on. The ranking module is applied in a recurrent fashion at each time step. The ranking module contains two GNNs: (1) $E$, which updates the epidemic state, and (2) $I$, which updates the information state. It also contains two other networks, $G$ and $F$, which update node representations and node scores by using the epidemic state and information state as well as the previous node representations. \textbf{Input.} The input to the ranking module consists of three feature types (See \figref{fig:ranking}): (1) \textit{Static node features} $\zeta^s_v(t)$: topological graph centralities (betweeness, closeness, eigenvector and degree centralities) and random node features. (2) \textit{Dynamic node features} $\zeta^d_v(t)$ : All test results that were performed up the current timestamp (including positive and negative test results). We denote all nodes features as a concatenation $\zeta_v(t)=[\zeta^s_v(t),\zeta^d_v(t)]$. (3) \textit{Edge features} and the structure of the temporal graph $\mathcal{E}(t)$: All previous interactions up to the current step, including the transmission probability for each interaction. Figure \ref{fig:ranking} illustrates the basic data flow in the ranking module. \begin{figure}[t] \centering \includegraphics[width=0.7\columnwidth]{figs/RL_graphs_fig3.png} \caption{Block diagram of our suggested ranking module. It is composed of 4 neural networks $I$,$E$,$G$,$F$, which update the nodes scores and hidden states at each time step.} \label{fig:ranking} \end{figure} \textbf{Epidemic GNN.} The spread of epidemic through point contact is modeled by a GNN $E$. As the epidemic cannot spread by more than one hop per step, it is sufficient to model the spread with a single GNN layer. Formally, denote by $p_{vu}$ the probability of transmission during the interaction between $(v,u)$ at time $t$. For each $v$, the output of $E(\cdot)$ is a feature vector denoted by $e_v(t)$: \begin{align*} e_{v}(t) & =\sum_{u\sim_{t}v}p_{vv'}(t)\cdot M_{e}(\zeta_{v}(t),\zeta_{v'}(t);\theta_{m_e}), \end{align*} where $M$ is multilayer perceptron (MLP). Rather than considering the probability as an edge feature, this module mimics the epidemic transition rule to accelerate learning. \textbf{Information GNN.} The score of a node is affected both by the propagation dynamics, and by the information available to the agent. One may hope that since the former has a known timescale (days), on a short time scale (single day) the score of node would only be affected by its neighboring nodes. This, however, is not the true because information can propagate long distance in the graph almost instantaneously. As a simple example, consider nodes in a connected chain of (untested) nodes and note that they are statistically dependent. As a result, revealing the state of one node immediately affects the distribution over all nodes in the chain. With this consideration in mind, we designed an \textit{information GNN}, $I$, which represents the {\em information state} of each node. As discussed above, updated information on a node $u$ a few hops away from node $v$ may abruptly change our beliefs on the state of $v$. Furthermore, this change may occur even if $v$ and $u$ did not interact in the last time step but rather a while ago. To update the information state, we construct a cumulative multi-graph $G'$ where the set of edges between nodes $v$ and $u$ at time $t$ are all the interactions that occurred during the last $\tau$ steps, $\mathcal{E}_{G'}$=$\cup_{t'\in[t-\tau,t]}\mathcal{E}_{G}(t)$. The features of each edge in $\mathcal{E}_{G'}$, $\phi_{vu}(t')$, are the interaction delay $t-t'$ and the transmission probability $p_{v,v'}(t')$. The information features are the output of $k$-layer GNN; the $l^{th}$ layer is: \[ x_{v}^{l}(t)=\sum_{v'\sim_{t}v}M^{l}(x_v^{l-1}(t),x_{v'}^{l-1}(t),\phi_{vv'\text{\rq}(t)};\theta_M^l). \] As before, $M^l$ is an MLP, with $x_{v}^{0}(t)=\zeta_{v}(t)$ and $x_{v}^{k}(t)=i_{v}(t)$ are the final node features. The value of $\tau$, the information window size, was 7 in all our experiments. \textbf{Score and hidden state update.} For every node we hold a hidden state $h_{v}(t)$, which is updated following \begin{equation} h_{v}(t)=G(h_{v}(t-1),\zeta_{v}(t),e_{v}(t), i_{v}(t) ;\theta_{g}) \end{equation} After updating the new node hidden state, we use them to calculate the node score using a neural network $F$, \begin{equation} s_{v}(t)= F(h_{v}(t),h_{v}(t-1),\zeta_{v}(t);\theta_{f}) \end{equation} Here, $F$ is an MLP, while $G$ can be either an MLP or recurrent module such as GRU. \textbf{Sampling.} Given the score per node $s_v(t)$, we sample without replacement $k$ nodes iteratively. We (1) map the score of $n$ nodes to a probability distribution using a score-to-probability distribution function, (2) sample a node, and (3) adjust the distribution by removing its weight. We repeat this process $k$ iterations. \subsection{Design choices} \textbf{RL framework.} The action space of choosing a subset of $k$ nodes out of $n$ nodes is large even for small $n$ and $k$. Using an action-value approach like Q-learning implies that an approximate value is assigned to every possible action, but the action space size is prohibitively too large for action-value methods. Instead, we use a policy-gradient algorithm and model the problem as a ranking problem. The algorithm learns to rank nodes using a parameterized model, and then uses a sampling procedure to choose a subset of $k$ nodes. Many on-policy gradient algorithms use entropy to define a trust region. Computing the entropy requires summing ${k \choose |\mathcal{V}|}$ terms at each step, and it is computationally expensive. A more scalable solution is the unbiased entropy estimator of \citet{Zhang2018a}, but the variance of that estimator is high. As an alternative, PPO trust region is not based on an explicit evaluation of the entropy, and performed better in our experiments. We also evaluated A2C, which did not perform as well as PPO in our experiments. \textbf{Critic module.} PPO, as an actor-critic algorithm, requires a critic module to estimate the value function in a given state. We construct the actor using an architecture that is similar to the ranking module, but apply to element-wise max operation on the rows (representing the nodes) of the input to the score module $F$ (\figref{fig:ranking}). This reduces $F$'s input to a single row of features, and the output is then a scalar rather than a vector. Importantly, the critic is parametrized by a different set of weights than the ranking module (actor). \textbf{Score-to-probability distribution.} Usually, node scores are converted to a distribution over actions using a softmax. This approach is problematic for our case because node probabilities decay exponentially with their scores, leading to two major drawbacks. It discourages exploration of low-score nodes, and limits sensitivity to the top of the distribution, instead of at the top-k selected. Instead, we define the probability to sample an action $a_{i}$ to be \begin{equation} \Pr(a_{i})=\frac{x_{i}'}{\sum x_{i}'}\quad \textrm{, with } x_{i}'=x_{i}-\min_{i}x_{i}+\epsilon, \label{eq: score-to-prob} \end{equation} where $\{x_{i}\}$ is the set of scores and $\epsilon$ a constant. By not using an exponential as in softmax, the probability differences between low scoring nodes and high scoring nodes become less extreme. Furthermore, the parameter $\epsilon$ controls the initial exploration ratio. In standard DNN initialization schemes (e.g., XAVIER), the initial value of $x_{i}$ is expected to be in [-1,1]. If $\epsilon\gg1$ than the dominant term in \eqref{eq: score-to-prob} is $\epsilon$. This promotes exploration initially, as all actions are likely to be sampled in the early training stages. \textbf{Normalization in scale-free networks.} RNN are well-known to suffer from the problem of exploding or vanishing gradients. This problem is exacerbated in a RNN-GNN framework used for RL algorithms, because they may be applied for arbitrary long episodes, causing internal state to grow unbounded. This problem is particularly severe if the underlying graph contains hubs (highly connected nodes). One approach to alleviate this problem, is by including an RNN like a GRU module, where the hidden state values pass through a sigmoid layer. As the magnitude of the input grows, gradient become smaller and training slows down. Scale-free networks contain with high probability "hub" nodes that have high-degree, namely $O(n)$ neighbors. The presence of these hubs further aggravates this problem. As a simple case, consider a star graph with a large number of nodes. In a GNN framework, it receives updates from a large number of neighbors and its internal state increases in magnitude. The next time that the GNN module is applied (e.g., at the next RL step), the growing internal state increases the magnitude of the internal state of its neighbors. This leads to a positive-feedback loop that causes the internal state representation to diverge. Since RL algorithms may be applied for arbitrary long periods, the internal state may grow unbounded unless corrected. This problem can be solved by directly normalizing each node hidden state. We have experimented with various normalization methods, and found that $L_2$ normalization worked best, as shown in the next section. \textbf{Transition probabilities}. In the case of the COVID-19 pandemic, the transition probabilities can be estimated using the interaction properties, such as duration and inter-personal distance, using known epidemiological models. This was done by the government agency which provided our contact tracing network (see below). Alternatively, one can learn the transmission probability as a regression problem from known interactions (e.g, using data from post-infection questioning). Finally, if this information is not accessible, it is possible to omit the epidemic model #E# from the proposed framework and use only the feature vector created by the information module #I#. \section{Experiments} \subsection{Compared approaches} We compare methods from three categorizes: A) programmed; B) supervised learning (SL) C) Reinforcement learning (RL). Each experiment was performed with at least three random seeds. There exist additional approaches designed for the vaccination problem, but, as discussed in Sectio~\ref{sec:related_work}, they are not appropriate for the setup studied here. More details about experiments and implementation, including network architecture, are given in Appendix \ref{sec:experimental details}. \textbf{A. Programmed baselines.} Most countries currently prioritize their testing based on fixed procedures determined in advance and not learned form data. We compare with two such methods to rank nodes. \textbf{(1) Infected neighbors.} Rank nodes based on the number of known infected nodes in their 2-hop neighborhood (neighbors and their neighbors). Each node $v$ is assigned a tuple $(I_{v}^{(1)},I_{v}^{(2)})$, and tuples are sorted in a decreasing lexicographical order. A similar algorithm was used in \cite{Meirom2015, 8071015} to detect infected nodes in a noisy environment. \textbf{(2) Probabilistic risk.} Each node keeps an estimate of the probability it is infected at time $t-1$. To estimate infection probability at time $t$, beliefs are propagated from neighbors, and dynamic programming is used to analytically solve the probability update. See Appendix \ref{sec:tree model} for details. \textbf{(3) Degree centrality.} In this baselines high degree nodes are prioritized. This is an intuitive heuristic and it is used frequently \cite{Salathe2010}. It was found empirically to provide good results \cite{Sambaturu}. \textbf{(4) Eigenvalue centrality.} Another common approach it to select nodes using spectral graph properties, such as the eigenvalue centrality (e.g., \cite{Preciado2014,Yang2020}). The main drawback of these programmed algorithms is that they do not exploit all available information about dynamics. Specifically, they do not use negative test results, which contain information about the true distribution of the epidemic over network nodes. \textbf{B. Supervised learning.} Algorithms that learn the risk per node using features of the temporal graph, its connectivity and infection state. Then, $k$ nodes with the highest risk are selected. \textbf{(5) Supervised (vanilla).} We treat each time step $t$ and each node $v_i$ as a sample, and train a 3-layer deep network using a cross entropy loss against the ground truth state of that node at time $t$. The input of the DNN has two components: A static component described in \secref{sec:ranking_module}, and a dynamic part that contains the number of infected neighbors and their neighbors (like \#1 above). Note that the static features include the, amongst other features, the degree and eigenvector centralities. Therefore, if learning is successful, this baseline may derive an improved use of centralities based on local epidemic information. \textbf{(6) Supervised (+GNN).} Like \#5, but the input to the model is the set of all historic interactions of $v_i$'s and its $d$-order neighbours and their time stamps as an edge feature. The architecture is a GNN that operates on node and edge features. We used the same ranking module as our GNN framework, but the output probability is regarded as the probability that a node is infected. \textbf{(6) Supervised (+weighted degree).} Same as \#6, but the loss is modified and nodes are weighted by their degree. Indeed, we wish to favour models that are more accurate on high-degree nodes, because they may infect a greater number of nodes. \textbf{(8) Supervised (+weighted degree +GNN).} Like \#6 above, using degree-weighted loss like \#7. \textbf{C. RL algorithms:} \textbf{\RLGN{}} is our algorithm described in \secref{sec:approach}. The input to \textbf{(9) RL-vanilla} is the same as in (\#1) and (\#6) above. Correspondingly, the GNN module of described in \secref{sec:approach} is replaced by a DNN similar to (\#6), while the rest of the RL algorithm remains intact. \subsection{Experiment details and evaluations} \textbf{Training.} We train the RL and SL by generating random networks, and selecting for each instance a random subset of $m_{0}$ initially infected nodes. We propagate the epidemic until it spans at least $k_{0}$ infected nodes (for at least $t_{0}$ steps), and randomly detect a subset of the infected nodes of size $<k_{0}$. The simulation then follows the agent-network dynamics described in \secref{sec:problem_formulation}. \textbf{Evaluation Metrics.} The end goal of quarantining and epidemiological testing is to minimize the spread of the epidemic. As it is unreasonable to eradicate the epidemic using social distancing alone, the hope is to ``flatten the curve'', namely, to slow down the epidemic progress. We use two success metrics: (1) \textbf{\% healthy:} The percent of nodes kept healthy throughout the simulation. (2) \textbf{\%contained:} The probability of containing the epidemic. This was computed as the fraction of simulations having cumulative infected nodes smaller than a fraction $\alpha$. We focus on this metric because it captures the important notion of the capacity of a health system. In the 2-community setup, where each community has half of the nodes, a natural choice of $\alpha$ is slightly greater than $0.5$, capturing those cases where the algorithm contains the epidemic within the infected community. In all the experiments we set $\alpha=0.6$. The only exception is the three-communities experiments, in which we set the bar slightly higher than $1/3$, and fixed $\alpha=0.4$. \subsection{Network datasets and models} We study three types of networks which differ by their connectivity patterns. \textbf{(1) Community-based networks} have nodes clustered into densely-connected communities, with sparse connections across communities. We use the \textit{Stochastic Block Model} (SBM, \cite{abbe2017community}), for 2 and 3 communities. The Stochastic Block Model (SBM) is defined by (1) A partition of nodes to $m$ disjoint communities $C_{i}$, $i=1\dots m$; and (2) a matrix $P$ of size $m\times m$, which represents the edge probabilities between nodes in different communities, namely, the matrix entry $P_{i,j}$ determines the probability of an edge $(v,v')$ between $v\in C_{i}$ and $v'\in C_{j}$. The diagonal elements in $P$ are often much larger than the off-diagonal elements, representing the dense connectivity in a community, compared to the intra-connectivity between communities. \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{figs/three_communtities.png} \caption{Supervised vs RL with 3-community networks. \textbf{Left:} RLGN successfully learns to contain the epidemic 60\% of the time, while SL fails. \textbf{Right:} SL isolates many more infected nodes, but less important ones.} \label{fig:three_communities} \end{figure} \textbf{(2) Preferential attachment (PA)} networks exhibit a node-degree distribution that follows a power-law (scale-free), like those found in many real-world networks. We use the dual Barbarsi-Albert model \cite{Moshiri2018}, which allows for continuously varying the mean node degree. \textbf{Generating temporal graphs.} Static networks generated using PA or SBM are converted to a temporal graph by first selecting a random subset of edges $\mathcal{E}(t)$ at each time step $t$, and then assigning to each edge a transmission probability $q_e(t)$ sampled uniformly $U[a,b]$. \textbf{(3) Contact-tracing networks.} We received anonymized high-level statistical information about real contact tracing networks that included the distribution of node degree, transmission probability and mean number of interactions per day, collected during April 2020. \begin{figure} \centering \begin{tabular}{cc} \includegraphics[width=0.5\columnwidth]{figs/fig1}& \includegraphics[width=0.5\columnwidth]{figs/fig2}\\ (a) & (b) \end{tabular} \caption{Statistics of a real-world contact-tracing graph. (a) The empirical transition probability $P(p_e)$ on a contact tracing network and our suggested curve fit. (b) The degree distribution on the contact tracing network, along with its fit.} \label{fig:transmission_prob} \end{figure} Fig. \ref{fig:transmission_prob}(a) presents the degree distribution in this data, and the transmission probability is presented in Fig. \ref{fig:transmission_prob}(b). The latter was derived based on the contact properties, such as the length and the proximity of the interaction. On average, $1.635\pm0.211$ interactions with a significant transmission probability were recorded per-person per-day. We generated random networks based on these distributions using a configuration model framework \citep{Newman2010a}. The fitted model for the degree distribution is a mixture of a Gaussian and a power-law distribution \begin{align} P(degree=x)=0.47\cdot\mathcal{N}(0.41,0.036)+0.53\cdot Beta(5.05,20.02). \end{align} The fitted model for the transmission probability is a mixture of a Gaussian and a Beta distribution \begin{align} P(p_{e}=x)=2.68\cdot\mathcal{N}(-4.44,11.18)+3.2\cdot10^{-3}\cdot x^{-0.36}. \end{align} \begin{table} \centering \begin{tabular}{|l|c|c|} \hline & \#Nodes & \#Edges\\ \hline \hline CA-GrQc & 5242 & 14496\\ \hline Montreal & 103425 & 630893\\ \hline Portland & 10000 & 199167\\ \hline Enron & 32430 & 54397\\ \hline GEMSEC-RO & 41773 & 222887\\ \hline \end{tabular}\caption{\label{tab:datasets-info}Number of edges and nodes in the large-scale datasets} \end{table} \textbf{(4) large-scale datasets.} We consider graphs of different sizes and sources: (A) A research collaboration network (CA-GrQc), representing social interactions between researchers. In addition to social interaction, information also diffuses on this network \cite{network_database}. (B) The Montreal dataset (Montreal), based on WiFi hotspot tracing, collected in Montreal, Canada over three years, representing a proximity network \cite{Hoen2015}. (C) a compartment-based synthetic network, derived from first principles, using a population census in Portland, Oregon (Portland) \cite{Wells2013,Eubank2004}. (D) An email network (Enron), representing a computer network on which malwares spread, (E) An online social network. We used the recent GEMSEC-RO \cite{rozemberczki2019gemsec}, presenting friendship relations in the Deezer music service in Romania. This accommodates for a graph on which preferences and product adaption (songs) propagate. All these networks have been extensively used in previous work, in particular epidemiological studies, as key networks models \cite{Sambaturu, Yang2020, Hoen2015, Herrera2016,Wells2013,Eubank2004}. Table \ref{tab:datasets-info} summarizes the various datasets, spanning graphs with 5K nodes to graphs with more than 100K nodes. \begin{table} \centering \setlength{\tabcolsep}{3pt} \scalebox{0.97}{{\sc{ \begin{tabular}{|l|c|c|} \hline \%contained & 2 communities & 3 communities \\ \hline \hline Tree-based model & $15\pm 35$ & $0\pm0$ \\ \hline Counter model & $19\pm39$ & $ 1\pm 4$ \\ \hline Degree centrality & $23\pm1$ & $0\pm0$ \\ \hline Eigenvector centrality & $19\pm3$ & $0\pm0$\\ \hline Supervised (vanilla) & $24\pm 11$ & $2\pm 2$ \\ \hline Supervised +GNN & $27\pm 10$ & $ 2\pm 2$ \\ \hline Supervised +degree & $29\pm 10$ & $ 1\pm 2$\\ \hline Supervised +GNN+deg & $24\pm 10$ & $2\pm 02$\\ \hline \RLGN{} (Vanilla) & $66\pm 10$ & $7\pm 5$ \\ \hline \RLGN{} full (ours) & \textbf{88}{$\boldsymbol{\pm}$}\textbf{1} & \textbf{53}{$\boldsymbol{\pm}$}\textbf{13} \\ \hline \end{tabular} }}} \caption{Probability (in \%) of containing an epidemic in community-based networks. Each community has $30$ densely connected nodes. } \label{tab:comaprison-chart} \end{table} \begin{table} \centering \setlength{\tabcolsep}{3pt} \scalebox{0.99}{{\sc{ \centering \begin{tabular}{|l|c|c||c|c|} \hline & \multicolumn{2}{c}{\%contained} & \multicolumn{2}{c}{\%healthy} \\ \hline & PA & CT & PA & CT\\ \hline \hline Tree based model & $1\pm1$ & $0\pm0$ & $10\pm7$ & $11\pm3$\\ \hline Counter model & $0\pm0$ & $0\pm0$ & $7\pm7$ & $14\pm5$ \\ \hline Degree centrality & $22\pm4$ & $0\pm1$ & $30\pm2$ & $16\pm1$ \\ \hline Eigenvector centrality & $21\pm1$ & $0\pm1$ & $30\pm1$ & $16\pm1$ \\ \hline SL (vanilla) & $2\pm2$ & $0\pm0$ & $13\pm3$ & $17\pm1$\\ \hline SL + GNN & $27\pm6$ & $15\pm4$ & $34\pm3$ & $32\pm$2\\ \hline SL + deg & $3\pm3$ & $0\pm1$ & $15\pm3$ & $18\pm1$\\ \hline SL + deg + GNN & $26\pm5$ & $16\pm5$ & $33\pm3$ & $32\pm1$\\ \hline RL (vanilla) & $2\pm2$ & $1\pm1$ & $17\pm1$ & $16\pm1$\\ \hline RLGN (ours) & \textbf{78}{$\boldsymbol{\pm}$}\textbf{4} & \textbf{45}{$\boldsymbol{\pm}$}\textbf{6} & \textbf{52}{$\boldsymbol{\pm}$}\textbf{2} & \textbf{40}{$\boldsymbol{\pm}$}\textbf{1} \\ \hline \end{tabular} }}} \caption{\%contained epidemics and \%healthy nodes achieved on a preferential attachment (PA) network, and contact tracing (CT) network. In both cases, networks had $200$ nodes.} \label{tab:comaprison-chart-scale-free} \end{table} \subsection{Results} \label{sec:results} In a first set of experiments, we compared 7 approaches for learning and inference on 3 network types. The results reported in Table \ref{tab:comaprison-chart} and \ref{tab:comaprison-chart-scale-free} show that RLGN outperforms all baselines in all network types. A video highlighting the results can be found \href{https://www.dropbox.com/s/ae897mzcv61fw20/epidemic\%20video_1.mp4?dl=0}{online (anonymized)} \footnote{Link: \url{https://www.dropbox.com/s/ae897mzcv61fw20/epidemic\%20video_1.mp4?dl=0}}. To gain insight into this result, we first look more deeply into the case of 3-community networks. \figref{fig:three_communities}(a) traces the fraction of contained epidemics and \figref{fig:three_communities}(b) the fraction of infected nodes during training. The supervised learning algorithm detects substantially more infected nodes (right panel) than RLGN, but these tend to have lower future impact on the spread, and it fails to contain the epidemic (left). A closer look shows that RL, but not SL, successfully learns to identify and neutralize the critical nodes that connect communities and prevent the disease from spreading to another community. To further understand the solutions learned for PA networks, consider the following two extremes. First, when a network is very sparsely connected, it would be easy to cut long infection chains, and both approaches are expected to be successful. At the other extreme, for densely connected networks, there are no critical nodes, because there are many paths between any two nodes. To study this effect we generated networks with the preferential-attachment mechanism, while varying the mean node degree. This degree can also be viewed in terms of the $R_0$ coefficient, the mean number of nodes infected by a single diseased node. The greater $R_0$, the more difficult it is to contain the epidemic. \begin{figure} (a)\hspace{120pt} (b)\hspace{120pt}\\ \includegraphics[width=0.48\columnwidth]{figs/phase_shift.png} \includegraphics[width=0.48\columnwidth]{figs/stability_analysis} \caption{\textbf{Stability analysis:} \textbf{(a)} The contained epidemic fraction as a function of the basic reproduction number $R_0$ on a PA network. RLGN outperforms SL over a large range of $R_0$ values. \textbf{(b)} Stability against test-time shift in transmission probability. \textit{Orange:} The performance of RLGN deteriorates when the mean transmission probability at test time is higher more than $40\%$ than train time. \textit{Purple:} As a baseline, training and testing with the same higher transmission probability. \label{fig:stability} } \end{figure} Fig.~\ref{fig:stability}(a) quantifies this effect, showing the percent of contained epidemics as a function of the $R_0$ coefficient. RL has a significant advantage over supervised+GNN for a range of $R_0$ values between $2.0$ and $2.9$. Finally, \figref{fig:stability}(b) depicts a robustness analysis of \RLGN{} for variations in the epidemiological model. One of the most difficult quantities to assess is the probability for infection per social interaction. \figref{fig:stability}(b) shows that the trained model can sustain up to $\sim40\%$ deviation at test time in this key parameter. \iffalse \begin{figure} \centering \includegraphics[width=1\columnwidth]{figs/moving_histogram.png} \caption{The fraction of infected nodes as a function of time step $t$. The epidemic propagtes more slowly under RLGN compared with the best baseline (supervised+GNN, \#4). Shaded areas represent one standard deviation around the mean. Experiment was performed on a preferential attachment network with $300$ nodes and mean degree $2.8$. \label{fig:epidemic-speed} } \end{figure} \fi \begin{figure} \begin{tabular}{ccc} (a) GamesecRO & (b) Enron & (c) ca-GrQc\\ \includegraphics[width=0.31\columnwidth]{figs/mean_per_step_soc-gemsec-RO.png} & \includegraphics[width=0.31\columnwidth]{figs/mean_per_step_ia-email-EU.png} & \includegraphics[width=0.31\columnwidth]{figs/mean_per_step_ca-GrQc.png} \end{tabular} \caption{The fraction of infected nodes as a function of time step $t$. Shaded areas represent one standard deviation around the mean. (a) The epidemic propagation on an online social (gemsec-RO) (b) The epidemic propagation on an email network (Enron). (c) The epidemic propagation on the collaboration graph ca-GrQc. In all cases the epidemic propagates more slowly under RLGN compared with the best baseline (supervised+GNN, \#4). \label{fig:epidemic-speed} } \end{figure} \subsection{Robustness of results} We have tested the robustness of our results to the underlying graph size. Specifically, we compare the two best algorithms RLGN (\#8) and SL+GNN (\#4), using graphs with various sizes, from 300 nodes to 1000 nodes. Table \ref{tab:300-nodes-pa} compares RLGN with the SL+GNN algorithm on preferential attachment (PA) networks (mean degree $=2.8$). We provide results for various sizes of initial infection $i_{0}$ and number of available tests $k$ at each step. The experiments show that there is a considerable gap between the performance of the RL and the second-best baseline. Furthermore, RLGN achieves better performance than the SL+GNN algorithm with 40\%-100\% more tests. Namely, it increases the effective number of tests by a factor of $\times1.4-\times2$. We also tested the sensitivity of the results to the relative size of the initial infection. Table \ref{tab:300-nodes-pa} shows results when 4\% of the the network was initially infected, as well as for 7.5\% and 10\%. The results show that RLGN outperforms the baselines in this wide range of infection sizes. \begin{table} \centering \setlength{\tabcolsep}{3pt} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=300$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $27\pm2$ & $15\pm5$ & $21\pm2$ & $4\pm2$ & $18\pm1$ & $1\pm1$\\ \hline SL, $k=1.33\%$ & $41\pm3$ & $37\pm6$ & $27\pm2$ & $12\pm4$ & $24\pm2$ & $6\pm3$\\ \hline SL, $k=2\%$ & ${66\pm4}$ & $76\pm6$ & ${48\pm3}$ & $55\pm7$ & $37\pm2$ & $32\pm6$\\ \hline RLGN, $k=1\%$ & $50\pm2$ & ${78\pm7}$ & {$43\pm2$} & ${58\pm1}$ & ${40\pm1}$ & ${48\pm6}$\\ \hline \end{tabular} \vspace*{0.2 cm} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=500$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $24\pm2$ & $7\pm4$ & $20\pm1$ & $2\pm1$ & $19\pm1$ & $0\pm1$\\ \hline SL, $k=1.6\%$ & $48\pm3$ & $54\pm6$ & $35\pm2$ & $27\pm7$ & $29\pm1$ & $11\pm1$\\ \hline SL, $k=2\%$ & ${67\pm3}$ & $83\pm5$ & ${46\pm2}$ & $53\pm4$ & $38\pm2$ & $37\pm7$\\ \hline {RLGN, ${k=1\%}$} & $52\pm1$ & ${97\pm2}$ & ${44\pm2}$ & ${75\pm11}$ & ${42\pm1}$ & ${66\pm6}$\\ \hline \end{tabular} \vspace*{0.2 cm} \begin{tabular}{|l|c|c|c|c|c|c|} \hline \multirow{2}{*}{\textbf{$n=1000$}} & \multicolumn{2}{c|}{Init. infection size 5\%} & \multicolumn{2}{c|}{Init. Infection size 7.5\%} & \multicolumn{2}{c|}{Init. infection size 10\%}\\ \cline{2-7} \cline{3-7} \cline{4-7} \cline{5-7} \cline{6-7} \cline{7-7} & \%healthy & \%contained & \%healthy & \%contained & \%healthy & \%contained\\ \hline SL, $k=1\%$ & $25\pm2$ & $5\pm3$ & $21\pm1$ & $0\pm1$ & $19\pm1$ & $0\pm0$\\ \hline SL, $k=1.5\%$ & $42\pm2$ & $49\pm6$ & $30\pm1$ & $10\pm3$ & $27\pm1$ & $4\pm2$\\ \hline SL, $k=2\%$ & ${66\pm1}$ & $84\pm5$ & ${45\pm2}$ & $59\pm5$ & $37\pm1$ & $30\pm1$\\ \hline {RLGN, ${k=1\%}$} & $52\pm1$ & ${97\pm2}$ & ${44\pm2}$ & ${75\pm11}$ & ${42\pm1}$ & ${66\pm6}$\\ \hline \end{tabular} \caption{A comparison between RLGN and SL+GNN (the best baseline). RLGN performance is highlighted. The number of additional resources needed to surpass the RLGN performance in a given metric is also highlighted. In many cases, even using SL+GNN with twice as many resources than RLGN performs worse than RLGN. The evaluation was performed on a preferential attachment network with mean degree $2.8$. The number of nodes is indicated at the top of each table.} \label{tab:300-nodes-pa} \end{table} \subsection{Inference on large graphs and real-world networks} We further evaluated how models trained on medium-size graphs generalize to perform inference on much larger graphs. Specifically, we trained RLGN and SL+GNN (three model initialization for each) on a preferential attachment network with $1000$ nodes and evaluated its performance on various larger graphs. We investigated the progression of the epidemic under either RLGN or supervised+GNN algorithms. Figure \ref{fig:epidemic-speed} shows that the epidemic spread speed is slower under the RLGN policy in all graph. In general, there are two extreme configuration regimes. First, the ``too-hard" case, when the number of tests is insufficient to block the epidemic, and second, the ``too-easy" case when there is a surplus of tests such that every reasonable algorithm can contain it. The more interesting case is the intermediate regime, where some algorithms succeed to delay the epidemic progression, or block it completely, better than other algorithms. Fig. \ref{fig:epidemic-speed}(a) illustrates the case where the number of tests is insufficient for containing the epidemic, for all algorithms we tested. In Fig. \ref{fig:epidemic-speed}(b), the number of tests is insufficient for SL to block the epidemic. However, with same number of tests, RLGN algorithm successfully contains the epidemic. Fig. \ref{fig:epidemic-speed}(c) presents an interesting case where RLGN slows down the epidemic progression and reduces the number of total number of infected node, compared with SL, but RL does not contain it completely. \begin{table} \centering{}% \begin{tabular}{|l|c|c|c|c|c|} \hline & CA-GrQc & Montreal & Portland & Enron & GEMSEC-RO\\ \hline \hline Degree Centrality & $25.52\pm0.01$ & $12.83\pm0.01$ & $0.67\pm0.01$ & $71.14\pm0.02$ & $2.43\pm0.01$\\ \hline Eigenvector Centrality & $25.37\pm0.01$ & $8.06\pm0.01$ & $0.04\pm0.01$ & $55.10\pm0.02$ & $2.41\pm0.01$\\ \hline SL & $29.79\pm0.02$ & $23.09\pm0.03$ & $1.57\pm0.01$ & $68.45\pm0.05$ & $4.26\pm0.01$\\ \hline RLGN & \textbf{42.69}{$\boldsymbol{\pm}$}\textbf{0.03} & \textbf{39.68}{$\boldsymbol{\pm}$}\textbf{0.03} & \textbf{3.71}{$\boldsymbol{\pm}$}\textbf{0.01} & \textbf{89.19}{$\boldsymbol{\pm}$}\textbf{0.02} & \textbf{6.52}{$\boldsymbol{\pm}$}\textbf{0.01} \\ \hline \end{tabular}\caption{\label{tab:dataset-healthy}The mean percentile of healthy nodes after a 20 steps. RLGN perform better on all datasets with a statistically significant gap. } \end{table} Table \ref{tab:dataset-healthy} compares the performance of the RLGN and the best baseline (SL) on the large-scale datasets. We included the centralities baselines (#3,#4) in the comparison as they are heavily used in epidemiological studies. Table \ref{tab:dataset-healthy} shows that the RLGN consistently performs better than the baselines, and the gap is clearly statistically significant. Finally, we evaluated the performance of RLGN on a Preferential Attachment network with $50,000$ nodes (mean degree $=2.8$), as this random network model is considered a reasonable approximation for many other real world networks. We found that RLGN successfully contained the epidemic in all $150$ evaluation episodes, while the SL+GNN was unable to block the epidemic even once. The mean percentile of healthy nodes at the end of the episode was $51\pm1$ for RLGN, while for the SL+GNN it was only $21\pm2$, a difference of more than $15$ STDs. \subsection{Ablation Studies} \subsubsection{Mapping scores to action distribution.} We compare the performance of our score-to-probability function (calibrated-scores) to the popular softmax (Boltzmann) distribution. In practice, in most instances, we were unable to train a model using the softmax distribution as the neural network weights diverge. Fig.~\ref{fig:score-to-prob} presents the training curve in one of the few instances that did converge. It is clear that the model was not able to learn a useful policy while using the calibrated-scores probability function resulted in a corresponding value of more than $0.75$. \begin{figure} \centering \includegraphics[width=0.55\columnwidth]{figs/score_to_prob_ablation.png} \caption{The fraction of contained epidemics during training on a preferential attachment model with $200$ nodes and a mean degree $2.8$. For non-normalized mapping, only one of the three seeds in the softmax distribution simulation completed training due to numerical instability. No stability issues were observed when using the calibrated scores normalization scheme described by Eq. \eqref{eq: score-to-prob}. \label{fig:score-to-prob}} \end{figure} \begin{table} \centering \begin{tabular}{|c|c|c|} \hline & $\%contained$ & \# training epochs\\ \hline \hline Sigmoid & $0.84\pm0.05$ & 1210\\ \hline GRU & $0.91\pm0.03$ & 810\\ \hline $L_{2}$ norm. & $\mathbf{0.93\pm0.02}$ & \textbf{500}\\ \hline \end{tabular} \caption{\label{tab:norm-table} Training time and fraction of contained epidemic for three normalization schemes. The $L_2$ normalization scheme is fastest and achieves the best performance.} \end{table} \subsubsection{Normalization in scale-free networks.} We compared the suggested normalization to a number of other alternative normalization methods. (1) Applying a sigmoid layer after the hidden state update module $G$. (2) Replace the hidden state update module with a GRU layer. (3) Apply $L_2$ normalization to each feature vector $h_v(t)$ (similarly to \cite{Hamilton2017}) (4) Normalize the feature vector matrix by its $L_2$ norm. These four normalization schemes span three different types of normalization: single-feature normalization (1+2), vector normalization (3), and matrix normalization (4). Table \ref{tab:norm-table} presents the score after training and the number of training steps required to complete training. Method (4) was unstable and training did not converge, therefore it was omitted from the table. The main reason for the training time difference is that without normalization, the DNN weights' magnitude increases. In a GRU module, or with a direct application of a sigmoid layer, the features pass through a sigmoid activation function. When the magnitude of the input to this layer is large, the gradient is very small due to the sigmoid plateau. This substantially slows down the learning process. \subsubsection{Information processing module. } Our experiments showed the information module has a critical role in improving the performance of the RL-GNN framework. We performed an ablation study by removing it completely from our DNN module, keeping only the epidemic module. The full DNN module achieved a contained epidemic score of $0.77\pm0.06$, while the ablated DNN module corresponding score was $0.62\pm0.10$, a degradation of more than $20\%$. \section{Extensions\label{sec:extensions}} The approach and model discussed in this paper can be applied to important problems other than epidemic control. {\bf Influence maximization (IM).} Unlike epidemic control, in IM, the decision maker the objective is to maximize the spread of some opinion on a social network graph. They act to select nodes to be influenced by presenting information, actively contacting them, or sending coupons etc. Given a budget, the IM agent can only contact a limited number of nodes over a period of time. Influence spreads over the social networks similar to the model described above. The overall cost has two terms: cost of spending budget on influencing individual nodes, and benefit from influencing a give portion of the network. Local effects such as high degree nodes are important to IM. {\bf Fake news detection and confinement.} Consider a social network where fake news can be maliciously distributed, and spread over the network. A decision maker can verify the authenticity of items, but only verify a limited number of items per a time period. Once a fake item is detected, it is erased from the network. The objective is to minimize the total number of nodes that observe fake items. The main difference from the epidemic problem is that once a fake item is discovered, it can be erased from the entire network. The trade-off is that the decision maker does not want to waste inspection resources on items that are likely to die out. The fake new control and confinement problem can be therefore naturally cast within the framework outlined here. {\bf Epidemic Control: Beyond Node Selection}. While this paper addressed the important problem of deciding which nodes to examine given a certain umber of tests, we can also ask what if not only the subset of nodes to be tested, but also \emph{the number of tests.} to be performed can be controlled. Increasing the number of tests will help us contain the epidemic, however, it may be expensive to increase the number of tests and economy of scale may not work here. Another form of control is imposing a partial quarantine that reduces the number of interactions and resulting infections. Such a quarantine would come with a cost, of course. Both variations, and others, can be easily modeled within the framework presented in this paper. The crucial aspects of the model is having a objective that is cumulative reward structure, an action space that depends only on the information states, and a relatively short horizon for the relevant information to propagate so that the GNN approach works. Other important variations to the test kit allocation problems such partial quarantines, or using less accurate but more abundant tests can be easily modeled within the framework presented in this paper. The crucial aspects of the model is having an objective that has a cumulative reward structure, an action space that depends only on the information states, and a relatively short horizon for the relevant information to propagate so that the GNN approach works. \section{Conclusions} This paper shows that combining RL with GNNs provides a powerful approach for controlling spreading processes on graphs. In the context of COVID-19 spread, we demonstrated that using an RL+GNN approach allows us to confine the spread of an epidemic that is approximately 30\% more contagious (i.e., $R_0$ that is 30\% higher) with the same resources as a standard supervised learning-based approach. In addition, our results indicate that prioritizing tests using RL on temporal graphs can increase the number of healthy people by $25\%$ and contain the epidemic $30\%$ more often than supervised approaches and $2.5\times$ more often than non-learned baselines using the same resources. \bibliographystyle{ACM-Reference-Format} \section{Electronic Submission} \label{submission} Submission to ICML 2021 will be entirely electronic, via a web site (not email). Information about the submission process and \LaTeX\ templates are available on the conference web site at: \begin{center} \textbf{\texttt{http://icml.cc/}} \end{center} The guidelines below will be enforced for initial submissions and camera-ready copies. Here is a brief summary: \begin{itemize} \item Submissions must be in PDF\@. \item Submitted papers can be up to eight pages long, not including references, plus unlimited space for references. Accepted papers can be up to nine pages long, not including references, to allow authors to address reviewer comments. Any paper exceeding this length will automatically be rejected. \item \textbf{Do not include author information or acknowledgements} in your initial submission. \item Your paper should be in \textbf{10 point Times font}. \item Make sure your PDF file only uses Type-1 fonts. \item Place figure captions \emph{under} the figure (and omit titles from inside the graphic file itself). Place table captions \emph{over} the table. \item References must include page numbers whenever possible and be as complete as possible. Place multiple citations in chronological order. \item Do not alter the style template; in particular, do not compress the paper format by reducing the vertical spaces. \item Keep your abstract brief and self-contained, one paragraph and roughly 4--6 sentences. Gross violations will require correction at the camera-ready phase. The title should have content words capitalized. \end{itemize} \subsection{Submitting Papers} \textbf{Paper Deadline:} The deadline for paper submission that is advertised on the conference website is strict. If your full, anonymized, submission does not reach us on time, it will not be considered for publication. \textbf{Anonymous Submission:} ICML uses double-blind review: no identifying author information may appear on the title page or in the paper itself. Section~\ref{author info} gives further details. \textbf{Simultaneous Submission:} ICML will not accept any paper which, at the time of submission, is under review for another conference or has already been published. This policy also applies to papers that overlap substantially in technical content with conference papers under review or previously published. ICML submissions must not be submitted to other conferences and journals during ICML's review period. Informal publications, such as technical reports or papers in workshop proceedings which do not appear in print, do not fall under these restrictions. \medskip Authors must provide their manuscripts in \textbf{PDF} format. Furthermore, please make sure that files contain only embedded Type-1 fonts (e.g.,~using the program \texttt{pdffonts} in linux or using File/DocumentProperties/Fonts in Acrobat). Other fonts (like Type-3) might come from graphics files imported into the document. Authors using \textbf{Word} must convert their document to PDF\@. Most of the latest versions of Word have the facility to do this automatically. Submissions will not be accepted in Word format or any format other than PDF\@. Really. We're not joking. Don't send Word. Those who use \textbf{\LaTeX} should avoid including Type-3 fonts. Those using \texttt{latex} and \texttt{dvips} may need the following two commands: {\footnotesize \begin{verbatim} dvips -Ppdf -tletter -G0 -o paper.ps paper.dvi ps2pdf paper.ps \end{verbatim}} It is a zero following the ``-G'', which tells dvips to use the config.pdf file. Newer \TeX\ distributions don't always need this option. Using \texttt{pdflatex} rather than \texttt{latex}, often gives better results. This program avoids the Type-3 font problem, and supports more advanced features in the \texttt{microtype} package. \textbf{Graphics files} should be a reasonable size, and included from an appropriate format. Use vector formats (.eps/.pdf) for plots, lossless bitmap formats (.png) for raster graphics with sharp lines, and jpeg for photo-like images. The style file uses the \texttt{hyperref} package to make clickable links in documents. If this causes problems for you, add \texttt{nohyperref} as one of the options to the \texttt{icml2021} usepackage statement. \subsection{Submitting Final Camera-Ready Copy} The final versions of papers accepted for publication should follow the same format and naming convention as initial submissions, except that author information (names and affiliations) should be given. See Section~\ref{final author} for formatting instructions. The footnote, ``Preliminary work. Under review by the International Conference on Machine Learning (ICML). Do not distribute.'' must be modified to ``\textit{Proceedings of the $\mathit{38}^{th}$ International Conference on Machine Learning}, Online, PMLR 139, 2021. Copyright 2021 by the author(s).'' For those using the \textbf{\LaTeX} style file, this change (and others) is handled automatically by simply changing $\mathtt{\backslash usepackage\{icml2021\}}$ to $$\mathtt{\backslash usepackage[accepted]\{icml2021\}}$$ Authors using \textbf{Word} must edit the footnote on the first page of the document themselves. Camera-ready copies should have the title of the paper as running head on each page except the first one. The running title consists of a single line centered above a horizontal rule which is $1$~point thick. The running head should be centered, bold and in $9$~point type. The rule should be $10$~points above the main text. For those using the \textbf{\LaTeX} style file, the original title is automatically set as running head using the \texttt{fancyhdr} package which is included in the ICML 2021 style file package. In case that the original title exceeds the size restrictions, a shorter form can be supplied by using \verb|\icmltitlerunning{...}| just before $\mathtt{\backslash begin\{document\}}$. Authors using \textbf{Word} must edit the header of the document themselves. \section{Format of the Paper} All submissions must follow the specified format. \subsection{Dimensions} The text of the paper should be formatted in two columns, with an overall width of 6.75~inches, height of 9.0~inches, and 0.25~inches between the columns. The left margin should be 0.75~inches and the top margin 1.0~inch (2.54~cm). The right and bottom margins will depend on whether you print on US letter or A4 paper, but all final versions must be produced for US letter size. The paper body should be set in 10~point type with a vertical spacing of 11~points. Please use Times typeface throughout the text. \subsection{Title} The paper title should be set in 14~point bold type and centered between two horizontal rules that are 1~point thick, with 1.0~inch between the top rule and the top edge of the page. Capitalize the first letter of content words and put the rest of the title in lower case. \subsection{Author Information for Submission} \label{author info} ICML uses double-blind review, so author information must not appear. If you are using \LaTeX\/ and the \texttt{icml2021.sty} file, use \verb+\icmlauthor{...}+ to specify authors and \verb+\icmlaffiliation{...}+ to specify affiliations. (Read the TeX code used to produce this document for an example usage.) The author information will not be printed unless \texttt{accepted} is passed as an argument to the style file. Submissions that include the author information will not be reviewed. \subsubsection{Self-Citations} If you are citing published papers for which you are an author, refer to yourself in the third person. In particular, do not use phrases that reveal your identity (e.g., ``in previous work \cite{langley00}, we have shown \ldots''). Do not anonymize citations in the reference section. The only exception are manuscripts that are not yet published (e.g., under submission). If you choose to refer to such unpublished manuscripts \cite{anonymous}, anonymized copies have to be submitted as Supplementary Material via CMT\@. However, keep in mind that an ICML paper should be self contained and should contain sufficient detail for the reviewers to evaluate the work. In particular, reviewers are not required to look at the Supplementary Material when writing their review. \subsubsection{Camera-Ready Author Information} \label{final author} If a paper is accepted, a final camera-ready copy must be prepared. For camera-ready papers, author information should start 0.3~inches below the bottom rule surrounding the title. The authors' names should appear in 10~point bold type, in a row, separated by white space, and centered. Author names should not be broken across lines. Unbolded superscripted numbers, starting 1, should be used to refer to affiliations. Affiliations should be numbered in the order of appearance. A single footnote block of text should be used to list all the affiliations. (Academic affiliations should list Department, University, City, State/Region, Country. Similarly for industrial affiliations.) Each distinct affiliations should be listed once. If an author has multiple affiliations, multiple superscripts should be placed after the name, separated by thin spaces. If the authors would like to highlight equal contribution by multiple first authors, those authors should have an asterisk placed after their name in superscript, and the term ``\textsuperscript{*}Equal contribution" should be placed in the footnote block ahead of the list of affiliations. A list of corresponding authors and their emails (in the format Full Name \textless{}[email protected]\textgreater{}) can follow the list of affiliations. Ideally only one or two names should be listed. A sample file with author names is included in the ICML2021 style file package. Turn on the \texttt{[accepted]} option to the stylefile to see the names rendered. All of the guidelines above are implemented by the \LaTeX\ style file. \subsection{Abstract} The paper abstract should begin in the left column, 0.4~inches below the final address. The heading `Abstract' should be centered, bold, and in 11~point type. The abstract body should use 10~point type, with a vertical spacing of 11~points, and should be indented 0.25~inches more than normal on left-hand and right-hand margins. Insert 0.4~inches of blank space after the body. Keep your abstract brief and self-contained, limiting it to one paragraph and roughly 4--6 sentences. Gross violations will require correction at the camera-ready phase. \subsection{Partitioning the Text} You should organize your paper into sections and paragraphs to help readers place a structure on the material and understand its contributions. \subsubsection{Sections and Subsections} Section headings should be numbered, flush left, and set in 11~pt bold type with the content words capitalized. Leave 0.25~inches of space before the heading and 0.15~inches after the heading. Similarly, subsection headings should be numbered, flush left, and set in 10~pt bold type with the content words capitalized. Leave 0.2~inches of space before the heading and 0.13~inches afterward. Finally, subsubsection headings should be numbered, flush left, and set in 10~pt small caps with the content words capitalized. Leave 0.18~inches of space before the heading and 0.1~inches after the heading. Please use no more than three levels of headings. \subsubsection{Paragraphs and Footnotes} Within each section or subsection, you should further partition the paper into paragraphs. Do not indent the first line of a given paragraph, but insert a blank line between succeeding ones. You can use footnotes\footnote{Footnotes should be complete sentences.} to provide readers with additional information about a topic without interrupting the flow of the paper. Indicate footnotes with a number in the text where the point is most relevant. Place the footnote in 9~point type at the bottom of the column in which it appears. Precede the first footnote in a column with a horizontal rule of 0.8~inches.\footnote{Multiple footnotes can appear in each column, in the same order as they appear in the text, but spread them across columns and pages if possible.} \begin{figure}[ht] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{icml_numpapers}} \caption{Historical locations and number of accepted papers for International Machine Learning Conferences (ICML 1993 -- ICML 2008) and International Workshops on Machine Learning (ML 1988 -- ML 1992). At the time this figure was produced, the number of accepted papers for ICML 2008 was unknown and instead estimated.} \label{icml-historical} \end{center} \vskip -0.2in \end{figure} \subsection{Figures} You may want to include figures in the paper to illustrate your approach and results. Such artwork should be centered, legible, and separated from the text. Lines should be dark and at least 0.5~points thick for purposes of reproduction, and text should not appear on a gray background. Label all distinct components of each figure. If the figure takes the form of a graph, then give a name for each axis and include a legend that briefly describes each curve. Do not include a title inside the figure; instead, the caption should serve this function. Number figures sequentially, placing the figure number and caption \emph{after} the graphics, with at least 0.1~inches of space before the caption and 0.1~inches after it, as in Figure~\ref{icml-historical}. The figure caption should be set in 9~point type and centered unless it runs two or more lines, in which case it should be flush left. You may float figures to the top or bottom of a column, and you may set wide figures across both columns (use the environment \texttt{figure*} in \LaTeX). Always place two-column figures at the top or bottom of the page. \subsection{Algorithms} If you are using \LaTeX, please use the ``algorithm'' and ``algorithmic'' environments to format pseudocode. These require the corresponding stylefiles, algorithm.sty and algorithmic.sty, which are supplied with this package. Algorithm~\ref{alg:example} shows an example. \begin{algorithm}[tb] \caption{Bubble Sort} \label{alg:example} \begin{algorithmic} \STATE {\bfseries Input:} data $x_i$, size $m$ \REPEAT \STATE Initialize $noChange = true$. \FOR{$i=1$ {\bfseries to} $m-1$} \IF{$x_i > x_{i+1}$} \STATE Swap $x_i$ and $x_{i+1}$ \STATE $noChange = false$ \ENDIF \ENDFOR \UNTIL{$noChange$ is $true$} \end{algorithmic} \end{algorithm} \subsection{Tables} You may also want to include tables that summarize material. Like figures, these should be centered, legible, and numbered consecutively. However, place the title \emph{above} the table with at least 0.1~inches of space before the title and the same after it, as in Table~\ref{sample-table}. The table title should be set in 9~point type and centered unless it runs two or more lines, in which case it should be flush left. \begin{table}[t] \caption{Classification accuracies for naive Bayes and flexible Bayes on various data sets.} \label{sample-table} \vskip 0.15in \begin{center} \begin{small} \begin{sc} \begin{tabular}{lcccr} \toprule Data set & Naive & Flexible & Better? \\ \midrule Breast & 95.9$\pm$ 0.2& 96.7$\pm$ 0.2& $\surd$ \\ Cleveland & 83.3$\pm$ 0.6& 80.0$\pm$ 0.6& $\times$\\ Glass2 & 61.9$\pm$ 1.4& 83.8$\pm$ 0.7& $\surd$ \\ Credit & 74.8$\pm$ 0.5& 78.3$\pm$ 0.6& \\ Horse & 73.3$\pm$ 0.9& 69.7$\pm$ 1.0& $\times$\\ Meta & 67.1$\pm$ 0.6& 76.5$\pm$ 0.5& $\surd$ \\ Pima & 75.1$\pm$ 0.6& 73.9$\pm$ 0.5& \\ Vehicle & 44.9$\pm$ 0.6& 61.5$\pm$ 0.4& $\surd$ \\ \bottomrule \end{tabular} \end{sc} \end{small} \end{center} \vskip -0.1in \end{table} Tables contain textual material, whereas figures contain graphical material. Specify the contents of each row and column in the table's topmost row. Again, you may float tables to a column's top or bottom, and set wide tables across both columns. Place two-column tables at the top or bottom of the page. \subsection{Citations and References} Please use APA reference format regardless of your formatter or word processor. If you rely on the \LaTeX\/ bibliographic facility, use \texttt{natbib.sty} and \texttt{icml2021.bst} included in the style-file package to obtain this format. Citations within the text should include the authors' last names and year. If the authors' names are included in the sentence, place only the year in parentheses, for example when referencing Arthur Samuel's pioneering work \yrcite{Samuel59}. Otherwise place the entire reference in parentheses with the authors and year separated by a comma \cite{Samuel59}. List multiple references separated by semicolons \cite{kearns89,Samuel59,mitchell80}. Use the `et~al.' construct only for citations with three or more authors or after listing all authors to a publication in an earlier reference \cite{MachineLearningI}. Authors should cite their own work in the third person in the initial version of their paper submitted for blind review. Please refer to Section~\ref{author info} for detailed instructions on how to cite your own papers. Use an unnumbered first-level section heading for the references, and use a hanging indent style, with the first line of the reference flush against the left margin and subsequent lines indented by 10 points. The references at the end of this document give examples for journal articles \cite{Samuel59}, conference publications \cite{langley00}, book chapters \cite{Newell81}, books \cite{DudaHart2nd}, edited volumes \cite{MachineLearningI}, technical reports \cite{mitchell80}, and dissertations \cite{kearns89}. Alphabetize references by the surnames of the first authors, with single author entries preceding multiple author entries. Order references for the same authors by year of publication, with the earliest first. Make sure that each reference includes all relevant information (e.g., page numbers). Please put some effort into making references complete, presentable, and consistent. If using bibtex, please protect capital letters of names and abbreviations in titles, for example, use \{B\}ayesian or \{L\}ipschitz in your .bib file. \section*{Software and Data} If a paper is accepted, we strongly encourage the publication of software and data with the camera-ready version of the paper whenever appropriate. This can be done by including a URL in the camera-ready copy. However, \textbf{do not} include URLs that reveal your institution or identity in your submission for review. Instead, provide an anonymous URL or upload the material as ``Supplementary Material'' into the CMT reviewing system. Note that reviewers are not required to look at this material when writing their review. \section*{Acknowledgements} \textbf{Do not} include acknowledgements in the initial version of the paper submitted for blind review. If a paper is accepted, the final camera-ready version can (and probably should) include acknowledgements. In this case, please place such acknowledgements in an unnumbered section at the end of the paper. Typically, this will include thanks to reviewers who gave useful comments, to colleagues who contributed to the ideas, and to funding agencies and corporate sponsors that provided financial support. \nocite{langley00} \section{Electronic Submission} \label{submission} Submission to ICML 2021 will be entirely electronic, via a web site (not email). Information about the submission process and \LaTeX\ templates are available on the conference web site at: \begin{center} \textbf{\texttt{http://icml.cc/}} \end{center} The guidelines below will be enforced for initial submissions and camera-ready copies. Here is a brief summary: \begin{itemize} \item Submissions must be in PDF\@. \item Submitted papers can be up to eight pages long, not including references, plus unlimited space for references. Accepted papers can be up to nine pages long, not including references, to allow authors to address reviewer comments. Any paper exceeding this length will automatically be rejected. \item \textbf{Do not include author information or acknowledgements} in your initial submission. \item Your paper should be in \textbf{10 point Times font}. \item Make sure your PDF file only uses Type-1 fonts. \item Place figure captions \emph{under} the figure (and omit titles from inside the graphic file itself). Place table captions \emph{over} the table. \item References must include page numbers whenever possible and be as complete as possible. Place multiple citations in chronological order. \item Do not alter the style template; in particular, do not compress the paper format by reducing the vertical spaces. \item Keep your abstract brief and self-contained, one paragraph and roughly 4--6 sentences. Gross violations will require correction at the camera-ready phase. The title should have content words capitalized. \end{itemize} \subsection{Submitting Papers} \textbf{Paper Deadline:} The deadline for paper submission that is advertised on the conference website is strict. If your full, anonymized, submission does not reach us on time, it will not be considered for publication. \textbf{Anonymous Submission:} ICML uses double-blind review: no identifying author information may appear on the title page or in the paper itself. Section~\ref{author info} gives further details. \textbf{Simultaneous Submission:} ICML will not accept any paper which, at the time of submission, is under review for another conference or has already been published. This policy also applies to papers that overlap substantially in technical content with conference papers under review or previously published. ICML submissions must not be submitted to other conferences and journals during ICML's review period. Informal publications, such as technical reports or papers in workshop proceedings which do not appear in print, do not fall under these restrictions. \medskip Authors must provide their manuscripts in \textbf{PDF} format. Furthermore, please make sure that files contain only embedded Type-1 fonts (e.g.,~using the program \texttt{pdffonts} in linux or using File/DocumentProperties/Fonts in Acrobat). Other fonts (like Type-3) might come from graphics files imported into the document. Authors using \textbf{Word} must convert their document to PDF\@. Most of the latest versions of Word have the facility to do this automatically. Submissions will not be accepted in Word format or any format other than PDF\@. Really. We're not joking. Don't send Word. Those who use \textbf{\LaTeX} should avoid including Type-3 fonts. Those using \texttt{latex} and \texttt{dvips} may need the following two commands: {\footnotesize \begin{verbatim} dvips -Ppdf -tletter -G0 -o paper.ps paper.dvi ps2pdf paper.ps \end{verbatim}} It is a zero following the ``-G'', which tells dvips to use the config.pdf file. Newer \TeX\ distributions don't always need this option. Using \texttt{pdflatex} rather than \texttt{latex}, often gives better results. This program avoids the Type-3 font problem, and supports more advanced features in the \texttt{microtype} package. \textbf{Graphics files} should be a reasonable size, and included from an appropriate format. Use vector formats (.eps/.pdf) for plots, lossless bitmap formats (.png) for raster graphics with sharp lines, and jpeg for photo-like images. The style file uses the \texttt{hyperref} package to make clickable links in documents. If this causes problems for you, add \texttt{nohyperref} as one of the options to the \texttt{icml2021} usepackage statement. \subsection{Submitting Final Camera-Ready Copy} The final versions of papers accepted for publication should follow the same format and naming convention as initial submissions, except that author information (names and affiliations) should be given. See Section~\ref{final author} for formatting instructions. The footnote, ``Preliminary work. Under review by the International Conference on Machine Learning (ICML). Do not distribute.'' must be modified to ``\textit{Proceedings of the $\mathit{38}^{th}$ International Conference on Machine Learning}, Online, PMLR 139, 2021. Copyright 2021 by the author(s).'' For those using the \textbf{\LaTeX} style file, this change (and others) is handled automatically by simply changing $\mathtt{\backslash usepackage\{icml2021\}}$ to $$\mathtt{\backslash usepackage[accepted]\{icml2021\}}$$ Authors using \textbf{Word} must edit the footnote on the first page of the document themselves. Camera-ready copies should have the title of the paper as running head on each page except the first one. The running title consists of a single line centered above a horizontal rule which is $1$~point thick. The running head should be centered, bold and in $9$~point type. The rule should be $10$~points above the main text. For those using the \textbf{\LaTeX} style file, the original title is automatically set as running head using the \texttt{fancyhdr} package which is included in the ICML 2021 style file package. In case that the original title exceeds the size restrictions, a shorter form can be supplied by using \verb|\icmltitlerunning{...}| just before $\mathtt{\backslash begin\{document\}}$. Authors using \textbf{Word} must edit the header of the document themselves. \section{Format of the Paper} All submissions must follow the specified format. \subsection{Dimensions} The text of the paper should be formatted in two columns, with an overall width of 6.75~inches, height of 9.0~inches, and 0.25~inches between the columns. The left margin should be 0.75~inches and the top margin 1.0~inch (2.54~cm). The right and bottom margins will depend on whether you print on US letter or A4 paper, but all final versions must be produced for US letter size. The paper body should be set in 10~point type with a vertical spacing of 11~points. Please use Times typeface throughout the text. \subsection{Title} The paper title should be set in 14~point bold type and centered between two horizontal rules that are 1~point thick, with 1.0~inch between the top rule and the top edge of the page. Capitalize the first letter of content words and put the rest of the title in lower case. \subsection{Author Information for Submission} \label{author info} ICML uses double-blind review, so author information must not appear. If you are using \LaTeX\/ and the \texttt{icml2021.sty} file, use \verb+\icmlauthor{...}+ to specify authors and \verb+\icmlaffiliation{...}+ to specify affiliations. (Read the TeX code used to produce this document for an example usage.) The author information will not be printed unless \texttt{accepted} is passed as an argument to the style file. Submissions that include the author information will not be reviewed. \subsubsection{Self-Citations} If you are citing published papers for which you are an author, refer to yourself in the third person. In particular, do not use phrases that reveal your identity (e.g., ``in previous work \cite{langley00}, we have shown \ldots''). Do not anonymize citations in the reference section. The only exception are manuscripts that are not yet published (e.g., under submission). If you choose to refer to such unpublished manuscripts \cite{anonymous}, anonymized copies have to be submitted as Supplementary Material via CMT\@. However, keep in mind that an ICML paper should be self contained and should contain sufficient detail for the reviewers to evaluate the work. In particular, reviewers are not required to look at the Supplementary Material when writing their review. \subsubsection{Camera-Ready Author Information} \label{final author} If a paper is accepted, a final camera-ready copy must be prepared. For camera-ready papers, author information should start 0.3~inches below the bottom rule surrounding the title. The authors' names should appear in 10~point bold type, in a row, separated by white space, and centered. Author names should not be broken across lines. Unbolded superscripted numbers, starting 1, should be used to refer to affiliations. Affiliations should be numbered in the order of appearance. A single footnote block of text should be used to list all the affiliations. (Academic affiliations should list Department, University, City, State/Region, Country. Similarly for industrial affiliations.) Each distinct affiliations should be listed once. If an author has multiple affiliations, multiple superscripts should be placed after the name, separated by thin spaces. If the authors would like to highlight equal contribution by multiple first authors, those authors should have an asterisk placed after their name in superscript, and the term ``\textsuperscript{*}Equal contribution" should be placed in the footnote block ahead of the list of affiliations. A list of corresponding authors and their emails (in the format Full Name \textless{}[email protected]\textgreater{}) can follow the list of affiliations. Ideally only one or two names should be listed. A sample file with author names is included in the ICML2021 style file package. Turn on the \texttt{[accepted]} option to the stylefile to see the names rendered. All of the guidelines above are implemented by the \LaTeX\ style file. \subsection{Abstract} The paper abstract should begin in the left column, 0.4~inches below the final address. The heading `Abstract' should be centered, bold, and in 11~point type. The abstract body should use 10~point type, with a vertical spacing of 11~points, and should be indented 0.25~inches more than normal on left-hand and right-hand margins. Insert 0.4~inches of blank space after the body. Keep your abstract brief and self-contained, limiting it to one paragraph and roughly 4--6 sentences. Gross violations will require correction at the camera-ready phase. \subsection{Partitioning the Text} You should organize your paper into sections and paragraphs to help readers place a structure on the material and understand its contributions. \subsubsection{Sections and Subsections} Section headings should be numbered, flush left, and set in 11~pt bold type with the content words capitalized. Leave 0.25~inches of space before the heading and 0.15~inches after the heading. Similarly, subsection headings should be numbered, flush left, and set in 10~pt bold type with the content words capitalized. Leave 0.2~inches of space before the heading and 0.13~inches afterward. Finally, subsubsection headings should be numbered, flush left, and set in 10~pt small caps with the content words capitalized. Leave 0.18~inches of space before the heading and 0.1~inches after the heading. Please use no more than three levels of headings. \subsubsection{Paragraphs and Footnotes} Within each section or subsection, you should further partition the paper into paragraphs. Do not indent the first line of a given paragraph, but insert a blank line between succeeding ones. You can use footnotes\footnote{Footnotes should be complete sentences.} to provide readers with additional information about a topic without interrupting the flow of the paper. Indicate footnotes with a number in the text where the point is most relevant. Place the footnote in 9~point type at the bottom of the column in which it appears. Precede the first footnote in a column with a horizontal rule of 0.8~inches.\footnote{Multiple footnotes can appear in each column, in the same order as they appear in the text, but spread them across columns and pages if possible.} \begin{figure}[ht] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{icml_numpapers}} \caption{Historical locations and number of accepted papers for International Machine Learning Conferences (ICML 1993 -- ICML 2008) and International Workshops on Machine Learning (ML 1988 -- ML 1992). At the time this figure was produced, the number of accepted papers for ICML 2008 was unknown and instead estimated.} \label{icml-historical} \end{center} \vskip -0.2in \end{figure} \subsection{Figures} You may want to include figures in the paper to illustrate your approach and results. Such artwork should be centered, legible, and separated from the text. Lines should be dark and at least 0.5~points thick for purposes of reproduction, and text should not appear on a gray background. Label all distinct components of each figure. If the figure takes the form of a graph, then give a name for each axis and include a legend that briefly describes each curve. Do not include a title inside the figure; instead, the caption should serve this function. Number figures sequentially, placing the figure number and caption \emph{after} the graphics, with at least 0.1~inches of space before the caption and 0.1~inches after it, as in Figure~\ref{icml-historical}. The figure caption should be set in 9~point type and centered unless it runs two or more lines, in which case it should be flush left. You may float figures to the top or bottom of a column, and you may set wide figures across both columns (use the environment \texttt{figure*} in \LaTeX). Always place two-column figures at the top or bottom of the page. \subsection{Algorithms} If you are using \LaTeX, please use the ``algorithm'' and ``algorithmic'' environments to format pseudocode. These require the corresponding stylefiles, algorithm.sty and algorithmic.sty, which are supplied with this package. Algorithm~\ref{alg:example} shows an example. \begin{algorithm}[tb] \caption{Bubble Sort} \label{alg:example} \begin{algorithmic} \STATE {\bfseries Input:} data $x_i$, size $m$ \REPEAT \STATE Initialize $noChange = true$. \FOR{$i=1$ {\bfseries to} $m-1$} \IF{$x_i > x_{i+1}$} \STATE Swap $x_i$ and $x_{i+1}$ \STATE $noChange = false$ \ENDIF \ENDFOR \UNTIL{$noChange$ is $true$} \end{algorithmic} \end{algorithm} \subsection{Tables} You may also want to include tables that summarize material. Like figures, these should be centered, legible, and numbered consecutively. However, place the title \emph{above} the table with at least 0.1~inches of space before the title and the same after it, as in Table~\ref{sample-table}. The table title should be set in 9~point type and centered unless it runs two or more lines, in which case it should be flush left. \begin{table}[t] \caption{Classification accuracies for naive Bayes and flexible Bayes on various data sets.} \label{sample-table} \vskip 0.15in \begin{center} \begin{small} \begin{sc} \begin{tabular}{lcccr} \toprule Data set & Naive & Flexible & Better? \\ \midrule Breast & 95.9$\pm$ 0.2& 96.7$\pm$ 0.2& $\surd$ \\ Cleveland & 83.3$\pm$ 0.6& 80.0$\pm$ 0.6& $\times$\\ Glass2 & 61.9$\pm$ 1.4& 83.8$\pm$ 0.7& $\surd$ \\ Credit & 74.8$\pm$ 0.5& 78.3$\pm$ 0.6& \\ Horse & 73.3$\pm$ 0.9& 69.7$\pm$ 1.0& $\times$\\ Meta & 67.1$\pm$ 0.6& 76.5$\pm$ 0.5& $\surd$ \\ Pima & 75.1$\pm$ 0.6& 73.9$\pm$ 0.5& \\ Vehicle & 44.9$\pm$ 0.6& 61.5$\pm$ 0.4& $\surd$ \\ \bottomrule \end{tabular} \end{sc} \end{small} \end{center} \vskip -0.1in \end{table} Tables contain textual material, whereas figures contain graphical material. Specify the contents of each row and column in the table's topmost row. Again, you may float tables to a column's top or bottom, and set wide tables across both columns. Place two-column tables at the top or bottom of the page. \subsection{Citations and References} Please use APA reference format regardless of your formatter or word processor. If you rely on the \LaTeX\/ bibliographic facility, use \texttt{natbib.sty} and \texttt{icml2021.bst} included in the style-file package to obtain this format. Citations within the text should include the authors' last names and year. If the authors' names are included in the sentence, place only the year in parentheses, for example when referencing Arthur Samuel's pioneering work \yrcite{Samuel59}. Otherwise place the entire reference in parentheses with the authors and year separated by a comma \cite{Samuel59}. List multiple references separated by semicolons \cite{kearns89,Samuel59,mitchell80}. Use the `et~al.' construct only for citations with three or more authors or after listing all authors to a publication in an earlier reference \cite{MachineLearningI}. Authors should cite their own work in the third person in the initial version of their paper submitted for blind review. Please refer to Section~\ref{author info} for detailed instructions on how to cite your own papers. Use an unnumbered first-level section heading for the references, and use a hanging indent style, with the first line of the reference flush against the left margin and subsequent lines indented by 10 points. The references at the end of this document give examples for journal articles \cite{Samuel59}, conference publications \cite{langley00}, book chapters \cite{Newell81}, books \cite{DudaHart2nd}, edited volumes \cite{MachineLearningI}, technical reports \cite{mitchell80}, and dissertations \cite{kearns89}. Alphabetize references by the surnames of the first authors, with single author entries preceding multiple author entries. Order references for the same authors by year of publication, with the earliest first. Make sure that each reference includes all relevant information (e.g., page numbers). Please put some effort into making references complete, presentable, and consistent. If using bibtex, please protect capital letters of names and abbreviations in titles, for example, use \{B\}ayesian or \{L\}ipschitz in your .bib file. \section*{Software and Data} If a paper is accepted, we strongly encourage the publication of software and data with the camera-ready version of the paper whenever appropriate. This can be done by including a URL in the camera-ready copy. However, \textbf{do not} include URLs that reveal your institution or identity in your submission for review. Instead, provide an anonymous URL or upload the material as ``Supplementary Material'' into the CMT reviewing system. Note that reviewers are not required to look at this material when writing their review. \section*{Acknowledgements} \textbf{Do not} include acknowledgements in the initial version of the paper submitted for blind review. If a paper is accepted, the final camera-ready version can (and probably should) include acknowledgements. In this case, please place such acknowledgements in an unnumbered section at the end of the paper. Typically, this will include thanks to reviewers who gave useful comments, to colleagues who contributed to the ideas, and to funding agencies and corporate sponsors that provided financial support. \nocite{langley00} \section{Introduction} Consider an epidemic spreading in the population. To contain the disease and prevent it from spreading, it becomes critical to detect infected carriers and isolate them; see Fig.~\ref{fig:viralinfection} for an illustration. As the epidemic spreads, the demand for tests outgrows their availability, and not all potential carriers can be tested. It becomes necessary to identify the most likely epidemic carriers using limited testing resources. How should we rank candidates and prioritize vaccines and tests to prevent the disease from spreading? As a second example, imagine a seemingly very different problem, where one would like to promote an opinion or support product adaption by advertisements or information sharing on a social graph. If an impactful node is convinced, it may influence other nodes towards the desired opinion, creating a cascade of information diffusion. These two problems are important examples of a larger family of problems: controlling diffusive processes over networks through nodal interventions. Other examples include viruses inflicting computer networks or cascades of failures in power networks. In all these cases, an agent can steer the dynamics of the system using interventions that modify the states of a (relatively) small number of nodes. For instance, infected people can be asked to self-quarantine, preventing the spread of a disease, and key twitters may be targeted with coupons. However, a key difficulty is that the current state is often not fully observed, for example, we don't know the ground truth infection status for every node in the graph. \begin{figure}[t] \centering \includegraphics[width=0.9\columnwidth]{figs/RL_graphs_fig1_trimmed.png} \caption{ A viral infection process on a graph and an intervention aimed to stop its spread. Here, graph nodes represent people and edges represent interactions. At $t=1$ only two people are infected (red). At $t=2$ several interactions resulted in new \textit{exposed} people (yellow); At $t=3$ the blue node was selected to be quarantined to stop the viral spread. This paper presents a general framework for learning how to control such dynamic processes on graphs. }\label{fig:viralinfection} \end{figure} More formally, we consider a graph $G(t)=(\mathcal{V},\mathcal{E}(t))$ whose structure changes in time. $\mathcal{V}$ is the set of nodes and $\mathcal{E}(t)=\{e_{uv}(t)\}$ is the set of edges at step $t$. The state of a node $v\in\mathcal{V}$ is a random variable that depends on the interactions between $v$ and its neighbors. At each turn, the agent may select a subset of nodes and attempt to change their state. The goal is to minimize an objective that depends on the number of nodes in each state. For example, consider a setup where the agent tries to promote its product or opinion. At each step, the agent may select a set of seed nodes and attempt to influence them by presenting relevant information or ads. If those nodes are convinced, they may spread the information through future contacts. The optimization goal, in this case, is to maximize the number of influenced nodes. The problem of controlling the dynamics of a system using localized interventions is very hard, and for several reasons. First, it requires making decisions in a continuously changing environment with complex dependencies. Second, to solve the problem one must assess the potential downstream ripple effect for any specific node that becomes affected, and balance it with the probability that the node indeed becomes affected. Finally, models must handle noise and partial observability. In particular, it is well known that even the single-round, non-sequential, influence maximization problem is computationally hard \cite{Kempe2003}. Current approaches for solving this problem can be divided into two main families: (1) Monte Carlo simulation that estimates the utility of each decision \citep[see e.g.][]{Goyal2011}. These approaches can find good solutions for small to moderate-sized ($\sim 10^3$ nodes) graphs, but do not scale to larger graphs. (2) Heuristics based on topological properties of the known graph. For example, act on nodes with a high degree \citep[e.g.][]{Liu2017}. These approaches can be scaled to very large graphs, but are often sub-optimal. In addition to these two families, learning approaches have been used to mix different heuristics \cite{Chung2019,Tian2020}. We pose the problem of controlling a diffusive process on a temporally evolving graph as a partially-observed Markov decision process (POMDP). We then formulate the problem of selecting a subset of nodes for dynamical intervention as a {\em ranking } problem, and design an actor-critic RL algorithm to solve it. We use the observed changes of nodes states and connections to construct a temporal multi-graph, which has time-stamped interactions over edges, and describe a deep architecture based on GNNs to process it. The main challenge in our setup is that the underlying dynamics is not directly and fully observed. Instead, partial information about the state of some nodes is given at each point in time. While the diffusive process spreads by point contacts, new node information may impact our belief on the state of a node a few hops away from the source of new information. For example, consider an epidemic spreading on a network. Detecting an infected person directly modifies the probability that nodes that are connected to it by a path in the temporal graph are also infected (Fig.~\ref{fig:inf_vs_diff}). To address this issue, our architecture contains two separate GNN modules, one updates the node representation according to the dynamic process and the other is in charge of long range information propagation. These GNNs take as input a multi-graph over the nodes, where edges are time-stamped with the time of interactions. In addition, we show that combining RL with temporal graphs requires stabilizing information aggregation from other neighbors when updating nodes hidden states, and control how actions are sampled during training to ensure sufficient exploration. We show empirically the benefits of these components. \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{figs/example.png} \caption{The difference between two types of data propagation on the graph. Red nodes are positively tested epidemic carriers. Yellow nodes are undetected epidemic carriers. Blue nodes are inferred to be infected. Left - infection propagation involves only direct neighbours. Right - long range information propagation: The top node is detected as infected at time $t=2$. As it must have been infected by its neighbor, our belief regarding the infection state of people on this long infection chain, including those that are found many hops away, change. We use two separate GNNs in order to model these two processes. } \label{fig:inf_vs_diff} \end{figure} We test our approach on two very different problems, Influence Maximization and Epidemic Test Prioritization, and show that our approach outperforms state-of-the-art methods, often significantly. Our framework can be possibly further extended for problems beyond the ones mentioned here, e.g. traffic control, active sensing for complex scenes, etc. This paper makes the following contributions: {\bf (1)}~A new RL framework for controlling \textit{partially-observed diffusive processes over graphs}. We present a novel formulation of two challenging problems: the \textit{testing allocation} problem and the \textit{partially-observed influence maximization} problem. {\bf (2)}~A new architecture for controlling the dynamics of diffusive processes over graphs. Our architecture prioritizes interventions on a temporal multi-graph by leveraging deep Graph Neural Networks (GNNs). \textbf{(3)} A set of benchmarks and strong baselines, including network-based real-world contact tracing statistical data for COVID-19. Our RL approach achieves superior performance over these datasets. \section{A motivating example} \label{sec:toy-example} We begin with an example to illustrate the trade-offs of the problem (\figref{fig:toy-example}). In this example, our goal is to minimize the number of infected nodes in a social interactions graph. Given a list of time-stamped interactions between nodes, we form a discrete time-varying graph as follows. If $u$ and $v$ interact at time $t$, then the edge $e\!=\!(u,v)$ exists at time $t$. Each interaction is characterized by a transmission probability $p_e(t)$, meaning that a healthy node that interacts with an infected node at time $t$ becomes infected with probability $p_e(t)$. For the purpose of this example, assume that we can test a single node only at odd timesteps. If the node is positively tested as infected, it is quarantined and cannot further interact with other nodes. Otherwise, we do not perturb the dynamics and it may interact freely with its neighbors. Consider the "two stars" network in \figref{fig:toy-example}. The left hub (node $v_1$) has $m_1$ neighbors, and the right hub ($v_2$) has $m_2$. At $t=0,$ only the edge $(v_{1},v_{2})$ is present with transmission probability $p$. For all $t\geq1$, all edges depicted in \figref{fig:toy-example} exist with transmission probability $1$. Assume that this is known to the agent, and that at $t=1$ we suspect that $v_{1}$ was infected at $t=0$. Clearly, we should either test $v_1$ or $v_2$. It is easy to compute the expected number of infected nodes in both cases (details in Appendix \ref{sec:appendix-toy-example}). The decision would be to test $v_{2}$ if $2p\geq1+m_{1}/m_{2}$ and otherwise test $v_1$. This example illustrates that an optimal policy must balance two factors: \emph{the probability that the dynamics is affected} - that a test action yields a ``positive", and the future consequences of our action - the \emph{strategic importance} of selecting\emph{ $v_{1}$ vs. $v_{2}$}, expressed by the ratio $m_{1}/m_{2}$. A policy targeting likely-infected nodes will always pick node $v_1$, but since it only focuses on the first term and ignores the second term, it is clearly suboptimal. \begin{figure} \centering \includegraphics[width=0.6\columnwidth]{figs/toy_example.png} \caption{ A double star configuration. The state of $v_{2}$ is unknown at the $t=1$. $v_1$ is infected at $t=0$.} \label{fig:toy-example} \vspace{-1mm} \end{figure} \section{Problem Formulation} \label{sec:problem_formulation} We start with a general formulation of the control problem, and then give two concrete examples from different domains: Epidemic test prioritization, and dynamic influence maximization. Formal definitions are given in Appendix \ref{sec:problem_formulation_appendix}. \subsection{General formalism} Consider a graph $G(t)=(\mathcal{V},\mathcal{E}(t))$ whose structure changes in time. $\mathcal{V}$ is the set of nodes and $\mathcal{E}(t)=\{e_{uv}(t)\}$ is the set of edges at step $t$. Each edge $e_{uv}(t)$ is associated with features $\phi_{uv}(t)$ which may vary in time, and each node $v$ is characterized with features $\zeta_{v}(t)$. The state of a node $v\in\mathcal{V}$ is a random variable $ST_v(t)$ which can have values in $\mathcal{Y}=\{y_{1},y_{2},..\}$. The node's state dynamic depends on the interactions between $v$ and its neighbors, its state and the state of those neighbors, all at time $t-1$. At each step, the agent selects a subset $a(t)$ of $k$ nodes, and attempt to change the state of any selected node $v\in a(t)$, namely, apply a stochastic transformation on a subset of the nodes. Selecting nodes and setting their states defines the action for the agent, and plays the role of a knob for controlling the global dynamics of the process over the graph. The action space consists of all possible selections of a subset $a(t)$ of $k$ nodes $a(t)\subset V$. Even for moderate graph, with $\sim100-1000$ and small $k$ the action space ${|\mathcal{V}| \choose k }$ is huge. The optimization criterion depends only on the total number of nodes in state $y_i$, $c_{i}(t)$. The objective is therefore of the form $\max \sum_{t}\gamma^{t-t_{0}}g(c_{1}(t),c_{2}(t),..)$, where future evaluations are weighted by a discount factor $\gamma \le 1$. Additionally, the agent may be subject to constraints written in a similar manner $\sum_{i}f_{i}(c_{1}(t),c_{2}(t),..)\geq z_{i}(t)$. \subsection{Epidemic test prioritization} We consider the recent COVID-19 outbreak that spreads through social contacts. The temporal graph $G$ is defined over a group of nodes (people) $\mathcal{V}$, and its edges $\mathcal{E}(t)$ are determined by their daily social interactions. An edge $(u,v)$ between two nodes exists at time $t$ iff the two nodes interacted at time $t$. Each of these interactions is characterized by features $e_{uv}(t)$, including its duration, distancing and environment (e.g., indoors or outdoors). Additionally, each node $v$ has features $\zeta_{v}(t)$ (e.g., age, sex etc.). \textbf{The SEIR model dynamics} \cite{Lopez2020}. Every node (person) can be in one of the following states: \textit{susceptible} -- a healthy, yet uninfected person ($S$ state), \textit{exposed/latent} -- infected but cannot infect others ($L$ state), \textit{infectious} -- may infect other nodes ($I$ state), or \textit{removed} -- self-quarantined and isolated from the graph ($R$ state). A healthy node can become infected by interacting with its neighbors. The testing intervention changes the state of a node. If infected or exposed, its state is set to $R$, otherwise it remains as it is. More details can be found in the appendix. \textbf{Optimization goal, action space.} The objective is to minimize the spread of the epidemic, namely, minimize the number of infected people (in either $L, R$ or $I$ states), over time. Our setup differs from previous work (e.g., \cite{Hoffmann2020, Wang2020}) in two important aspects. First, we do not assume a node can be vaccinated or immunized against the epidemic. Second, we do not assume a node can be quarantined or disconnected from the graph without justification, namely, without a positive test result. Often, nodes perform required social functionality. Isolating a high-degree node from the network, like putting a bus-driver in quarantine, will either deteriorate the transportation network quality, or will require using a replacement driver that will have the same interactions pattern. A preemptive node removal would either not affect the network connectivity or impair the network functionality. \textbf{Observation space.} At each time $t$, the agent is exposed to all past interactions between network nodes, $\left\{ \mathcal{E}(t')|t'<t\right\} $. In addition, we are given partial information on the nodes state. The agent is provided with information on a subset of the infectious nodes at $t=0$. At every $t>0$, the agent observes all past test results, i.e, for every $v\in a(t'), t'<t$ we observe if node $s$ was healthy at $t'$ or not. \subsection{Dynamic influence maximization} The classical multi-round influence maximization problem \cite{domingos2001mining, Kempe2003, Lei2015} assumes the agent knows the groundtruth state of every node at every turn. More often than not, that is an unrealistic assumption. The agent can only know if a person is influenced if the person \emph{actively} signals it, for example by using a coupon code. Furthermore, there might be a substantial delay from the time the information was presented to the time a feedback was received. Therefore, we extend this setup to include partial observability. \textbf{Model Dynamics.} Each node is either \emph{Influenced} or \emph{Susceptible}. Influenced nodes try to influence their neighbors, following a dynamic generalization of two canonical models: Linear Threshold (LT) and Independent Cascades (IC). In an IC model, if $u$ is Influenced and $(u,v)\in \mathcal{E}_t$, then $u$ may influence $v$ according to a probabilistic model. In a LT model, each node $v$ is associated with a threshold $w_v$, and each edge $e$ carries an impact weight of $q_e$. If the sum of edge weights, the cumulative "peer pressure", of neighboring infected nodes exceeds $w_v$, node $v$ is influenced. See Appendix \ref{sec:problem_formulation_appendix} for details on these models. \textbf{Optimization goal, action space.} The goal is to maximize the number of \emph{Influenced} nodes. All nodes start at the \emph{Susceptible} state. At each step the agent selects a seed set $a(t)$ of $k$ nodes, and attempts to influence them. Each attempt succeeds with some probability $q$ independently for every $v\in a(t)$. \textbf{Observation space.} At every step, an influenced node may reveal that it is influenced, e.g. by clicking on ads, with some probability $\eta$. The set of these signals at previous times along with past interactions between nodes consists the observation space. \begin{figure}[t] \centering \includegraphics[width=0.85\columnwidth]{figs/RL_graphs_fig2.png} \caption{Schematic of our approach. The Ranking module receives as input a sequence of graphs and outputs scores over nodes. Scores are then used to sample actions, selecting nodes for intervention. Here, the person circled in blue is selected for quarantine and its connections are canceled (dashed blue lines). The downstream effect on epidemic progression is then fed as a loss to the ranking module.} \label{fig:Approachsechematics} \end{figure} \section{Approach} \label{sec:approach} This section introduces our main contribution. Our goal is to select a subset of nodes for influencing the dynamics. The direct approach would be to perform a Monte Carlo simulation of the diffusive process for every possible action at every step, and choose the best performing action. However, this approach does not scale, and is unfeasible even for moderate networks \citep[see][and Appendix \ref{sec:approach-discussion_appendix} for discussion]{Liu2017, Banerjee2020}. An alternative popular approach uses predefined heuristics or greedy approaches (e.g., \cite{Yang2020,Preciado2014, Murata2018}), but this is arbitrary and often sub-optimal. We propose a learning-based approach, which generalizes from past patterns collected during training. Since our goal is to maximize an objective over time in a dynamic environment, RL is a natural choice (Figure \ref{fig:Approachsechematics}). Yet, even with a learning approach, solving the general case of the \textit{subset selection} problem would be combinatorially hard \cite{Kempe2003} and is difficult to scale to large graphs. At the other extreme, a simple approximated solution can be achieved by scoring each node independently and then selecting the top-ranked nodes. Unfortunately, this approximation would potentially be far from optimal because it neglects correlations across nodes that are crucial. Therefore, it is important that node selection would consider other nodes, at least locally. For example, creating tight clusters of \emph{Influenced} nodes is critical in Influence Maximization under the Linear Threshold model (see Appendix \ref{sec:problem_formulation_appendix}). Assume that the intervention budget is sufficient for establishing a single cluster but there exist two equally beneficial regions to promote such cluster. The agent should learn to focus on one region rather than spread on two regions. This requires learning to choose optimal subsets rather than choosing nodes independently. Our approach takes a mid-road: We use a graph neural network to compute per-node scores, where each node is exposed to the features of nodes in its extended $m$-hop neighborhood (where $m$ is the depth of the GNN). This way, agent can learn to take into account complex correlations, and to select high-quality subsets by ranking nodes by their scores. \subsection{The Ranking Module} \label{sec:ranking_module} \paragraph{Overview.} In our approach, an RL agent receives as input the node and edge features of the temporal graph, and scores each node. The module that performs that scoring is called the {\it ranking module} (\figref{fig:ranking}). Scores are used to generate a probability distribution over nodes, and then for sampling a subset of $k$ nodes for testing. Namely, the scores encode the agent policy. The ranking module also updates the internal representation of each node, which aggregates past observations and information. The score of a node is affected both by propagation dynamics and by information available to the agent. One may hope that on a short time scale the node score would only be affected by its neighboring nodes. Unfortunately, information can propagate long distances in the graph almost instantaneously, because revealing the state of one node in a long chain affects other nodes To handle this effect, the ranking module contains two GNNs (see Fig.~\ref{fig:ranking}). (1) A local diffusion component $D$ updates the diffusion process state; and (2) a long-range information component $I$ updates the information state. We use Proximal Policy Optimization (PPO) \cite{Schulman2017} to optimize our agent. We sequentially apply the suggested action, log the (state, action) tuple in an experience replay buffer, and train our model based on the PPO loss term. We further motivate our framework and extended the discussion on our design choices in Appendix \ref{sec:approach-discussion_appendix}. \subsection{Modules} \textbf{Input.} The input to the ranking module consists of three feature types: (1) \textit{Static node features} $\zeta^s_v(t)$: e.g., topological graph centralities (betweenness, closeness, eigenvector, and degree centralities) and random node features. (2) \textit{Dynamic node features} $\zeta^d_v(t)$ : All intervention results up to the current timestamp. We denote all nodes features as a concatenation $\zeta_v(t)=[\zeta^s_v(t),\zeta^d_v(t)]$. (3) \textit{Edge features} and the structure of the temporal graph $\mathcal{E}(t)$: All previous interactions up to the current step, including the transmission probability for each interaction. All these features are scalars, except the dynamic node features, which are encoded as one hot vectors. Figure \ref{fig:ranking} illustrates the basic data flow in the ranking module. \begin{figure}[t] \centering \includegraphics[width=0.8\columnwidth]{figs/RL_graphs_fig3.png} \caption{The ranking module. It is composed of 4 neural networks $I$,$D$,$G$,$F$, which update the nodes scores and hidden states at each time step.} \label{fig:ranking} \end{figure} \textbf{Local diffusion GNN.} The spread through point contact is modeled by a GNN $D$. As the diffusive process spreads by only one hop per step, it is sufficient to model the spread with a single GNN layer. Formally, denote by $u\sim_{t}v$ an interaction between $u$ and $v$ at time $t$, and by $p_{vu}$ the probability of transmission during this interaction. For each $v$, the output of $D(\cdot)$ is a feature vector denoted by $d_v(t)$: \begin{align*} d_{v}(t) & =\sum_{u\sim_{t}v}p_{vu}(t)\cdot M_{e}(\zeta_{v}(t),\zeta_{u}(t);\theta_{m_e}), \end{align*} where $M$ is multilayer perceptron (MLP). Rather than considering the probability as an edge feature, this component mimics the dynamic process transition rule to accelerate learning. \textbf{Long-range information GNN.} GNN $I$ computes the {\em information state} of each node. As discussed above, updated information on a node $u$ a few hops away from node $v$ may abruptly change our belief on the state of $v$. Furthermore, this change may occur even if $v$ and $u$ did not interact in the last time step but rather a while ago. To update the information state, we construct a cumulative multi-graph $G'$ where the set of edges between nodes $v$ and $u$ at time $t$ are all the interactions that occurred during the last $\tau$ steps. The features of each edge $\phi_{vu}(t')$ at time $t'$ are the interaction delay $t-t'$ and the transmission probability $p_{v,v'}(t')$. The information features are the output of $k$-layer GNN; the $l^{th}$ layer is: \[ x_{v}^{l}(t)=\sum_{v'\sim_{t}v}M^{l}(x_v^{l-1}(t),x_{v'}^{l-1}(t),\phi_{vv'}(t);\theta_M^l). \] As before, $M^l$ is an MLP, with $x_{v}^{0}(t)=\zeta_{v}(t)$ and $i_{v}(t)=x_{v}^{k}(t)$ are the final node features. \textbf{Score and hidden state update.} For every node we hold a hidden state $h_{v}(t)$, updated according to a neural network $G$, \begin{equation} h_{v}(t)=G(h_{v}(t-1),\zeta_{v}(t),d_{v}(t), i_{v}(t) ;\theta_{g}) \end{equation} After updating the new node hidden states, we use them to calculate the node scores using a neural network $F$, \begin{equation} s_{v}(t)= F(h_{v}(t),h_{v}(t-1),\zeta_{v}(t);\theta_{f}) \end{equation} Here, $F$ and $G$ are two additional components (see Fig.~\ref{fig:ranking}). $F$ is an MLP, while $G$ can be either an MLP or recurrent module such as GRU. \subsection{Sampling and scoring} During inference, we pick the top $k$ scored nodes. During training, to encourage exploration we use the score per node $s_v(t)$ to sample $k$ nodes. We (1) map the score of $n$ nodes to a probability distribution (2) sample a node, and (3) adjust the distribution by removing its weight. We repeat this process $k$ iterations (sample without replacement). \textbf{Score-to-probability.} Usually, node scores are converted to a distribution over actions using a softmax. As demonstrated in \cite{mei2020}, this approach is problematic as node probabilities decay exponentially with their scores, leading to two major drawbacks: it discourages exploration of low-score nodes, and also limits sensitivity to the top of the distribution rather than at the $k$-th ranked node. Instead, we set the probability to sample an action $a_{i}$ to \begin{equation} \Pr(a_{i})=\frac{x_{i}'}{\sum x_{i}'}\quad \textrm{, with } x_{i}'=x_{i}-\min_{i}x_{i}+\epsilon, \label{eq: score-to-prob} \end{equation} where $\{x_{i}\}$ is the set of scores and $\epsilon$ a constant. The probability difference between low scoring nodes and high scoring nodes becomes less extreme than softmax. Furthermore, the parameter $\epsilon$ controls the initial exploration ratio. We compare our approach with the recent escort transform \cite{mei2020} that is considered to be a state-of-the-art score-to-probability method. As shown in Appendix \ref{sec:experimental details}, our method outperforms the escort transform in this problem. \section{Experiments \label{sec: Experiments}} We evaluated our approach in two tasks: (1) Epidemic test prioritization, and (2) Dynamic influence maximization. More experiments and details are in Appendix \ref{sec:experimental details}. \textbf{Real-World Datasets.} We tested our algorithm and baselines on graphs of different sizes and sources, ranging from 5K to over 100K nodes. \textbf{(1) CA-GrQcA} A research collaboration network \cite{network_database}. \textbf{(2) Montreal}, based on WiFi hotspot tracing\cite{Hoen2015}. \textbf{(3) Portland:} a compartment-based synthetic network \cite{Wells2013,Eubank2004}. \textbf{(4) Email:} An email network \cite{Leskovec2007a} \textbf{(5) GEMSEC-RO: } \cite{rozemberczki2019gemsec}, friendship relations in the Deezer music service. All these networks have been extensively used in previous works, in particular in epidemiological studies, as key networks models \cite{Sambaturu, Yang2020, Herrera2016,Wells2013,Eubank2004}. Table \ref{tab:datasets-info} summarizes the datasets. \textbf{Synthetic Datasets.} We considered three synthetic, random network families: \textbf{(1) Community-based networks} have nodes clustered into densely-connected communities, with sparse connections across communities. We use the \textit{Stochastic Block Model} (SBM, \cite{abbe2017community}), for 2 and 3 communities. \textbf{(2) Preferential attachment (PA)} networks exhibit a node-degree distribution that follows a power-law (scale-free), like those found in many real-world networks. We used the dual Barbarsi-Albert model \cite{Moshiri2018}. \textbf{(3) Contact-tracing networks.} We received anonymized high-level statistical information (see Appendix \ref{sec:experimental details}) about real contact tracing networks, collected during April 2020. \textbf{Generating temporal graphs.} For all networks except CT graphs, at each time step $t$ we select uniformly at random a subset of edges $\mathcal{E}(t)$ and then assign to each edge a transmission probability $q_e(t)$ sampled uniformly in $[0.5,1]$. We use a different methodology for the CT graphs, See Appendix \ref{sec:experimental details} for details. \textbf{Training procedure.} Algorithms were trained on randomly generated PA networks with $1000$ nodes. Each experiment was performed with at least three random seeds. \subsection{Epidemic test prioritization} \subsubsection{Baselines} \label{sec:baselines} We compare methods from three categories. \textbf{A. Preprogrammed heuristic (no-learning) baselines.} Rank nodes based on: \emph{(1) Infected neighborhood}: Number of known infected nodes in their 2-hop neighborhood \cite{Meirom2015, 8071015}. \emph{(2) Probabilistic risk}: Probability of infection at time $t-1$. Using dynamic programming to analytically solve the probability propagation. \emph{(3) Degree centrality} \cite{Salathe2010, Sambaturu}. \emph{(4) Eigenvector centrality:} \cite{Preciado2014,Yang2020}. \textbf{B. Supervised learning.} Learn the risk per-node using features of the temporal graph, its connectivity, and infection state. Each time step $t$ and node $v_i$ is a sample, and its label is determined by the next step. \emph{(5) Supervised (vanilla).} Features include a static component described in \secref{sec:ranking_module}, and a dynamic part that contains the number of infected neighbors and their neighbors. \emph{(6) Supervised (+GNN).} Like \#5, the input is the set of all historic interactions of $v_i$'s and its $d$-order neighbors \emph{(7) Supervised (+weighted degree).} Like \#6, the loss weighs nodes are by their degree. \emph{(8) Supervised (+weighted degree +GNN).} Like \#6 above, using degree-weighted loss like \#7. \textbf{C. RL algorithms:} \textbf{\RLGN{}} is our algorithm described in \secref{sec:approach}. The input to \textbf{(9) RL-vanilla} is the same as in (\#1) and (\#6) above. Correspondingly, the GNN module described in \secref{sec:approach} is replaced by a DNN similar to (\#6). \textbf{Evaluation Metric.} The end goal of quarantining and epidemiological testing is to minimize the spread of the epidemic. Our success metric is therefore the percent of nodes kept healthy throughout the simulation. An auxiliary metric we sometime used was \textbf{\%contained:} The probability of containing the epidemic. This was computed as the fraction of simulations having cumulative infected nodes smaller than a fraction $\alpha=0.4$. \subsubsection{Results} \label{sec:results} In the first set of experiments, we compared RLGN with the 9 baselines described in Section \ref{sec:baselines} on the synthetic networks described above. The results reported in Table \ref{tab:comaprison-chart-PA} show that RLGN outperforms all baselines on all network types. We selected the top-performing algorithms and evaluated them on the large, real-world networks dataset. \begin{SCtable} \centering \scriptsize \setlength{\tabcolsep}{5pt} \caption{ \% of healthy nodes achieved on a preferential attachment (PA) network, and contact tracing (CT) network. Here, two nodes were selected for testing at each step, $k=2$.} \scalebox{0.99}{{\sc{ \centering \begin{tabular}{lcc} & PA & CT\\ \hline Tree-based (2) & $10\pm7$ & $11\pm3$\\ Counter model (1) & $7\pm7$ & $14\pm5$ \\ Degree (3) & $30\pm2$ & $16\pm1$ \\ Eigenvector (4) & $30\pm1$ & $16\pm1$ \\ SL (vanilla) (5) & $13\pm3$ & $17\pm1$\\ SL + GNN (6) & $34\pm3$ & $32\pm$2\\ SL + deg (7) & $15\pm3$ & $18\pm1$\\ SL + deg + GNN (8)& $33\pm3$ & $32\pm1$\\ \hline RL (vanilla) (9) & $17\pm1$ & $16\pm1$\\ RLGN (ours) & \textbf{52}{$\boldsymbol{\pm}$}\textbf{2} & \textbf{40}{$\boldsymbol{\pm}$}\textbf{1} \\ \hline \end{tabular} }}} \label{tab:comaprison-chart-PA} \end{SCtable} Table \ref{tab:dataset-healthy} compares the performance of the RLGN and the best baseline (SL) on the large-scale datasets. We included the centralities baselines (\#3,\#4) in the comparison as they are heavily used in epidemiological studies. Table \ref{tab:dataset-healthy} shows that RLGN consistently performs better than the baselines, and the gap is clearly statistically significant. We also evaluated the performance of RLGN on a Preferential Attachment network with $50,000$ nodes (mean degree $=2.8$), as this random network model is considered a reasonable approximation for many other real-world networks. The mean percentile of healthy nodes at the end of the episode was $51\pm1$ for RLGN, while for the SL+GNN it was only $21\pm2$, a difference of more than $15$ STDs. \textbf{Analysis.} To gain insight into these results, \figref{fig:three_communities} traces the fraction of contained epidemics and infected nodes during training in 3-community networks. Supervised learning detects \emph{substantially more infected nodes} than RLGN (right panel), but these tend to have a lower future impact on the spread, and it fails to contain the epidemic (left). A closer look shows that RLGN, but not SL, successfully learns to identify and neutralize the \emph{critical nodes that connect communities} and prevent the disease from spreading to another community. See a video highlighting these results \href{https://youtu.be/Rhqy7YY9gX8}{online} \footnote{Link: \url{https://youtu.be/Rhqy7YY9gX8}}. When would RLGN be successful? In sparsely connected networks, it is easy to cut long infection chains, and both approaches succeed. In densely connected networks, there are no critical nodes, because there are many paths between any two nodes. This can also be viewed in terms of the $R_0$ coefficient, the mean number of nodes infected by a single diseased node. The greater $R_0$, the more difficult it is to contain the epidemic. Therefore, we expect RLGN to excel in intermediate regimes. Fig.~\ref{fig:stability}(a) indeed shows that RL has a significant advantage over supervised+GNN for a range of $R_0$ values between $2.0$ and $2.9$. We have deepened our analysis, and investigated: (1) Can we quantify the algorithm by their ability to reduce $R_0$, the mean number of nodes infected by a single diseased node? Can we quantify the performance by the number of tests required to achieve the same level of performance, measuring their effective test utilization? (2) How robust the trained algorithms to variations in the epidemiological parameters? (3) How does the performance gap between the algorithms scale with the network size? Due to lack of space, we expand on these topics in Appendix \ref{sec:experimental details}. Appendix \ref{sec:experimental details} also includes a comparison between RLGN and the best performing baselines across a range of network sizes, initial infection sizes and testing capacities (Table \ref{tab:300-nodes-pa}). \textbf{Ablation studies.} We assess the importance of key elements in our framework using ablation studies. First, to quantify the contribution of the information module, we removed it completely from our DNN module, keeping only the epidemic module. The full DNN module achieved a contained epidemic score of $0.77\pm0.06$, while the ablated DNN module corresponding score was $0.62\pm0.10$, a degradation of more than $20\%$. This shows that the information module has a critical role in improving the performance of the RLGN framework. Second, in the opposite direction, one may wonder: Why separate local and long-range GNNs, rather than a single higher-capacity network? We found that using a local-diffusion GNN training converges faster (Fig. \ref{fig:local_diffusion}). Presumably, because it models the process more closely to the true spreading. Appendix \ref{sec:experimental details} contains additional ablation studies of key elements in our framework: (A) Our score-to-probability function outperforms the popular softmax distribution and escort transform. (B) Internal state normalization in scale-free networks accelerates training substantially. \ignore{ \begin{table*} \centering{}% \caption{\label{tab:dataset-healthy}The mean percentile of healthy nodes after a 20 steps. RLGN performs better on all datasets with a statistically significant gap. At each step 1\% of the nodes are tested.} \begin{tabular}{|l|c|c|c|c|c|} \hline & CA-GrQc & Montreal & Portland & Email & GEMSEC-RO\\ \hline \hline Degree & $25.52\pm0.01$ & $12.83\pm0.01$ & $0.67\pm0.01$ & $71.14\pm0.02$ & $2.43\pm0.01$\\ \hline E.vector & $25.37\pm0.01$ & $8.06\pm0.01$ & $0.04\pm0.01$ & $55.10\pm0.02$ & $2.41\pm0.01$\\ \hline SL & $29.79\pm0.02$ & $23.09\pm0.03$ & $1.57\pm0.01$ & $68.45\pm0.05$ & $4.26\pm0.01$\\ \hline RLGN & \textbf{42.69}{$\boldsymbol{\pm}$}\textbf{0.03} & \textbf{39.68}{$\boldsymbol{\pm}$}\textbf{0.03} & \textbf{3.71}{$\boldsymbol{\pm}$}\textbf{0.01} & \textbf{89.19}{$\boldsymbol{\pm}$}\textbf{0.02} & \textbf{6.52}{$\boldsymbol{\pm}$}\textbf{0.01} \\ \hline \end{tabular} \end{table*} } \setlength{\tabcolsep}{2pt} \begin{table}[t] \centering{}% \small \caption{\label{tab:dataset-healthy}Mean percentile of healthy nodes after 20 steps. RLGN perform better on all datasets. In all cases, std $<0.1$. 1\% of nodes are tested at each step. } \begin{tabular}{lccccc} \toprule & CA-GrQc & Montreal & Portland & Enron & GEMSEC-RO\\ \midrule Degree & $25.5$ & $12.8$ & $0.7$ & $71.1$ & $2.4$\\ E.vector & $25.4$ & $8.1$ & $0.04$ & $55.1$ & $2.4$\\ SL & $29.8$ & $23.1$ & $1.6$ & $68.5$ & $4.3$\\ RLGN & \textbf{42.7} & \textbf{39.7}& \textbf{3.71} & \textbf{89.2} & \textbf{6.5} \\ \bottomrule \end{tabular} \end{table} \begin{figure} \centering \includegraphics[width=1.0\columnwidth]{figs/three_communtities.png} \caption{Supervised \textit{vs.} RL with 3-community networks. \textbf{Left:} RLGN successfully learns to contain the epidemic 60\% of the time (see containment definition in Appendix \ref{sec:experimental details}), while SL fails. \textbf{Right:} SL isolates many more infected nodes, but less important ones.} \label{fig:three_communities} \end{figure} \subsection{Influence Maximization} \setlength{\tabcolsep}{4pt} \begin{table*} \centering{}% \vskip 0.15in \small \caption{Influence Maximization: Mean percentile of influenced nodes after 15 steps \label{tab:IM-geometric}.} \centering \begin{tabular}{lccccc} \toprule & CA-GrQc & Montreal & Enron & GEMSEC-RO & CA-HEPTh \\ \midrule LIR \cite{Liu2017} & $7.3\pm0.3$ & $86.2\pm0.7$ & $29\pm0.3$ & $0.25\pm0.02$ & \textbf{$\boldsymbol{9.2\pm0.3}$}\\ LIR (filtered) & $8.0\pm0.2$ & $\boldsymbol{86.4\pm0.7}$ & $28.8\pm0.3$ & $0.22\pm0.02$ & $8.5\pm0.3$\\ Degree & $8.4\pm0.2$ & $85.5\pm0.8$ & $\boldsymbol{31.6\pm0.6}$ & $0.07\pm0.01$ & \textbf{$\boldsymbol{9.2\pm0.3}$}\\ Degree Discounted \cite{Murata2018} & $8.7\pm0.2$ & $85.6\pm0.7$ & $26.7\pm0.6$ & $0.05\pm0.01$ & $8.4\pm0.2$\\ Eigenvector \cite{Bozorgi2016} & $8.3\pm0.2$ & $82.9\pm0.8$ & $\boldsymbol{31.8\pm0.5}$ & $0.07\pm0.01$ & $2.2\pm0.2$\\ RLGN (ours)& $\boldsymbol{10.2\pm0.6}$ & $\boldsymbol{87.4\pm0.5}$ & \textbf{$\boldsymbol{31.3\pm0.6}$} & $\boldsymbol{5.8\pm0.3}$ & \textbf{$\boldsymbol{9.1\pm0.5}$}\\ \bottomrule \end{tabular} \end{table*} \textbf{Baselines}. Unlike the epidemic test prioritization, in this problem there is no supervised signal; there is no immediate feedback that may be used for supervision. We compare our RLGN framework against the state-of-the-art scalable algorithms. \emph{(1) LIR} \cite{Liu2017} is an algorithm for top-k ranking for the IM problem. It was shown to achieve similar performance to MC based methods. \emph{(2) LIR (filtered):} LIR was designed for a fully observable setup. We extend this algorithm to a partially observed setup and filter out nodes with an identified \emph{influenced} neighbor. The motivation is that it is likely that such nodes are already influenced or likely to be influenced soon. \emph{(3) Degree discounted} \cite{Chen2009} is a topology-based algorithm that was shown to achieve a state-of-the-art performance on some networks, and \emph was recently extended to temporal graphs \cite{Murata2018}. \emph{(4) Degree Centrality} and \emph{(5) Eigenvector Centrality}, defined previously, were also used extensively \cite{Lei2015,Chen2014,Bozorgi2016}. \textbf{Results}. We have compared RLGN against the aforementioned baselines on the real-world datasets in Table \ref{tab:IM-geometric}. We included an additional (CA-HEPTh) network that was frequently used as a benchmark for this problem. Table \ref{tab:IM-geometric} shows that RLGN performs remarkably in this domain as well. It achieves state-of-the-art performance, often with a considerable gap. Additional experiments and experimental details appear in Appendix \ref{sec:experimental details}. \section{Previous work \label{sec:related_work}} \textbf{Deep Learning on graphs.} Graph neural networks (GNNs) are deep neural networks that can process graph-structured data \cite{Sperduti1993, Sperduti1994, Sperduti1997, Pollack1990, Kuchler1996, kipf,Gilmer2017,Duvenaud2015, Hamilton2017, Velickovic2017}. Several works combine recurrent mechanisms with GNNs to learn temporal graph data, \cite{liu2019towards, rossi2020temporal, liu2020towards, pareja2020evolvegcn}. Further information can be found in \cite{kazemi2020representation}. \textbf{Ranking on graphs.} The problem of ranking on graphs is a fundamental CS problem. It has various applications such as web page ranking \cite{page1999pagerank,agarwal2006ranking} and knowledge graph search \cite{xiong2017explicit}. \textbf{Reinforcement learning and graphs} studies can be split into two main categories: leveraging graph structure for general RL problems \cite{Zhang2018,Jiang2018}, and applying RL methods for graph problems. Our work falls into the latter. An important line of work uses RL to solve NP-hard combinatorial optimization problems on graphs. \cite{Zhu,Dai, Wei2021}. \textbf{Manipulation of dynamic processes on graphs. } The problem of node manipulation (e.g., vaccination) for controlling epidemic processes on graphs was intensively studied \cite{Hoffmann2020, Medlock2009}. This problem is often addressed in the setup of the fire-fighter problem and its extensions \cite{firefighter_survey, Tennenholtz2017, Sambaturu}. Other work considered the problem of vaccination assignments, and cast this problem into a minimal cover problem \cite{Wang2020,Song2020, Wijayanto2019}. Other common approaches include developing centrality measures designed to highlight bottleneck nodes \cite{Yang2020}, or using spectral methods for allocating resources \cite{Saha2015, Preciado2014, Ogura2017}. Alternative line of research \cite{MILLER2007780, Cohen2002} developed heuristics for the same task. In most previous work setups a single decision is taken. In our multi-round setup, the agent performs a sequential decision making. The agent needs to balance between retrieving information (for better informed future decisions), maximizing the probability that the intervention will be successful, and optimizing the long-term goal. \textbf{Influence Maximization}, (IM) is a canonical optimization problem of dynamical processes on graphs. IM was first presented in \cite{Kempe2003}, and proved to be NP-Hard and hard to approximate. Key approximation algorithms were derived in \cite{Goyal2011, Nguyen2016}, but since they do not scale to large graphs, many alternative heuristics were developed \cite{Murata2018,Liu2017}. For surveys, see \citet{Banerjee2020, Li2018}. Multi-armed Bandit was used for estimating model parameters \cite{Vaswani2017, Lei2015}. The IM formulation was extended to a multi-round framework by \citet{Lin2015}. \citet{Chung2019, Tian2020, Lin2015} used RL to find the optimal combination of heuristics from a short list of hand-designed features. These approaches are limited by the small number of pre-selected heuristics and by the problem-specific, hand-crafted features. In contrast, our approaches is general and it is not limited to reweighting or a predefined subset of policies, neither uses hand-designed, problem-specific features. Our agent learns a policy from scratch and uses GNNs to generalize to different domains \cite{Yehudai2020}. \section{Conclusions} This paper shows that combining RL with GNNs provides a powerful approach for controlling diffusive processes on graphs. Our approach handles an exponential state space, combinatorial action space and partial observability, and achieves superior performance on challenging tasks on large, real-world networks. The approach and model discussed in this paper can be applied to important problems other than epidemic control and influence maximization. For example, fake news can be maliciously distributed, and spread over the network. A decision maker can verify the authenticity of items, but only verify a limited number of items per a time period. The objective would be to minimize the total number of nodes that observe fake items. Our approach assumes that a decision taken by considering only $k$ hops neighborhood of each node is a fairly good approximation to the optimal policy which takes into account the whole graph. If long range correlations exists, this may deteriorate performance. As such, it is sufficient to train our model on small graphs and infer on a larger graph. An interesting question is the ability of our approach to address edge cases that may result from this training protocol, and the generalization ability of our model as a function of long-range correlations in the data. A key concern for real world application is privacy preservation of individual nodes. Our approach requires local aggregated information about the node's neighborhood, compared to other approaches (e.g., \cite{Kempe2003,Yang2020} which required detailed information on the complete graph. Furthermore, recent papers \cite{zhou2021vertically} have shown that it is possible to use graph neural network while preserving privacy, and we leave it for future research to apply such approaches in this setup. \bibliographystyle{icml2021}
{'timestamp': '2021-07-12T02:09:26', 'yymm': '2010', 'arxiv_id': '2010.05313', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05313'}
arxiv
\section{Appendix} \label{sec:appendix} \subsection{Proofs for Subject Reduction Theorem and Progress Theorem} \label{app:sr} We first list several basic lemmas. In the proofs, we often omit $I$ or $\mathcal{P}$ unless required. \begin{lemma}[Inversion lemma] \label{lem:Inv_S} \begin{enumerate}[label=(\arabic*)] \item\label{lem:Inv_S1}% Let $\der{\Gamma}{\ensuremath{{P}}}{T}$. \begin{enumerate}[label=(\alph*)] \item\label{lem:Inv_S1a} If $\ensuremath{{P}} = \sum\limits_{i\in I}\procin {{\sf p}} {\ell_i(x)} {\ensuremath{Q}_i}$, then $ \&_{i\in I}\procin {{\sf p}} {\ell_i{(\S_i)}}{T_i}\subtT $ and $ \der{\Gamma, x:\S_i}{ \ensuremath{Q}_i}{T_i} ,$ for every $i\in I.$ \item\label{lem:Inv_S1b} If $\ensuremath{{P}} = \procout {{\sf p}}{\ell}{\kf{e}}{\ensuremath{Q}}$, then $ \der{\Gamma}{\kf{e}}{\S}$ and $\der{\Gamma}{ \ensuremath{Q}}{T'} $ and $\S'\leq\vcentcolon \S$ and $\procout{{\sf p}}{\ell}{\S'}{T'}\subtT.$ \item\label{lem:Inv_S1c} If $\ensuremath{{P}} = \cond{\kf{e}}{\ensuremath{{P}}_1}{\ensuremath{{P}}_2} $, then $\der{\Gamma}{\ensuremath{{P}}_1}{T_1}$ and $\der{\Gamma}{\ensuremath{{P}}_2}{T_2}$ and $T_1\leqslant T$ and $T_2\subtT.$ \item\label{lem:Inv_S1d} If $\ensuremath{{P}} = \mu {\roleVar}.\ensuremath{Q} $, then $ \der{\Gamma, {\roleVar}:T}{\ensuremath{Q}}{T} $. \item\label{lem:Inv_S1e} If $\ensuremath{{P}} = {\roleVar}$, then $\Gamma = \Gamma', {\roleVar}:T'$ and $T'\subtT$. \item\label{lem:Inv_M1}% If $P=\motion{dt}{a}.{Q}$, then $\der{\Gamma}{Q}{T'}$ and $T'\subtT$. \item\label{lem:Inv_M2 If $P=\sum\limits_{i\in I}{\procin \pq {\ell_i(x_i)} \ensuremath{{P}}_i}+\motion{dt}{a}.{Q}$, then $\&_{i\in I}\procin {{\sf p}} {\ell_i{(\S_i)}}{T_i} \& T'\subtT $ and $ \der{\Gamma, x:\S_i}{ \ensuremath{{P}}_i}{T_i} ,$ for every $i\in I$ and $\der{\Gamma}{\motion{dt}{a}.{Q}}{T'}$. \end{enumerate} \item\label{lem:Inv_S2} If $\der{} {\prod\limits_{i\in I}\pa{{\sf p}_i}{\ensuremath{{P}}_i}}\ensuremath{{\sf G}}$, then $\participant \ensuremath{{\sf G}}\subseteq\set{{\sf p}_i\mid i \in I}$ and $\der{}{\ensuremath{{P}}_i}{\projt \ensuremath{{\sf G}} {{{\sf p}_i}}}$ for every $i\in I$. \end{enumerate} \end{lemma} \begin{proof} By induction on type derivations. \end{proof} \begin{lemma}[Substitution lemma]\label{lem:Subst_S} \label{lem:subs_X} \begin{enumerate} \item If $\der{\Gamma, x:\S}{\ensuremath{{P}}}{T} $ and $\der{\Gamma}{\kf{v}}{\S}$, then $\der{\Gamma}{\ensuremath{{P}} \sub{\kf{v}}{x}}{T}$. \item If $\der{\Gamma, {\roleVar}:T}{\ensuremath{{P}}}{T} $ and $\der{\Gamma}{\ensuremath{Q}}{T}$, then $\der{\Gamma}{\ensuremath{{P}} \sub{\ensuremath{Q}}{{\roleVar}}}{T}$. \end{enumerate} \end{lemma} \begin{proof} By structural induction on $\ensuremath{{P}}$. \end{proof} \begin{lemma}{Subject Congruence}\label{lem:cong}$ \ $ \begin{enumerate}[label=(\arabic*)] \item \label{lem:congP} Let $ \der{\Gamma}{\ensuremath{{P}}}{T} $ and $ \ensuremath{{P}}\equiv\ensuremath{Q}$. Then $ \der{\Gamma}{\ensuremath{Q}}{T} $. \item \label{lem:congN} Let $ \der{}{M}{\ensuremath{{\sf G}}}$ and $M\equiv M'$. Then $ \der{}{M}{\ensuremath{{\sf G}}}$. \end{enumerate} \end{lemma} \begin{proof} By case analysis on the derivation of $ \ensuremath{{P}}\equiv \ensuremath{Q} $ and $ M\equiv M'$ \begin{enumerate} \item The only interesting case is \rulename{t-rec}. So, in this case, $ \ensuremath{{P}} = \mu {\roleVar}.\ensuremath{{P}}' $ and $ \ensuremath{Q} = \ensuremath{{P}}'\sub {\mu {\roleVar}.\ensuremath{{P}}'}{{\roleVar}}.$ By Lemma~\ref{lem:Inv_S}.\ref{lem:Inv_S1}.\ref{lem:Inv_S1d} we get $ \der{\Gamma,{\roleVar}:T}{\ensuremath{{P}}'}{T}. $ From that, $ \der{\Gamma}{\ensuremath{{P}}}{T} $ and Lemma~\ref{lem:subs_X}, we conclude. \item Straightforward. \end{enumerate} \end{proof} \begin{lemma} \label{lem:erase} If\; $\tout\pq\ell{\S}.{T}\leq\projt\ensuremath{{\sf G}}{\sf p}$ % \;and\; $\tin{\sf p}\ell{\S'}.{T'} \leq \projt\ensuremath{{\sf G}}\pq$, % then \begin{enumerate}[label=(\arabic*)] \item\label{item:erase:subp}% $T \leqslant \projt{(\redG\ensuremath{{\sf G}}{\sf p}\ell{\sf q})}{\sf p}$ \item\label{item:erase:subq}% $T' \leqslant \projt{(\redG\ensuremath{{\sf G}}{\sf p}\ell{\sf q})}{\sf q}$; and \item\label{item:erase:g-consume-proj-r}% $\projt\ensuremath{{\sf G}}{\sf r} \leqslant \projt{(\redG\ensuremath{{\sf G}}{\sf p}\ell\pq)}{\sf r}$ % \;for\; ${\sf r}\not={\sf p}$, ${\sf r}\not=\pq$.% \end{enumerate} \end{lemma} \begin{proof} By induction on $\ensuremath{{\sf G}}$. \end{proof} \theoremSR* \begin{proof} The second close is a corollary from the first close and Lemma~\ref{lem:cong}. The proof is by induction on the derivation of $M \longrightarrow M'.$ \begin{itemize} \item[] $\rulename{comm}$: In this case, we can let: $M=\pa{\sf p}{\sum\limits_{i\in I} \procin{\pq}{\ell_i(x)}{\ensuremath{{P}}_i}}\; \ | \ \;\pa\pq{\procout {\sf p} {\ell_j}{\kf{e}} \ensuremath{Q}}$ and $M' = \pa{\sf p}{\ensuremath{{P}}_j}\sub{\kf{v}}{x}\; | \;\pa\pq\ensuremath{Q}$ with $\eval{\kf{e}}{\kf{v}}$. From $\der{}M\ensuremath{{\sf G}},$ by Lemma \ref{lem:Inv_S}\ref{lem:Inv_S2}, \begin{align} & \participant\ensuremath{{\sf G}}\subseteq \{{\sf p},{\sf q}\} \cup \{{\sf p}_l: l\in L\} \\ & \der{}{\sum\limits_{i\in I} \procin{\pq}{\ell_i(x)}{\ensuremath{{P}}_i}}{\projt{\ensuremath{{\sf G}}}{{\sf p}}} \label{eqv:proof28}\\ & \der{}{\procout{{\sf p}}{\ell_j}{\kf{e}}{\ensuremath{Q}}}{\projt{\ensuremath{{\sf G}}}{{\sf q}}} \label{eqv:proof29} \\% & \der{}{\ensuremath{{P}}_l}{\projt{\ensuremath{{\sf G}}}{{\sf p}_l}} \text{ for every }l \in L \label{eqv:proof30} \end{align} By Lemma \ref{lem:Inv_S}\ref{lem:Inv_S1}\ref{lem:Inv_S1a}, from \eqref{eqv:proof28}, \begin{align} & \bigwedge\limits_{i\in I}\tin {\sf q} {\ell_i}{\S_i}.{T_i} \leqslant \projt{\ensuremath{{\sf G}}}{{\sf p}} \label{eqv:proof31}\\ & \der{x:\S_i}{\ensuremath{{P}}_i}{T_i} \text{ for every }i\in I \label{eqv:proof32}% \end{align} By Lemma \ref{lem:Inv_S}\ref{lem:Inv_S1}\ref{lem:Inv_S1b}, from \eqref{eqv:proof29}, \begin{align} & \procout {{\sf p}}{\ell_{j}}{\S_j'}{T_2'''} \leqslant \projt{\ensuremath{{\sf G}}}{{\sf q}} \label{eqv:proof33}\\ & \der{}{\ensuremath{Q}}{T_2'''} \label{eqv:proof34} \\ & \der{}{e}{\S_j} \label{eqv:proof35} \\ & \S_j' \leq\vcentcolon \S_j \end{align} By Lemma~\ref{lem:Subst_S}, from \eqref{eqv:proof32}, \eqref{eqv:proof35} and $\eval{\kf{e}}{\kf{v}},$ \begin{align} \der{}{\ensuremath{{P}}_j\sub{v}{x}}{T_j} \label{eqv:proof37} \end{align} By Lemma~\ref{lem:erase}, from \eqref{eqv:proof31} and \eqref{eqv:proof33} \begin{align} T_2''' \leqslant \projt{(\redG\ensuremath{{\sf G}}\pq{{\ell_j}}{\sf p})}{{\sf q}}{} \quad T_{j} \leqslant \projt{(\redG\ensuremath{{\sf G}}{\sf p}{{\ell_j}}\pq)}{{\sf p}}{} \quad \projt{\ensuremath{{\sf G}}}{{\sf p}_l} \leqslant \projt{(\redG\ensuremath{{\sf G}}\pq{{\ell_j}}{\sf p})}{{\sf p}_l}{}, \;l\in L \label{eqv:proof38} \end{align} By \rulename{t-sub} and \rulename{t-sess}, from \eqref{eqv:proof30}, \eqref{eqv:proof34}, \eqref{eqv:proof37} and \eqref{eqv:proof38}, \begin{align*} \der{}{M'}{\redG\ensuremath{{\sf G}}\pq{{\ell_j}}{\sf p}}. \end{align*} \item[] \rulename{default}: $M = \pa{\sf p}{\sum\limits_{i\in I} \procin{\pq}{\ell_i(x)}{\ensuremath{{P}}_i} + \motion{\dtsess}{a}{\ensuremath{{P}}}}$ and $M'= {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t}.\ensuremath{{P}}}{\sstore{X}'}{\sstore{W}'}$ with \begin{enumerate} \item\label{thm:Def_E1}% ${\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\tau} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT 0}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}}$ and \item\label{thm:Def_E2}% ${\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT 0}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}},\xi,\nu, t} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t}.\ensuremath{{P}}}{\sstore{X}'}{\sstore{W}'}$ \end{enumerate} From Item (\ref{thm:Def_E1}), by (IH) of rule \rulename{traj-base}, we have $\der{}{M_0}{\ensuremath{{\sf G}}_0}$ such that $M_0={\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT 0}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}}$ and ${\ensuremath{{\sf G}}}\Longrightarrow{\ensuremath{{\sf G}}_0}$. Similarly from Item (\ref{thm:Def_E2}), by (IH) of rule \rulename{traj-step}, we have $\der{}{M'}{\ensuremath{{\sf G}}'}$ such that ${\ensuremath{{\sf G}}_0}\Longrightarrow{\ensuremath{{\sf G}}'}$, hence ${\ensuremath{{\sf G}}}\Longrightarrow{\ensuremath{{\sf G}}'}$. \item[] \rulename{traj-base}: By Definition~\ref{def:global-type-consumption}(\ref{Item:GC41},\ref{Item:GC6}). \item[] \rulename{traj-step}: By Definition~\ref{def:global-type-consumption}(\ref{Item:GC4},\ref{Item:GC6}). \item[] \rulename{non-interrupt}: By Definition~\ref{def:global-type-consumption}(\ref{Item:GC7}.\ref{Item:GC7A},\ref{Item:GC6}). \item[] \rulename{interrupt}: By Definition~\ref{def:global-type-consumption}(\ref{Item:GC7}.\ref{Item:GC7B},\ref{Item:GC6}). \item[] $\rulename{t-conditional}$: $M= \pa{\sf p}{\cond{\kf{e}}{\ensuremath{{P}}}{\ensuremath{Q}}} \; | \; \prod\limits_{l\in L} \pa{{\sf p}_l}{\ensuremath{{P}}_l},\; M'= \pa{\sf p}\ensuremath{{P}}\; | \; \prod\limits_{l\in L} \pa{{\sf p}_l}{\ensuremath{{P}}_l},\; \eval{e}{\kf{true}}.$ \\ From $\der{}M\ensuremath{{\sf G}},$ by Lemma \ref{lem:Inv_S}\ref{lem:Inv_S2}, \begin{align} & \der{}{{\cond{\kf{e}}{\ensuremath{{P}}}{\ensuremath{Q}}}}{\projt{\ensuremath{{\sf G}}}{{\sf p}}} \label{eqv:proof39} \\ & \der{}{\ensuremath{{P}}_l}{\projt{\ensuremath{{\sf G}}}{{\sf p}_l}},\;l\in L \label{eqv:proof40} \end{align} By Lemma \ref{lem:Inv_S}\ref{lem:Inv_S1}\ref{lem:Inv_S1c}, from \eqref{eqv:proof39}, \begin{align} & \der{}{\ensuremath{{P}}}{T_1} \qquad \der{}{\ensuremath{Q}}{T_2} \label{eqv:proof41} \\ & T_1\leqslant \projt{\ensuremath{{\sf G}}}{{\sf p}} \qquad T_2\leqslant \projt{\ensuremath{{\sf G}}}{{\sf p}} \label{eqv:proof42} \end{align} By \rulename{t-sub} and \rulename{t-sess}, from \eqref{eqv:proof40}, \eqref{eqv:proof41} and \eqref{eqv:proof42}, we derive $\der{}{M'}{\ensuremath{{\sf G}}}.$ \item[] $\rulename{f-conditional}$: Similar with $\rulename{t-conditional}$. \item[] \rulename{m-par} By Definition~\ref{def:global-type-consumption}(\ref{Item:GC7}.\ref{Item:GC7B},\ref{Item:GC6}) and by (IH) from \rulename{traj-step}. \item[] \rulename{r-par} By (IH) of $M_1 \xrightarrow{\alpha}M_2$. \item[] \rulename{r-struct} Assume that the last applied rule was \rulename{r-struct}. Then, $M_1' \xrightarrow{\alpha} M_2'$ was derived from $M_1 \xrightarrow{\alpha} M_2$ where $M_1 \equiv M_1'$ and $M_2 \equiv M_2'.$ By Lemma~\ref{lem:cong}\ref{lem:congN}, from the assumption $\der{}{M_1'}{\ensuremath{{\sf G}}},$ we deduce $\der{}{M_1}{\ensuremath{{\sf G}}}.$ By induction hypothesis, $\der{}{M_2}{\ensuremath{{\sf G}}'} \text{ for some }\ensuremath{{\sf G}}' \text{ such that }\ensuremath{{\sf G}}\Longrightarrow\ensuremath{{\sf G}}'.$ By Lemma \ref{lem:cong}\ref{lem:congN}, $\der{}{M'_2}{\ensuremath{{\sf G}}'} \text{ for some }\ensuremath{{\sf G}}' \text{ such that }\ensuremath{{\sf G}}\Longrightarrow\ensuremath{{\sf G}}'.$ \end{itemize} \end{proof} \theoremPROG* \begin{proof} {\bf\em (Communication Progress)} The proof is divided into two cases: {\bf (a)} the guard appearing in the branching type followed by {\bf (b)} a message exchange between two parties; or reduces by conditional. {\bf Case (a)} follows from the fact that there is always at least one guard in a choice whose predicate is evaluated to true (Definition \ref{def:well-formed}(1)). The typing rules ensure that the predicates are satisfied when a message is sent. {\bf Case (b)} The case when $M$ contains the conditional is trivial since always $M \longrightarrow M'$. There are three main cases: \begin{itemize} \item[] $\ensuremath{{\sf G}}=\GvtPair {\sf p}{\sf q}{\ell_i(S_i).\ensuremath{{\sf G}}_i}$. Then $M \equiv \pa{\sf p}\ensuremath{{P}} \;| \pa\pq\ensuremath{Q} \;|\;M_1$ and $\der{}\ensuremath{{P}}{\oplus_{i\in I}\tout {\sf q} {\ell_i}{\S_i}.{(\projt{\ensuremath{{\sf G}}_i}{{\sf p}})} }$ and $\der{}\ensuremath{Q}{\&_{i\in I} \tin {\sf p} {\ell_i}{\S_i}.{(\projt{\ensuremath{{\sf G}}_i}{{\sf q}})}}.$ Then we have $\ensuremath{{P}} \equiv \procout {\sf q} {\ell_{j}}{\kf{e}} \ensuremath{{P}}_{j}^{{\sf p}},$ $j\in I,$ $\eval\kf{e} v,$ and $\ensuremath{Q}\equiv \sum\limits_{i\in I'} \procin{\sf p}{\ell_i(x_i)}{\ensuremath{{P}}_i^{\sf q}} \text{ and }I\subseteq I':$ $M \longrightarrow \pa{\sf p} \ \ensuremath{{P}}_{j}^{{\sf p}} \;| \; \pa\pq \ensuremath{{P}}_j^{\sf q} \sub{v}{x} \;| \; M_1,$ by \rulename{comm}. \item[] Suppose $\ensuremath{{\sf G}}= g.\ensuremath{{\sf G}}'$. \begin{itemize} \item If $g = \GvtPre{{\sf p}}{\pq}{[\mathcal{P}_i]\ell_i}{\set{\nu:\ensuremath{{\sf S}}\mid\mathcal{P}'_i}}.g'$, it is proved as the first case above. \item The case $g$ is a motion primitive is proved in ({\bf\em Motion Progress}) below. \item The case $g=g_1 + g_2$ is reduced to the first case since all branching types can be written in the form of $\GvtPair {\sf p}{\sf q}{\ell_i(S_i).\ensuremath{{\sf G}}_i}$ (see the paragraph below Definition~\ref{def:global-types}). \item Suppose $\ensuremath{{\sf G}}= (g_1 \ast g_2).\ensuremath{{\sf G}}'$. Then by Definition~\ref{def:projection} and the fully separated condition of the well-formedness, if ${\sf p} \in g_1$, then ${\sf p} \not\in g_1$. Suppose $g_1 = \GvtPre{{\sf p}}{\pq}{[\mathcal{P}_i]\ell_i}{\set{\nu:\ensuremath{{\sf S}}\mid\mathcal{P}'_i}}.g_i'$. Then $M \equiv \pa{\sf p}\ensuremath{{P}} \;| \pa\pq\ensuremath{Q} \;|\;M_1$ and $\der{}\ensuremath{{P}}{\oplus_{i\in I}\tout {\sf q} {\ell_i}{\S_i}.{(\projt{\ensuremath{{\sf G}}_i}{{\sf p}})} }$ and $\der{}\ensuremath{Q}{\&_{i\in I} \tin {\sf p} {\ell_i}{\S_i}.{(\projt{\ensuremath{{\sf G}}_i}{{\sf q}})}}.$ Thus this case is the same as $\ensuremath{{\sf G}}=\GvtPair {\sf p}{\sf q}{\ell_i(S_i).\ensuremath{{\sf G}}_i}$ above. When $g_i$ is a motion primitive is proved in ({\bf\em Motion Progress}) below. \end{itemize} \item The case $\ensuremath{{\sf G}}= \mu \mathbf{t}.\ensuremath{{\sf G}}'$. Since $\ensuremath{{\sf G}}=\ensuremath{{\sf G}}'\sub{\mu \mathbf{t}.\ensuremath{{\sf G}}'}{\mathbf{t}}$, the case reduces to one of the above. \end{itemize} {\bf\em (Motion Progress)} For executing motions, Definition~\ref{def:well-formed}(3) and Theorem~\ref{th:motion-compat} ensure local trajectories can be composed into global trajectories. Suppose $\ensuremath{{\sf G}}=g.\ensuremath{{\sf G}}'$. \begin{itemize} \item Suppose $g = \motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}$. In this case, we have: $M=\prod_{i \in I} {\sf p}_i\ensuremath{\triangleleft{}}\proc{P_i}{\sstore{X}_i}{\sstore{W}_i}$. and we can write $P_i=\motion{\dtsess}{\ensuremath{\mathit{a}}_i\AT t_i}.P_i'$. By Definition~\ref{def:well-formed}(3) and Theorem~\ref{th:motion-compat}, we know $i\neq j \Rightarrow \mathsf{disjoint}(\ensuremath{\mathit{a}}_i,\ensuremath{\mathit{a}}_j)$. Hence by \rulename{M-Par}, we obtain $M \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}_i}, t} M'$, as required. \item The case $g = g_1\ast g_2$. If one of them is a branching, it is reduced to {\bf\em (Communication Progress)} proved above. Hence w.o.l.g., we can assume $g = g_1\ast g_2 \ast\cdots \ast g_n$ and $g_i = \motion{\dtsess}{{\sf p}_i:\ensuremath{\mathit{a}}_i}$. By the fully separation condition and Definition~\ref{def:well-formed}(3), this case is similar with the case above. \end{itemize} {\bf\em (Collision-free Progress)} By induction, following the same structure as {\bf\em (Motion Progress)}. \begin{itemize} \item The base case is given by $I$ and by \rulename{t-sess} which guarantees that $M$ is initially collision free. \item For the communication ($\GvtPair {\sf p}{\sf q}{\ell_i(S_i).\ensuremath{{\sf G}}_i}$), note that it does not change the physical state, and therefore, does not impact the geometric footprint used by a process. Hence, the case $\redG \ensuremath{{\sf G}}{\sf p}\ell\pq$ is straightforward. \item For motion actions ($\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}$), Definition~\ref{def:well-formed}(3) and Theorem~\ref{th:motion-compat} ensures collision freedom through execution steps. Therefore, after the corresponding reduction $M \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}_i}, t} M'$, $M'$ is also collision free. \item For the separation ($g_1\ast g_2$), Definition~\ref{def:well-formed}(2) enforces that the two parts are fully separated and the induction hypothesis means each subpart is collision-free. Therefore, the overall system is collision-free. \item The remaining cases are bookkeeping rules, e.g., inserting $@t$ or removing fully consumed motions, similar to the communication these rules do not change the physical state, and therefore, preserve collision freedom. \end{itemize} \end{proof} \begin{comment} \begin{figure*}[t] { \small \begin{align*} \mu \mathbf{t}. & {\color{roleColor}{\mathsf{Cart}}} \to {\color{roleColor}{\mathsf{Prod}}}: \mathit{arrive}. {\color{roleColor}{\mathsf{Cart}}}\to {\color{roleColor}{\mathsf{GRobot}}}: \mathit{start}.{\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{RRobot}}}:\mathit{start}.\\ & \left( \begin{array}{ccc} \left( \begin{array}{l} (\motion{\dtsess}{\tuple{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_move}^{\mathsf{\rightsquigarrow}}({\color{roleColor}{\mathsf{Prod}}}), {\color{roleColor}{\mathsf{Prod}}}:\mathsf{work}^{\mathsf{\lightning}}}}^{\color{roleColor}{\mathsf{Cart}}}.\\ {\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{Prod}}}:\mathit{ready}.\motion{\dtsess}{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_idle}^{\mathsf{\lightning}},{\color{roleColor}{\mathsf{Prod}}}:\mathsf{place}^{\mathsf{\rightsquigarrow}}})^{\color{roleColor}{\mathsf{Prod}}}. \end{array} \right) & ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{RRobot}}}: \mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Prod}}} & ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{GRobot}}}: \mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Prod}}} \end{array} \right).\\ & \left( \begin{array}{l} \big\{ {\color{roleColor}{\mathsf{Prod}}} \to{\color{roleColor}{\mathsf{Cart}}}:\mathit{green}. \\ \quad \quad \left( \begin{array}{cc} \motion{\dtsess}{{\color{roleColor}{\mathsf{Prod}}}:\mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Cart}}}) ~\ensuremath{\ast}~ & \left( \begin{array}{l} {\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{GRobot}}}:\mathit{arrive}.{\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{RRobot}}}:\mathit{free}. \\ \left(\begin{array}{cc} \left( \begin{array}{l} \motion{\dtsess}{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_move}^{\mathsf{\rightsquigarrow}}({\color{roleColor}{\mathsf{GRobot}}}),{\color{roleColor}{\mathsf{GRobot}}}:\mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Cart}}}.\\ {\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{GRobot}}}:\mathit{ready}.\\ \motion{\dtsess}{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_idle}^{\mathsf{\lightning}},{\color{roleColor}{\mathsf{GRobot}}}:\mathsf{pick}^{\mathsf{\rightsquigarrow}}}^{\color{roleColor}{\mathsf{GRobot}}}.\\ {\color{roleColor}{\mathsf{GRobot}}}\to{\color{roleColor}{\mathsf{Cart}}}:\mathit{ok} \end{array} \right) & ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{RRobot}}}:\mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Cart}}} \end{array}\right) \end{array} \right) \end{array} \right) \big\} \\ + \big\{ {\color{roleColor}{\mathsf{Prod}}}\to{\color{roleColor}{\mathsf{Cart}}}:\mathit{red}. (\motion{\dtsess}{{\color{roleColor}{\mathsf{Prod}}}:\mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Cart}}}) ~\ensuremath{\ast}~ \text{\quad as the above replacing ${\color{roleColor}{\mathsf{GRobot}}}$ by ${\color{roleColor}{\mathsf{RRobot}}}$\quad } ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{GRobot}}}:\mathsf{work}^{\mathsf{\lightning}}}) \big\} \end{array} \right).\mathbf{t} \end{align*} } \vspace{-3mm} \caption{Motion session type annotated with minimal senders\label{fig:annotated-global-session-type}} \end{figure*} \end{comment} \section{Introduction} \label{sec:intro} Modern robotics applications are often deployed in safety- or business-critical applications and formal specifications and reasoning about their correct behaviours is a difficult and challenging problem. These applications tightly integrate computation, communication, control of physical dynamics, and geometric reasoning. Developing programming models and frameworks for such applications has been long noted as an important and challenging problem in robotics \cite{Lozano-Perez}, and yet very little support exists today for compositional specification of behaviours or their static enforcement. In this paper, we present a programming model for concurrent robotic systems and a type-based approach to statically analyse programs. Our programming model uses \emph{choreographies}---global protocols which allow implementing distributed and concurrent components without a central control---to compositionally specify and statically verify both message-based communications and jointly executed motion between robotics components in the physical world. Our choreographies extend \emph{multiparty session types} \cite{HYC08} with \emph{dynamic motion primitives}, which represent pre-verified motions that the robots can execute in the physical world. We compile well-typed programs into robotics platforms. We show through a number of nontrivial usecases how our programming model can be used to design and implement correct-by-construction, complex, robotic applications on top of commercial and custom-build robotic hardware. Our starting point is the theory of motion session types \cite{ECOOP19}, which forms a type discipline based on global types with simple, discrete-time motion primitives. For many applications, we found this existing model too restrictive: it requires that all components agree on a pre-determined, global, discrete clock and it forces \emph{global synchronisation} among all robots at the fixed interval determined by the ``tick'' of the global clock. For example, two robots engaged in independent activities in different parts of a workspace must nevertheless stop their motion and synchronise every tick. This leads to communication-heavy programs in which the programmer must either pick a global clock that ensures every motion primitive can finish within one tick (making the system very slow) or that every motion primitive is interruptible (all robots stop every tick and coordinate). Our new model enhances the scope and applicability of motion sesstion types to robots: we go from the global and discrete clock to \emph{continuous behaviours} over time, allowing complex synchronisations as well as \emph{frame separation} between independent subgroups of robots. That is, the programmer does not need to think about global ticks when writing the program. Instead, they think in terms of motion primitives and the type system enforces that concurrent composition of motions is well-formed and that trajectories exist in a global timeline. Reasoning simultaneously about dynamics and message-based synchronisation is difficult because time is global and can be used as an implicit broadcast synchronisation mechanism. The complexity of our model arises from the need to ensure that every component is simultaneously ready to let time progress (through dynamics) or ready to send or receive messages (property \emph{communication safety}). At the same time, we must ensure that systems are able to correctly execute motion primitives (property \emph{motion compatibility}); and jointly executed trajectories are separated in space and time (property \emph{collision freedom}). Our verification technique is \emph{static}: if a program type checks, then every execution of the system satisfies communication safety, motion compatibility, and collision freedom. We manage the complexity of reasoning about the interplay between dynamics and concurrency through a separation of concerns. First, we specify \emph{continuous-time trajectories} as \emph{motion primitives}. Since the dynamics of different components can be coupled, the proof system uses an \emph{assume-guarantee proof system} \cite{AbadiLamport93,ChandyMisra88,Jones83,DBLP:journals/pieee/NuzzoSBGV15} on continuous time processes to relate an abstract motion primitive to the original dynamics. The assume guarantee contracts decouple the dynamics. Additionally, the proof system also checks that trajectories ensure disjointness of the use of geometric space over time. Second, we interpret choreographic specifications in continuous time, and extend the existing formalism in \cite{ECOOP19} with \emph{predicate refinements}---to reason about permissions (i.e., what parts of the state space an individual robot can access without colliding into a different robot). This is required for motion compatibility and collision freedom. We also introduce a \emph{separating conjunction} operator to reason about disjoint frames. The combination of message passing and dynamics makes static verification challenging. We introduce a notion of \emph{well-formedness} of choreographies that ensures motion and communication can be synchronised and disallows, e.g., behaviours when a message is blocked because a motion cannot be interrupted. We give an algorithm for checking well-formedness using a dataflow analysis on choreographies. We show that well-formed types can be projected on to end-components and provide a local type checking that allows refinement between motion primitives. % Checking compatibility and collision freedom reduces to validity queries in the underlying logic. Interestingly, the separating conjunction allows subgroups of robots to interact---through motion and messages---disjointly from other subgroups; this reduces the need for global communication in our implementations. We compile well-typed programs into programs in the PGCD \cite{PGCD} and ROS \cite{ROS} frameworks. We have used our implementation to program and verify a number of complex robotic coordination and manipulation tasks. Our implementation uses both commercial platforms (e.g., the Panda 7DOF manipulator, the BCN3D MOVEO arm) and custom-built components (mobile carts). In our experience, our programming model and typing discipline are sufficient to specify quite complex manoeuvres between multiple robots and to obtain verified implementations. Moreover, the use of choreographies and the separating conjunction are crucial in reducing verification effort: without the separating conjunction, verification times out on more complex examples. Our implementation uses SMT solvers to discharge validity queries arising out of the proof system; our initial experience suggests that while the underlying theories (non-linear arithmetic) are complex, it is possible to semi-automatically prove quite involved specifications. \paragraph{\bf Contributions and Outline} This paper provides a static compositional modelling, verification, and implementation framework through behavioural specifications for concurrent robotics applications that involve reasoning about message passing, continuous control, and geometric separation. We manage this complexity by decoupling dynamics and message passing and enables us to specify and implement robotic applications on top of commercial and custom-build robotic hardware. Our framework coherently integrates programming languages techniques, session type theories, and static analysis techniques; this enables us to model \emph{continuous behaviours} over time in the presence of complex synchronisations between independent subgroups of robots. We extend the global types in \cite{ECOOP19} to \emph{choreographies} including key constructs such as framing and predicate refinements, together with separation conjunctions, and integrate the typing system with an assume-guarantee proof system. We implement our verification system using a new set of robots (extending \cite{ECOOP19,PGCD}) in order to program and verify complex coordinations and manipulation tasks. The rest of the paper is organised as follows. \begin{description} \item[\underline{\sc{Sec.}~\ref{sec:example}}:] We first motivate our design for robotics specifications, and explain the correctness criteria -- \emph{communication safety}, \emph{motion compatibility}, and \emph{collision freedom} with an example. \item[\underline{\sc{Sec.}~\ref{sec:calculus}:}] We introduce a \emph{multiparty motion session calculus} with \emph{dynamic abstract motion primitives}; we provide an assume guarantee proof system to construct abstract motion primitives for maintaining geometric separation in space and time for concurrently executed motion primitives. We then prove Theorem~\ref{th:motion-compat} (\emph{Motion Compatibility}). \item[\underline{\sc{Sec.}~\ref{sec:proof-system}:}] We provide \emph{choreographic specifications} enriched with dynamic motion primitives and separation operator, and define their dataflow analysis. We propose a typing system and prove its main properties, Theorem~\ref{th:SR} (\emph{Subject Reduction}), Theorem~\ref{th:progress} (\emph{Communication and Motion Progress} and \emph{Collision-free Progress}). \item[\underline{\sc{Sec.}~\ref{sec:eval}:}] We describe our implementation, evaluation, and case studies. Our evaluation demonstrates that our framework allows specifying complex interactions and verifying examples beyond the scope of previous work. \item[\underline{\sc{Sec.}~\ref{sec:related} and {Sec.}~\ref{sec:discussion}:}] We discuss related work and conclude with a number of open challenges in reasoning about robotics applications. \end{description} Putting it all together, we obtain a compositional specification and implementation framework for concurrent robotics applications. Our paper is a starting point rather than the final word on robot programming. Indeed, we make many simplifying assumptions about world modeling, sensing and filtering, and (distributed) feedback control and planning. Even with these simplifications, the theoretical development is non-trivial. With a firm understanding of the basic theory, we hope that future work will lift many of the current limitations. \begin{comment} We expand the example in Figure~\ref{fig:cart-crane} and motivate the constructions in our language in {Sec.}~\ref{sec:example}. {Sec.}~\ref{sec:lang} defines a core language for robotic interactions and its operational semantics. Sections~\ref{sec:motion} and~\ref{sec:proof-system} build our proof system: first, by constructing abstract motion primitives from programs and then by incorporating them into a multiparty motion session type system. We discuss related work in {Sec.}~\ref{sec:related} and conclude with future work in {Sec.}~\ref{sec:conclusion}. \RMi{OLD:} In this paper, we provide a compositional proof system for robotics applications. To understand the capabilities such a proof system must provide, let us consider a simple example of a cart and crane assembly transporting a mass from a trolley (Figure~\ref{fig:cart-crane}). The cart assembly rolls on horizontal tracks and has a motor that produces a horizontal force. The crane consists of a winch with a cable that can be used to hoist a load. The combination of the cart and the crane can transport a load from some initial position to another; the cart communicates with a trolley to find the initial position for the load and to inform it when the load is picked up. Figure~\ref{fig:cart-crane}(a) shows the schematic of the system. The task of transporting the load from the trolley requires several steps and involve synchronisation between the software running on each component and joint execution of trajectories in space such that there is no collision. In more detail, a possible protocol for the task is as follows (see Figure~\ref{fig:cart-crane}(b) to see the visual flow of messages and control actions). Initially, we assume that the cart is at rest. First, the trolley sends a message giving the initial position of the load to the cart and remains at rest at that location. The cart sends a message to the crane to roll up its cable. This is to ensure the cable does not swing around (and hit objects in the workspace) while the cart moves to the load as well as to remove a drag due to the cable. While the cart remains stationary, the crane rolls its cable. When it is done, the crane sends an acknowledgement to the cart. At this point, the cart executes a motion primitive to move it on top of the load to be transported. In the meantime, the crane remains idle. Once the cart is on top of the load and stationary, it sends the crane a message to unroll the cable up to the position of the load and to grip the load. This involves the crane executing a motion primitive to unroll the cable, grab the object, and roll it up again. When this action is done, the crane synchronises with the cart. At this point, the cart confirms the pickup with the trolley and the protocol is over. In summary, a correct implementation of the task requires coordination and planning at the discrete level and executing trajectories at the continuous level, while ensuring components do not collide. Formally reasoning about such interaction between planning and control involves a number of challenges. Since the system is \emph{concurrent} and synchronises through \emph{message passing}, formal reasoning inherits the complexities of concurrent systems. Since the components control physical state in continuous space and time, and the dynamics of these states are coupled, reasoning inherits the complexities of continuous control systems and hybrid systems. Finally, since components reside in geometric space and must be collision-free, formal reasoning must consider the use of geometric space by components over time as well as reference frame transformations between components. There are many languages to model and implement robotics applications---from general purpose languages like C++ or Python on top of libraries such as ROS to domain-specific languages \cite{Nordmann2016survey} and to generic modelling languages such as Simulink or Modelica. They usually provide features for concurrency, dynamics, and geometric reasoning but little support for compositional reasoning. Typically, verification support is limited to testing/simulation or global model checking. On the other hand, models and verification tools from formal methods typically support a subset of these features. For example, \emph{hybrid automata} \cite{ACHH,Henzinger96} support continuous dynamics but little support for compositional reasoning about concurrency and geometry. \emph{Session types} \cite{THK,HKV98} support modular specifications and type-checking about message-passing but not continuous dynamics. \emph{Program logics} \cite{AptBO09,DBLP:conf/lics/Reynolds02,DBLP:conf/lics/CalcagnoOY07} support compositional reasoning about concurrency but do not support continuous dynamics or geometric reasoning. Our contribution is a compositional proof system based on session types to reason about robotics applications with support for dynamics, concurrency, and geometry. Our starting point is \textsf{PGCD}\xspace \cite{PGCD}, a recent ``core'' language for robotics applications. We extend \textsf{PGCD}\xspace with explicit support for dynamics in the language (the original papers \cite{PGCD,ECOOP19} either abstracted away the dynamics or used a discrete-time semantics) and provide an operational semantics for \textsf{PGCD}\xspace programs. One nontrivial feature of our operational semantics is the use of nonstandard models of reals to give a uniform semantics to both continuous and discrete evolution of the system as a sequence of infinitesimally small discrete steps. Reasoning about dynamics and message-based synchronisation is difficult because time is global in the system. Thus, our proof system has to ensure that every component is simultaneously ready to let time progress (through dynamics). Similarly, we must ensure that such jointly executed trajectories are separated in space and time. We manage the complexity of this reasoning through a separation of concerns. First, we abstract the original continuous-time trajectories into \emph{abstract motion primitives}. Since the dynamics of different components can be coupled, the proof system uses assume guarantee reasoning. Precisely, we use an \emph{assume-guarantee proof system} \cite{AbadiLamport93,ChandyMisra88,Jones83} on continuous time processes to relate an abstract motion primitive to the original dynamics. Our proof system uses the assume guarantee contracts to decouple the dynamics. Additionally, it also checks that trajectories ensure disjointness of the use of geometric space over time. Second, we use \emph{multiparty session types} \cite{HYC2016} over abstract motion primitives \cite{ECOOP19} as the basis for reasoning about global sequences of messages and motions. The global specification is written as a global type, which extends existing session typing systems with \emph{predicate refinements} and motion primitives connected by separating conjunction. A global type is projected onto each component to generate a local type for each component. Our soundness result states that if each component refines its local type, then the composition of the system satisfies the global type. The combination of message passing and dynamics makes static type checking challenging but our subtyping relations, which relate structured concurrency with motion, enable us to handle this complexity. In summary, we provide the first compositional reasoning framework for robotics applications that involve reasoning about concurrent message passing, continuous control, and geometric separation. Our framework manages the complexity of reasoning by decoupling dynamics and message passing. For the dynamics, we provide an assume guarantee proof system to construct abstract motion primitives. For concurrency, we define a multiparty motion session type system, which uses motion primitives as abstract actions, to specify valid sequences. We show how an implementation of a component can be type checked against the local type obtained by projecting the multiparty session type onto the component. Along the way, our proof systems maintain geometric separation in space and time for concurrently executed motion primitives. Putting it all together, we obtain a fully compositional framework for reasoning with complex, distributed robotics applications that goes significantly beyond the scope of existing techniques. The rest of the paper is organised as follows. We expand the example in Figure~\ref{fig:cart-crane} and motivate the constructions in our language in {Sec.}~\ref{sec:example}. {Sec.}~\ref{sec:lang} defines a core language for robotic interactions and its operational semantics. Sections~\ref{sec:motion} and~\ref{sec:proof-system} build our proof system: first, by constructing abstract motion primitives from programs and then by incorporating them into a multiparty motion session type system. We discuss related work in {Sec.}~\ref{sec:related} and conclude with future work in {Sec.}~\ref{sec:conclusion}. \end{comment} \begin{figure}[t] \hspace*{-1.5cm} \begin{minipage}{0.45\linewidth} \tikzset {_mwlgzwu4u/.code = {\pgfsetadditionalshadetransform{ \pgftransformshift{\pgfpoint{89.1 bp } { -108.9 bp } } \pgftransformscale{1.32 } }}} \pgfdeclareradialshading{_4euyx15e0}{\pgfpoint{-72bp}{88bp}}{rgb(0bp)=(1,1,1); rgb(0bp)=(1,1,1); rgb(25bp)=(0,0,0); rgb(400bp)=(0,0,0)} \tikzset {_7ai0opi17/.code = {\pgfsetadditionalshadetransform{ \pgftransformshift{\pgfpoint{89.1 bp } { -108.9 bp } } \pgftransformscale{1.32 } }}} \pgfdeclareradialshading{_co9gpcsuk}{\pgfpoint{-72bp}{88bp}}{rgb(0bp)=(1,1,1); rgb(0bp)=(1,1,1); rgb(25bp)=(0,0,0); rgb(400bp)=(0,0,0)} \tikzset {_eoe8gdy8h/.code = {\pgfsetadditionalshadetransform{ \pgftransformshift{\pgfpoint{89.1 bp } { -108.9 bp } } \pgftransformscale{1.32 } }}} \pgfdeclareradialshading{_dhd3hjkey}{\pgfpoint{-72bp}{88bp}}{rgb(0bp)=(1,1,1); rgb(0bp)=(1,1,1); rgb(25bp)=(0,0,0); rgb(400bp)=(0,0,0)} \tikzset {_cis49r535/.code = {\pgfsetadditionalshadetransform{ \pgftransformshift{\pgfpoint{89.1 bp } { -108.9 bp } } \pgftransformscale{1.32 } }}} \pgfdeclareradialshading{_9wx7ylssl}{\pgfpoint{-72bp}{88bp}}{rgb(0bp)=(1,1,1); rgb(0bp)=(1,1,1); rgb(25bp)=(0,0,0); rgb(400bp)=(0,0,0)} \tikzset{every picture/.style={line width=0.75pt}} % \begin{tikzpicture}[x=0.75pt,y=0.75pt,yscale=-0.6,xscale=0.6] \draw (177,145) -- (400.5,146) ; \draw (256.5,128) -- (318.5,128) -- (318.5,138) -- (256.5,138) -- cycle ; \draw [fill={rgb, 255:red, 255; green, 255; blue, 255 } ,fill opacity=1 ] (263.5,138.5) .. controls (263.5,134.08) and (267.08,130.5) .. (271.5,130.5) .. controls (275.92,130.5) and (279.5,134.08) .. (279.5,138.5) .. controls (279.5,142.92) and (275.92,146.5) .. (271.5,146.5) .. controls (267.08,146.5) and (263.5,142.92) .. (263.5,138.5) -- cycle ; \draw [fill={rgb, 255:red, 255; green, 255; blue, 255 } ,fill opacity=1 ] (296.5,139) .. controls (296.5,134.44) and (300.19,130.75) .. (304.75,130.75) .. controls (309.31,130.75) and (313,134.44) .. (313,139) .. controls (313,143.56) and (309.31,147.25) .. (304.75,147.25) .. controls (300.19,147.25) and (296.5,143.56) .. (296.5,139) -- cycle ; \draw (434,146) -- (428,126) -- (403.74,126) -- (397.74,146) -- cycle ; \path [shading=_4euyx15e0,_mwlgzwu4u] (419.45,126.5) .. controls (419.45,124.22) and (417.85,122.37) .. (415.87,122.37) .. controls (413.89,122.37) and (412.29,124.22) .. (412.29,126.5) .. controls (412.29,128.78) and (413.89,130.63) .. (415.87,130.63) .. controls (417.85,130.63) and (419.45,128.78) .. (419.45,126.5)(424.81,126.5) .. controls (424.81,121.25) and (420.81,117) .. (415.87,117) .. controls (410.93,117) and (406.93,121.25) .. (406.93,126.5) .. controls (406.93,131.75) and (410.93,136) .. (415.87,136) .. controls (420.81,136) and (424.81,131.75) .. (424.81,126.5) ; % \draw (419.45,126.5) .. controls (419.45,124.22) and (417.85,122.37) .. (415.87,122.37) .. controls (413.89,122.37) and (412.29,124.22) .. (412.29,126.5) .. controls (412.29,128.78) and (413.89,130.63) .. (415.87,130.63) .. controls (417.85,130.63) and (419.45,128.78) .. (419.45,126.5)(424.81,126.5) .. controls (424.81,121.25) and (420.81,117) .. (415.87,117) .. controls (410.93,117) and (406.93,121.25) .. (406.93,126.5) .. controls (406.93,131.75) and (410.93,136) .. (415.87,136) .. controls (420.81,136) and (424.81,131.75) .. (424.81,126.5) ; % \path [shading=_co9gpcsuk,_7ai0opi17] (394.31,101.5) .. controls (394.31,99.22) and (392.71,97.37) .. (390.73,97.37) .. controls (388.75,97.37) and (387.15,99.22) .. (387.15,101.5) .. controls (387.15,103.78) and (388.75,105.63) .. (390.73,105.63) .. controls (392.71,105.63) and (394.31,103.78) .. (394.31,101.5)(399.67,101.5) .. controls (399.67,96.25) and (395.67,92) .. (390.73,92) .. controls (385.79,92) and (381.78,96.25) .. (381.78,101.5) .. controls (381.78,106.75) and (385.79,111) .. (390.73,111) .. controls (395.67,111) and (399.67,106.75) .. (399.67,101.5) ; % \draw (394.31,101.5) .. controls (394.31,99.22) and (392.71,97.37) .. (390.73,97.37) .. controls (388.75,97.37) and (387.15,99.22) .. (387.15,101.5) .. controls (387.15,103.78) and (388.75,105.63) .. (390.73,105.63) .. controls (392.71,105.63) and (394.31,103.78) .. (394.31,101.5)(399.67,101.5) .. controls (399.67,96.25) and (395.67,92) .. (390.73,92) .. controls (385.79,92) and (381.78,96.25) .. (381.78,101.5) .. controls (381.78,106.75) and (385.79,111) .. (390.73,111) .. controls (395.67,111) and (399.67,106.75) .. (399.67,101.5) ; % \draw [line width=2.25] (415.87,117) -- (399.67,101.5) ; \draw [line width=2.25] (406.93,126.5) -- (390.73,111) ; \draw [line width=2.25] (385.17,95) -- (366.8,102) ; \draw [line width=2.25] (383.24,108) -- (368.73,112) ; \draw (365.83,97) -- (370.67,117) ; \draw [fill={rgb, 255:red, 0; green, 0; blue, 0 } ,fill opacity=1 ] (357.5,102.59) -- (365.53,98.71) -- (366.35,102.1) -- cycle ; \draw [fill={rgb, 255:red, 0; green, 0; blue, 0 } ,fill opacity=1 ] (360.4,116.59) -- (368.43,112.71) -- (369.25,116.1) -- cycle ; \draw (139.5,145) -- (145.5,125) -- (171.1,125) -- (177.1,145) -- cycle ; \path [shading=_dhd3hjkey,_eoe8gdy8h] (154.59,125.5) .. controls (154.59,123.33) and (156.25,121.57) .. (158.3,121.57) .. controls (160.35,121.57) and (162.01,123.33) .. (162.01,125.5) .. controls (162.01,127.67) and (160.35,129.43) .. (158.3,129.43) .. controls (156.25,129.43) and (154.59,127.67) .. (154.59,125.5)(149.03,125.5) .. controls (149.03,120.25) and (153.18,116) .. (158.3,116) .. controls (163.42,116) and (167.58,120.25) .. (167.58,125.5) .. controls (167.58,130.75) and (163.42,135) .. (158.3,135) .. controls (153.18,135) and (149.03,130.75) .. (149.03,125.5) ; % \draw (154.59,125.5) .. controls (154.59,123.33) and (156.25,121.57) .. (158.3,121.57) .. controls (160.35,121.57) and (162.01,123.33) .. (162.01,125.5) .. controls (162.01,127.67) and (160.35,129.43) .. (158.3,129.43) .. controls (156.25,129.43) and (154.59,127.67) .. (154.59,125.5)(149.03,125.5) .. controls (149.03,120.25) and (153.18,116) .. (158.3,116) .. controls (163.42,116) and (167.58,120.25) .. (167.58,125.5) .. controls (167.58,130.75) and (163.42,135) .. (158.3,135) .. controls (153.18,135) and (149.03,130.75) .. (149.03,125.5) ; % \path [shading=_9wx7ylssl,_cis49r535] (180.66,100.5) .. controls (180.66,98.33) and (182.32,96.57) .. (184.37,96.57) .. controls (186.42,96.57) and (188.08,98.33) .. (188.08,100.5) .. controls (188.08,102.67) and (186.42,104.43) .. (184.37,104.43) .. controls (182.32,104.43) and (180.66,102.67) .. (180.66,100.5)(175.1,100.5) .. controls (175.1,95.25) and (179.25,91) .. (184.37,91) .. controls (189.5,91) and (193.65,95.25) .. (193.65,100.5) .. controls (193.65,105.75) and (189.5,110) .. (184.37,110) .. controls (179.25,110) and (175.1,105.75) .. (175.1,100.5) ; % \draw (180.66,100.5) .. controls (180.66,98.33) and (182.32,96.57) .. (184.37,96.57) .. controls (186.42,96.57) and (188.08,98.33) .. (188.08,100.5) .. controls (188.08,102.67) and (186.42,104.43) .. (184.37,104.43) .. controls (182.32,104.43) and (180.66,102.67) .. (180.66,100.5)(175.1,100.5) .. controls (175.1,95.25) and (179.25,91) .. (184.37,91) .. controls (189.5,91) and (193.65,95.25) .. (193.65,100.5) .. controls (193.65,105.75) and (189.5,110) .. (184.37,110) .. controls (179.25,110) and (175.1,105.75) .. (175.1,100.5) ; % \draw [line width=2.25] (158.3,116) -- (175.1,100.5) ; \draw [line width=2.25] (167.58,125.5) -- (184.37,110) ; \draw [line width=2.25] (190.14,94) -- (209.19,101) ; \draw [line width=2.25] (192.14,107) -- (207.19,111) ; \draw (210.19,96) -- (205.18,116) ; \draw [fill={rgb, 255:red, 0; green, 0; blue, 0 } ,fill opacity=1 ] (218.83,101.59) -- (210.51,97.71) -- (209.65,101.11) -- cycle ; \draw [fill={rgb, 255:red, 0; green, 0; blue, 0 } ,fill opacity=1 ] (215.82,115.59) -- (207.5,111.71) -- (206.64,115.11) -- cycle ; \draw [fill={rgb, 255:red, 126; green, 211; blue, 33 } ,fill opacity=1 ] (446.74,133.54) -- (458.24,133.54) -- (458.24,143.54) -- (446.74,143.54) -- cycle ; \draw [fill={rgb, 255:red, 126; green, 211; blue, 33 } ,fill opacity=1 ] (451.24,123.54) -- (462.74,123.54) -- (462.74,133.54) -- (451.24,133.54) -- cycle ; \draw [fill={rgb, 255:red, 126; green, 211; blue, 33 } ,fill opacity=1 ] (458.24,133.54) -- (469.74,133.54) -- (469.74,143.54) -- (458.24,143.54) -- cycle ; \draw [fill={rgb, 255:red, 208; green, 2; blue, 27 } ,fill opacity=1 ] (128.35,133) -- (116.43,133) -- (116.43,143) -- (128.35,143) -- cycle ; \draw [fill={rgb, 255:red, 208; green, 2; blue, 27 } ,fill opacity=1 ] (116.43,133) -- (104.5,133) -- (104.5,143) -- (116.43,143) -- cycle ; \draw [fill={rgb, 255:red, 208; green, 2; blue, 27 } ,fill opacity=1 ] (122.13,122) -- (110.2,122) -- (110.2,132) -- (122.13,132) -- cycle ; \draw [fill={rgb, 255:red, 126; green, 211; blue, 33 } ,fill opacity=1 ] (281.74,117.54) -- (293.24,117.54) -- (293.24,127.54) -- (281.74,127.54) -- cycle ; \draw (247.5,107.5) -- (256.3,101) -- (256.3,104.25) -- (269.5,104.25) -- (269.5,110.75) -- (256.3,110.75) -- (256.3,114) -- cycle ; \draw (328.49,107.16) -- (319.88,113.94) -- (319.79,110.67) -- (306.59,111.04) -- (306.41,104.52) -- (319.61,104.15) -- (319.51,100.88) -- cycle ; \draw (405,157) node [align=left] {$\displaystyle \mathsf{GRobot}$}; \draw (292,157) node [align=left] {$\displaystyle \mathsf{Cart}$}; \draw (158,157) node [align=left] {$\displaystyle \mathsf{RRobot}$}; \end{tikzpicture} \includegraphics[width=0.9\linewidth]{example.png} \end{minipage} \begin{minipage}[c]{0.40\linewidth} \tikzset{every picture/.style={line width=0.75pt}} % \begin{tikzpicture}[x=0.75pt,y=0.75pt,yscale=-0.6,xscale=1] \draw [line width=2.25] (200.97,24.47) -- (198.46,300) ; \draw [shift={(198.42,304)}, rotate = 270.52] [color={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=2.25] (17.49,-5.26) .. controls (11.12,-2.23) and (5.29,-0.48) .. (0,0) .. controls (5.29,0.48) and (11.12,2.23) .. (17.49,5.26) ; \draw [line width=2.25] (310.21,25.97) -- (307.69,298.49) ; \draw [shift={(307.66,302.49)}, rotate = 270.53] [color={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=2.25] (17.49,-5.26) .. controls (11.12,-2.23) and (5.29,-0.48) .. (0,0) .. controls (5.29,0.48) and (11.12,2.23) .. (17.49,5.26) ; \draw [fill={rgb, 255:red, 238; green, 10; blue, 10 } ,fill opacity=1 ] (193.32,76.46) -- (205.57,76.46) -- (205.57,144.27) -- (193.32,144.27) -- cycle ; \draw [fill={rgb, 255:red, 184; green, 233; blue, 134 } ,fill opacity=1 ] (205.57,154.82) -- (194.34,154.82) -- (194.34,206.8) -- (205.57,206.8) -- cycle ; \draw [line width=2.25] (403.11,25.22) -- (400.6,297.74) ; \draw [shift={(400.56,301.74)}, rotate = 270.53] [color={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=2.25] (17.49,-5.26) .. controls (11.12,-2.23) and (5.29,-0.48) .. (0,0) .. controls (5.29,0.48) and (11.12,2.23) .. (17.49,5.26) ; \draw [fill={rgb, 255:red, 30; green, 211; blue, 231 } ,fill opacity=1 ] (315.82,78.72) -- (303.57,78.72) -- (303.57,145.77) -- (315.82,145.77) -- cycle ; \draw (200.46,51.59) -- (307.7,59.73) ; \draw [shift={(309.7,59.88)}, rotate = 184.34] [color={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=0.75] (10.93,-3.29) .. controls (6.95,-1.4) and (3.31,-0.3) .. (0,0) .. controls (3.31,0.3) and (6.95,1.4) .. (10.93,3.29) ; \draw (200.46,62.14) -- (402.65,77.06) ; \draw [shift={(404.64,77.21)}, rotate = 184.22] [color={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=0.75] (10.93,-3.29) .. controls (6.95,-1.4) and (3.31,-0.3) .. (0,0) .. controls (3.31,0.3) and (6.95,1.4) .. (10.93,3.29) ; \draw (201.48,144.27) -- (308.73,152.4) ; \draw [shift={(310.72,152.55)}, rotate = 184.34] [color={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=0.75] (10.93,-3.29) .. controls (6.95,-1.4) and (3.31,-0.3) .. (0,0) .. controls (3.31,0.3) and (6.95,1.4) .. (10.93,3.29) ; \draw [fill={rgb, 255:red, 65; green, 117; blue, 5 } ,fill opacity=1 ] (314.8,155.57) -- (303.57,155.57) -- (303.57,207.56) -- (314.8,207.56) -- cycle ; \draw (309.7,209.06) -- (200.41,220.9) ; \draw [shift={(198.42,221.12)}, rotate = 353.82] [color={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=0.75] (10.93,-3.29) .. controls (6.95,-1.4) and (3.31,-0.3) .. (0,0) .. controls (3.31,0.3) and (6.95,1.4) .. (10.93,3.29) ; \draw [fill={rgb, 255:red, 238; green, 10; blue, 10 } ,fill opacity=1 ] (193.32,222.63) -- (205.57,222.63) -- (205.57,287.42) -- (193.32,287.42) -- cycle ; \draw [fill={rgb, 255:red, 30; green, 211; blue, 231 } ,fill opacity=1 ] (312.76,221.87) -- (301.53,221.87) -- (301.53,286.67) -- (312.76,286.67) -- cycle ; \draw [fill={rgb, 255:red, 30; green, 211; blue, 231 } ,fill opacity=1 ] (408.73,79.47) -- (395.45,79.47) -- (395.45,286.67) -- (408.73,286.67) -- cycle ; \draw [dash pattern={on 4.5pt off 4.5pt}] (153.5,76.46) -- (446.5,78.72) ; \draw [dash pattern={on 4.5pt off 4.5pt}] (153.5,144.27) -- (346.45,145.77) ; \draw [dash pattern={on 4.5pt off 4.5pt}] (154.52,206.05) -- (347.47,207.56) ; \draw [dash pattern={on 4.5pt off 4.5pt}] (159.63,286.67) -- (426.08,287.42) ; \draw (201.99,12.41) node [font=\large] [align=left] {Cart}; \draw (401.07,13.16) node [font=\large] [align=left] {RRobot}; \draw (260.31,43.58) node [font=\large] [align=left] {$\displaystyle \mathit{arrive}$}; \draw (311.23,12.41) node [font=\large] [align=left] {GRobot}; \draw (355.28,61.15) node [font=\large] [align=left] {$\displaystyle \mathit{free}$}; \draw (259.18,160.32) node [font=\large] [align=left] {$\displaystyle \mathit{ready}$}; \draw (257.25,223.8) node [font=\large] [align=left] {$\displaystyle \mathit{ok}$}; \draw (358.41,154.02) node [anchor=north west][inner sep=0.75pt] [font=\Huge] [align=left] {*}; \draw (202,127) node [anchor=north west][inner sep=0.75pt] [font=\large] [align=left] {$\displaystyle {\displaystyle \rightsquigarrow }$}; \draw (202,269) node [anchor=north west][inner sep=0.75pt] [font=\large] [align=left] {$\displaystyle \rightsquigarrow $}; \draw (286,189) node [anchor=north west][inner sep=0.75pt] [font=\large] [align=left] {$\displaystyle \leftsquigarrow $}; \end{tikzpicture} \end{minipage} \caption{An example with a cart and two robot arms (left: schematic on top, actual robots used in experiments in {Sec.}~\ref{sec:eval} bottom) and a partial message sequence for one behavior of the system (right). Message exchanges take zero time but are shown with downward sloping arrows for readability. The colored boxes denote motion primitives and their execution allows physical time to pass. The light blue box denotes the motion primitive ``$\mathsf{work}$'' (in Figure~\ref{fig:basic-example}), red denotes ``$\mathsf{m\_move}$'', light green ``$\mathsf{m\_idle}$'', dark green ``$\mathsf{pick}$''. The dotted horizontal lines show synchronisation of global time across components. The use of the separating conjunction ``$\ast$'' ensures that time need not be synchronised with the red robot at intermediate synchronisations between the cart and the green robot. At each point, at most one motion primitive is non-interruptible (shown with ``${\mathsf{\rightsquigarrow}}$'') % \label{fig:basic_example_fig}} \end{figure} \begin{figure*}[t] { \small \begin{align*} \mu & \mathbf{t}. \!\!\!\!\! & \left( \begin{array}{l} \left( \begin{array}{l} \colorlet{oldcolor}{.} \color{blue}\boxed{\color{oldcolor}{\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{GRobot}}}:\mathit{arrive}.{\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{RRobot}}}:\mathit{free}}. \\[5px] \left(\begin{array}{cc} \left( \colorlet{oldcolor}{.} \color{green} \boxed{\color{oldcolor} \begin{array}{l} \motion{\dtsess}{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_move}^{\mathsf{\rightsquigarrow}}(\mathsf{point}),{\color{roleColor}{\mathsf{GRobot}}}:\mathsf{work}^{\mathsf{\lightning}}}.\\ {\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{GRobot}}}:\mathit{ready}.\\ \motion{\dtsess}{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_idle}^{\mathsf{\lightning}},{\color{roleColor}{\mathsf{GRobot}}}:\mathsf{pick}^{\mathsf{\rightsquigarrow}}}.\\ {\color{roleColor}{\mathsf{GRobot}}}\to{\color{roleColor}{\mathsf{Cart}}}:\mathit{ok}.\\ (\motion{\dtsess}{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_move}^{\mathsf{\rightsquigarrow}}(\mathsf{point})} ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{GRobot}}}:\mathsf{work}^{\mathsf{\lightning}}}) \end{array}} \color{oldcolor} \right) & \!\!\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{RRobot}}}:\mathsf{work}^{\mathsf{\lightning}}} \end{array} \right) \end{array}\right) \\ + \\ \big( \text{\quad as the above swapping ${\color{roleColor}{\mathsf{GRobot}}}$ with ${\color{roleColor}{\mathsf{RRobot}}}$\quad } \big) \end{array} \right).\mathbf{t} \end{align*} } \vspace{-3mm} \caption{Global choreography for the example\label{fig:basic-example}} \vspace*{-4mm} \end{figure*} \section{Motivating Example} \label{sec:example} In this section, we show a coordination example and use it to motivate the different choices of our programming model and choreography specifications. We start with a simple protocol. Consider a scenario where a cart shuttles (based on some unmodeled criterion) between two robotic arms, ``red'' and ``green'' (corresponding, e.g., to two different processing units). In each round, the cart lets the robots know of its choice and then moves to the chosen robot. On reaching its destination, the cart signals to the arm that it has arrived, and waits for the arm to finish processing. Meanwhile, the other arm can continue its own work independently. When the arm finishes its processing, it signals the cart that processing is complete. The cart moves back and then repeats the cycle. Figure~\ref{fig:basic_example_fig} shows a schematic of the system as well as a sample sequence of messages in each cycle. \myparagraph{Multiparty Motion Choreographies} We specify the global behaviour of a program using \emph{choreographies}, which describe the allowed sequence of global message exchanges and joint motion primitives as types for programs. The choreography for our example is shown in Figure~\ref{fig:basic-example}. It extends session types \cite{BLY2015,BYY2014,BMVY2019} with joint motion primitives similarly to motion session types \cite{ECOOP19} and a \emph{separating conjunction} $\ensuremath{\ast}$. {\bf\em (1) Messages and motion primitives.} The choreography in Figure~\ref{fig:basic-example} is a {\bf\emph{recursion}} ($\mu \mathbf{t}.G$), that makes a {\bf\emph{choice}} ($G_1 + G_2$) between two possibilities, corresponding to the cart interacting with the green or with the red robots (blue box). {\bf\em Message exchange} is specified by ${\sf p}\to{\sf q}:\ell$ which is a flow of a message labeled $\ell$ from process ${\sf p}$ to process ${\sf q}$. {\bf\em Joint motion primitives} $\motion{\dtsess}{{\sf p}:\ensuremath{\mathit{a}}, {\sf p}':\ensuremath{\mathit{a}}', \cdots}$ specify that the processes ${\sf p}$, ${\sf p}'$, etc.\ jointly execute motion primitives $\ensuremath{\mathit{a}}$, $\ensuremath{\mathit{a}}'$, etc.\ for the same amount of time. Global time is a global synchroniser; the type system makes sure that there is a consistent execution that advances time in the same way for every process. With just the construct for joint motion primitives, every component is forced to globally synchronise in time, preventing the robots to work independently in physically isolated spaces. We would like to specify, for example, that when the cart and the green robot ${\color{roleColor}{\mathsf{GRobot}}}$ is interacting, the red robot ${\color{roleColor}{\mathsf{RRobot}}}$ can independently perform its work without additional synchronisations. {\bf\em (2) Separating conjunctions.} To overcome this shortcoming, we introduce the {\bf\emph{separating conjunction}} $\ensuremath{\ast}$ (a novel addition from previous session types \cite{ECOOP19,BLY2015,BYY2014,BMVY2019}, explained below), which decomposes the participants into \emph{disjoint} subgroups, in terms of communication, dynamics, and use of geometric space over time, each of which can proceed independently until a merge point. The core interaction between the cart and an arm happens within the green box. Let us focus on the interaction when the green robot is picked. In this case, the cart moves to the green robot (while the green arm performs internal work), then synchronises with a $\mathit{ready}$ message, and then idles while the green arm picks an object from the cart. When the arm is done, it sends an $\mathit{ok}$ message, the cart moves back while the arm does internal work, and the protocol round ends. Meanwhile, the red robot can independently perform its work without synchronising with either the cart or the green robot. The other branch of $+$ is identical, swapping the roles of the red and the green robots. The separating conjunction makes it easy to specify physically and logically \emph{independent} portions of a protocol. Without it, we would be forced to send a message to the other (red) arm every time the cart and the green arm synchronised, even if the red arm proceeded independently. This would be required because time is global, and we would have to ensure that all motion primitives execute for exactly the same duration. Obviously, this leads to unwanted global synchronisations. {\bf\em (3) Interruptible and non-interruptible motions.} Our type system ensures that messages and motions alternate in the correct way. This requires differentiating between motion primitives that are {\bf\emph{interruptible}} (marked by ${\mathsf{\lightning}}$) from those that are not interruptible. An interruptible motion primitive is one that can be interrupted by a message receipt. For example, $\mathsf{m\_idle}$ or $\mathsf{work}$ in our example are interruptible. A {\bf\emph{non-interruptible}} motion primitive (marked by ${\mathsf{\rightsquigarrow}}$), on the other hand, should not be ``stopped'' by an external message. In order to ensure proper synchronisation between motion primitives and messages, we annotate motion primitives with ${\mathsf{\lightning}}$ or ${\mathsf{\rightsquigarrow}}$, which specify whether a motion can be interrupted by a message receipt or not. The type system checks that there is, at any time, at most one non-interruptible motion primitive, and moreover, the process executing that motion is the next one to send a synchronising message. This ensures that motion is compatible with synchronisation. The assumption that there is at most one non-interruptible motion primitive is a restriction; it rules out complex multi-robot maneuvres. However, there are already many ``loosely coupled'' systems that satisfy the assumption and it allows us to develop the (already complicated) theory without introducing distributed feedback control strategies to the mix. We leave lifting the assumption to future work. \myparagraph{Processes: Motion Primitives + Messages} We model robotic systems as concurrent processes in a variant of the session $\pi$-calculus for multiparty interactions \cite{YG2020}. Our calculus (defined in {Sec.}~\ref{sec:calculus}) abstracts away from the sequential operations and only considers the \emph{synchronisation behaviour} and the \emph{physical state changes}. Synchronisation is implemented through synchronous message exchanges between individual physical components (participants). Between message exchanges, each process executes \emph{motion primitives}: controller code that implements an actual robot motion. Motion primitives affect state changes in the physical world. \myparagraph{Correctness Criteria} Our type system prevents a well-typed implementation from ``going wrong'' in the following ways. \textbf{\emph{Communication Safety.}} We provide a choreography type system to ensure that programs are \emph{communication safe} and \emph{deadlock free}: a component does not get stuck sending a message with no recipient or waiting for a non-existent message. Ensuring communication safety is trickier for robotics programs because components may not be ready to receive messages because they are in the middle of executing a motion primitive that cannot be interrupted. \textbf{\emph{Motion Compatibility.}} We check that programs are able to \emph{jointly} execute motion primitives. The controllers implementing motion primitives implement control actions for coupled dynamical systems and we have to check that controllers for different components can be run together. \textbf{\emph{Collision Freedom.}} Components occupy 3D space; a correct implementation must ensure no geometric collision among objects. For example, we must ensure that the robot arms do not hit the cart when the cart is moving in their workspace. Our motion compatibility check ensures the geometric footprint of each component remains disjoint from others at all points in time. \myparagraph{Type Checking} The type checking algorithm has three parts. (1) First, we use an {\bf\emph{assume guarantee proof system}} to ensure jointly executed motion primitives are {\bf\emph{compatible}}: they allow a global trajectory for all the robots in the system and ensure there is no collision between components. (2) Second, we introduce a notion of {\bf\emph{well-formedness}} for choreographies. Well-formed choreographies ensure motion and message exchanges can be globally synchronised and that joint trajectories of the system are well-defined and collision free. (3) Finally, as in standard session types, we {\bf\emph{project a global choreography to its end-points}}, yielding a local type that can be checked for each process. The challenge is to manage the delicate interplay between time, motion, message exchanges, choices and the separating conjunction. This makes the well-formedness check more sophisticated than other choreography type systems. \section{Multiparty Motion Session Calculus} \label{sec:calculus} We now describe the motion session calculus, extending from \cite{ECOOP19}. \subsection{Syntax} \myparagraph{Physical Components and Processes} We assume a fixed static set $\ensuremath{\Bbb P}$ of \emph{physical components} (ranged over by ${\sf p}$, $\pq$,...), which are often called \emph{participants} or \emph{roles}; these are the different components that constitute the overall system. Each physical component executes a software process, which takes care of communication, synchronisation and motion. We describe the motion session calculus, which forms the core of the software process. A value $\kf{v}$ can be a natural number $\kf{n}$, an integer $\kf{i}$, a boolean $\kf{true}$/$\kf{false}$, or a real number. % An expression $\kf{e}$ can be a variable, a value, or a term built from expressions by applying (type-correct) computable operators. A \emph{motion primitive} (\ensuremath{\mathit{a}}, \ensuremath{\mathit{b}}, $\ldots$) is an abstraction of underlying physical trajectories; for the moment, consider a motion primitive simply as a name and describe its semantics later. We use the notation $\motion{dt}{\ensuremath{\mathit{a}}}$ to represent that a motion primitive executes and time elapses. We write the tuple $\motion{dt}{({\sf p}_i: \ensuremath{\mathit{a}}_i)}$ to denote a group of processes executing their respective motion primitives at the same time. For the sake of simplicity, we sometimes use $\ensuremath{\mathit{a}}$ for both single or grouped motions. The \emph{processes} ($\ensuremath{{P}},Q,R,...$) of the multiparty motion session calculus are defined by: \[ \begin{array}{lll}\ensuremath{{P}} ::= \procout {{\sf p}}{\ell}{\kf{e}}{\ensuremath{{P}}} \ensuremath{~~\mathbf{|\!\!|}~~ } \sum\limits_{i\in I} \procin{{\sf p}}{\ell_i(x_i)}{\ensuremath{{P}}_i} \ensuremath{~~\mathbf{|\!\!|}~~ } \cond{\kf{e}}\ensuremath{{P}} \ensuremath{{P}} % % \ensuremath{~~\mathbf{|\!\!|}~~ } \sum\limits_{i\in I} \procin{{\sf p}}{\ell_i(x_i)}{\ensuremath{{P}}_i}+\motion{dt}{a}.{\ensuremath{{P}}} \ensuremath{~~\mathbf{|\!\!|}~~ } \motion{dt}{\ensuremath{\mathit{a}}}.\ensuremath{{P}} \ensuremath{~~\mathbf{|\!\!|}~~ } \mu{\roleVar}.\ensuremath{{P}} \ensuremath{~~\mathbf{|\!\!|}~~ } {\roleVar} % \end{array} \] The output process $\procout{{\sf p}}{\ell}{\kf{e}}{\ensuremath{Q}}$ sends the value of expression $\kf{e}$ with label $\ell$ to participant ${\sf p}$. The sum of input processes (external choice) $\sum_{i\in I}\procin{{\sf p}}{\ell_i(x_i)}{\ensuremath{{P}}_i}$ is a process that can accept a value with label $ \ell_i $ from participant $ {\sf p}$ for any $ i\in I$; $\sum_{i\in I}\procin{{\sf p}}{\ell_i(x_i)}{\ensuremath{{P}}_i}+\motion{dt}{a}.{\ensuremath{{P}}}$ is an external choice with a \emph{default branch} with a motion action $\motion{dt}{a}.{\ensuremath{{P}}}$ which can always proceed when there is no message to receive. According to the label $\ell_i$ of the received value, the variable $x_i$ is instantiated with the value in the continuation process $ \ensuremath{{P}}_i$. We assume that the set $I$ is always finite and non-empty. Motion primitives are indicated by $\motion{dt}{\ensuremath{\mathit{a}}}$; the $\kf{dt}$ denoting that real time progresses when a motion primitive $\ensuremath{\mathit{a}}$ is executed. The conditional process $\cond{\kf{e}}{\ensuremath{{P}}}{Q} $ represents the internal choice between processes $ \ensuremath{{P}} $ and $ \ensuremath{Q} $. Which branch of the conditional process will be taken depends on the evaluation of the expression $ \kf{e}. $ The process $\mu {\roleVar}.\ensuremath{{P}}$ is a recursive process. Note that our processes do not have a null process: this is because a physical component does not ``disappear'' when the program stops. Instead, we model inaction with an iteration of some default motion primitive. \begin{example}[Processes]\rm The processes for the cart and the two robots from Figure~\ref{fig:basic_example_fig} are given as: \[ \begin{array}{cc} \begin{array}{rl}\small {\color{roleColor}{\mathsf{Cart}}}:\!\!\!\!\!\!\!\!\!\!\!\!\\ \mu {\roleVar}.\!\!\!\!\!\! & ({\color{roleColor}{\mathsf{GRobot}}}!\mathit{arrive}.{\color{roleColor}{\mathsf{RRobot}}}!\mathit{free}.\\ & \quad \motion{dt}{\mathsf{m\_move}(\text{co-ord of }{\color{roleColor}{\mathsf{GRobot}}})}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{ready}.\\ & \quad \motion{dt}{\mathsf{m\_idle}}.{\color{roleColor}{\mathsf{GRobot}}}?\mathit{ok}.\motion{dt}{\mathsf{m\_move}(\text{base})}.{\roleVar}\\ & + \textrm{ symmetrically for ${\color{roleColor}{\mathsf{RRobot}}}$ }) \end{array} & \!\!\!\!\!\!\!\! \begin{array}{rl} \small {\color{roleColor}{\mathsf{RRobot}}},\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\\\ {\color{roleColor}{\mathsf{GRobot}}}:\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\\ \mu {\roleVar}.\!\!\!\!\!\!& ({\color{roleColor}{\mathsf{Cart}}}?\mathit{arrive}.\motion{dt}{\mathsf{work}}.{\color{roleColor}{\mathsf{Cart}}}?\mathit{ready}.\\ & \quad \ \motion{dt}{\mathsf{pick}}.{\color{roleColor}{\mathsf{Cart}}}!\mathit{ok}.\motion{dt}{\mathsf{work}}).{\roleVar}\\ & \ + \ ({\color{roleColor}{\mathsf{Cart}}}?\mathit{free}.\motion{dt}{\mathsf{work}}).{\roleVar}\\ \end{array} \end{array} \] Note that for both processes, the recursion ensures that the program does not terminate. Motion primitives for the cart involve moving to various locations $\mathsf{m\_move}(\mathit{pos})$ and idling at a location ($\mathsf{m\_idle}$), and those for the robots involve doing some (unspecified) work $\mathsf{work}$ or picking items off the cart $\mathsf{pick}$ (internally, these motion primitives would involve motion planning and inverse kinematics for the robot arms). Next, we describe the modelling and representation of motion primitives in more detail. \end{example} \myparagraph{Physical Variables and Footprint} Motion primitives make the robot ``move'' in the physical world. Each motion primitive represents an abstraction of an underlying controlled dynamical system, such as the controller for the robot arm or the controller for a cart. The dynamical system changes underlying physical state (such as the position and orientation of the arm or the position and velocity of the cart). The dynamics can be coupled: for example, if an arm is mounted on a cart, then the motion of the cart is influenced by the mass and position of the arm. We model the underlying physical system using \emph{physical variables}, and we partition these into state variables $X$ (dynamical variables read and controlled by the component), input variables $W$ (dynamical variables read by the component, whose values are provided by the environment). The specification of a motion primitive will constrain the values of these variables over time. We make the physical variables clear by writing ${\roleP} \ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}}{{X}}{{W}}$ for a physical component ${\roleP}\in \ensuremath{\Bbb P}$ with state and input variables $X$ and $W$, respectively, which executes the process $\ensuremath{{P}}$. Each physical component ${\roleP}\in \ensuremath{\Bbb P}$ has a \emph{geometric footprint} $\geom{{\roleP}}$ associated with it. This represents the physical space occupied by the component, and will be used to ensure that two components do not collide. The footprint is a function from valuations to variables in $X$ to a subset of $ℝ^3$. It describes an overapproximation of the space occupied by the component as a function of the current state. Note that the footprint can depend on the state. \begin{example}\rm \label{ex:mp-footprint} Let $x$ and $v$ denote the position and the velocity of the cart, respectively, restricting the discussion only on one axis. Thus, $X = \set{x, v}$. If we assume there are no external influences on the cart, we can take $W = \emptyset$. The footprint provides a bounding box around the cart as it moves. If the cart has dimensions $(l, w, h)$, the footprint at the location $(x, y, z)$ is \begin{align} \set{(\mathsf{x}, \mathsf{y}, \mathsf{z}) \mid x-\frac{l}{2} \leq \mathsf{x} \leq x+\frac{l}{2} \wedge 0\leq \mathsf{y} \leq h \wedge z -\frac{w}{2} \leq \mathsf{z} \leq z+\frac{w}{2} } \end{align} \end{example} \myparagraph{Composition} We now define parallel composition of physical components. Composition of physical components ensure the following aspects. First, like process calculi, parallel composition provides a locus for message exchange: a physical component can send messages to, or receive messages from, another one. Second, composition connects physical state variables of one component to the physical input variables of another---this enables the coupling of the underlying dynamics. To ease reasoning about connections between physical variables, we assume that the components in a composition have disjoint sets of physical and logical variables, and connections occur through syntactic naming of input variables. Thus, a component with an input variable $x$ gets its value from the unique component that has a physical state variable called $x$. Hence, there is no ambiguity in forming connections. We refer to the variables of ${\roleP}$ as ${\roleP}.X$ and ${\roleP}.W$. We define a \emph{multiparty session} as a parallel composition of pairs of participants and processes: \[ \begin{array}{lll} M & ::= & {\sf p}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}}{X}{W} \ensuremath{~~\mathbf{|\!\!|}~~ } M \ensuremath{~|~} M \end{array} \] with the intuition that process $\ensuremath{{P}}$ plays the role of participant ${\sf p}$, % and can interact with other processes playing other roles in $M$. % A multiparty session is \emph{well-formed} if all its participants are different, and for each input variable of each participant there is a syntactically unique state variable in a different participant so that connections between physical variables is well-defined. We consider only well-formed processes. \begin{example}\rm For the example from {Sec.}~\ref{sec:example}, the multiparty session is \[ {\color{roleColor}{\mathsf{Cart}}}\ensuremath{\triangleleft{}}\proc{\text{proc.\ for ${\color{roleColor}{\mathsf{Cart}}}$}}{\set{x,v}}{\emptyset} \ensuremath{~|~} {\color{roleColor}{\mathsf{RRobot}}} \ensuremath{\triangleleft{}}\proc{\text{proc.\ for ${\color{roleColor}{\mathsf{RRobot}}}$}}{\cdot}{\cdot} \ensuremath{~|~} {\color{roleColor}{\mathsf{GRobot}}} \ensuremath{\triangleleft{}}\proc{\text{proc.\ for ${\color{roleColor}{\mathsf{GRobot}}}$}}{\cdot}{\cdot} \] (we have omitted the physical variables for the robot arms for simplicity). \end{example} \subsection{Motion Primitives} \label{sec:mp-rules} Before providing the operational semantics, we first consider how motion primitives are specified. Recall that motion primitives of a component ${\roleP}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}}{X}{W}$ abstract a trajectory arising out of the underlying dynamics. A first idea is to represent a motion primitive as a pair $\tuple{\ensuremath{\mathrm{Pre}\xspace}, \ensuremath{\mathrm{Post}\xspace}}$---this provides a precondition $\ensuremath{\mathrm{Pre}\xspace}$ that specifies the condition on the state under which the motion primitive can be applied and a postcondition $\ensuremath{\mathrm{Post}\xspace}$ that specifies the effect of applying the motion primitive on the physical state. However, this is not sufficient: the motion of two components can be coupled in time and the trajectory of a component depends on the inputs it gets from other components and, in turn, its trajectory influences the trajectories of the other components. Therefore, a motion primitive also needs to specify \emph{assumptions} on its external inputs and \emph{guarantees} it provides to other processes over time. These predicates are used to decouple the dynamics. Our motion primitive has three more ingredients. The first is the \emph{footprint}: the geometric space used by a process over time while it executes its trajectory and is used to ensure geometric separation between components. The second is a pair $(D, {\ddagger})$ of a \emph{time interval and an annotation}: the time interval bounds the \emph{minimal} and \emph{maximal times} between which a motion primitive is ready to communicate via message passing, and the ${\ddagger}$ annotation distinguishes between motion primitives that are interruptible by external messages from those that cannot be interrupted. We assume preconditions and postconditions only depend on the state, while assumptions, guarantees, and footprints may depend on both the state and the elapsed time. \begin{definition}[Motion primitive] The specification for a motion primitive $\ensuremath{\mathit{a}}$ of a physical process ${\roleP}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}}{X}{W}$, written $\judgement{\ensuremath{\mathit{a}}}{\ensuremath{\mathrm{Pre}\xspace},A,G,\ensuremath{\mathrm{Post}\xspace},\ensuremath{\mathit{FP}},D, {\ddagger}}$, consists of two predicates \emph{precondition} $\ensuremath{\mathrm{Pre}\xspace}$ and \emph{postcondition} $\ensuremath{\mathrm{Post}\xspace}$ over $X\cup W$, an \emph{input assumption} $A$ which is a predicate over $W\cup\set{\ensuremath{\mathsf{clock}}\xspace}$, an \emph{output guarantee} $G$ which is a predicate over $X\cup\set{\ensuremath{\mathsf{clock}}\xspace}$, a \emph{footprint} $\ensuremath{\mathit{FP}}$ which is a predicate over $X \cup \set{\mathsf{x},\mathsf{y},\mathsf{z},\ensuremath{\mathsf{clock}}\xspace}$, a \emph{duration} $D\in (ℝ\cup\set{\infty})^2$ which is a time interval, and ${\ddagger}\in\set{{\mathsf{\lightning}},{\mathsf{\rightsquigarrow}}}$ which indicates if the motion primitive can be interrupted by an external message (${\mathsf{\lightning}}$) or not (${\mathsf{\rightsquigarrow}}$). Given motion primitives $\ensuremath{\mathit{a}}$ and $\ensuremath{\mathit{a}}'$, we say $\ensuremath{\mathit{a}}$ \emph{refines} $\ensuremath{\mathit{a}}'$, denoted by $\ensuremath{\mathit{a}} \ensuremath{\preceq} \ensuremath{\mathit{a}}'$, with $\judgement{\ensuremath{\mathit{a}}}{φ,A,G,ψ,\ensuremath{\mathit{FP}}, D, {\ddagger}}$ and $\judgement{\ensuremath{\mathit{a}}'}{φ',A',G',ψ',\ensuremath{\mathit{FP}}', D', {\ddagger}'}$ iff (1) $φ ⇒ φ'$, (2) $A ⇒ A'$, (3) $G' ⇒ G$, (4) $ψ' ⇒ ψ$, (5) $\ensuremath{\mathit{FP}}' ⊆ \ensuremath{\mathit{FP}}$, (6) ${\ddagger} = {\ddagger}'$, and (7) either ${\ddagger} ={\mathsf{\lightning}}$ and $D⊆ D'$ or ${\ddagger}={\mathsf{\rightsquigarrow}}$ and $D' ⊆ D$. \end{definition} \subsection{Operational Semantics} \label{sec:opsem} The operational semantics is given as reduction rules relative to \emph{stores} $\sstore{X},\sstore{W}$ (Figure~\ref{fig:opsem}) that map physical variables to values. The semantics uses the standard structural rules defined in Figure~\ref{tab:sync:congr}. We adopt some standard conventions regarding the syntax of processes and sessions. Namely, we will use $\prod_{i\in I} {{\sf p}_i}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}_i}{X_i}{W_i}$ for ${{\sf p}_1}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}_1}{X_1}{W_1}\ensuremath{~|~} \ldots\ensuremath{~|~} {{\sf p}_n}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}_n}{X_n}{W_n},$ where $I=\set{1,\ldots,n}$, or simply as $\prod_{i\in I} \pa{{\sf p}_i}{\ensuremath{{P}}_i}$ when the physical variables are not important. % We use infix notation for external choice process, e.g., instead of $\sum_{i\in \{1,2\}} \procin{{\sf p}}{\ell_i(x)}{\ensuremath{{P}}_i}$, we write $\procin{{\sf p}}{\ell_1(x)}{\ensuremath{{P}}_1}+\procin{{\sf p}}{\ell_2(x)}{\ensuremath{{P}}_2}.$ {\em The value $\kf{v}$ of expression $\kf{e}$ with physical state $\sstore{X}$} (notation $\evalState{\kf{e}}{\kf{v}}{\sstore{X}}$) is computed as expected. We assume that $\evalState{\kf{e}}{\kf{v}}{\sstore{X}}$ is effectively computable and takes logical ``zero time.'' \begin{figure}[!t] \label{tab:sync:red} \small \[ \begin{array}[t]{@{}c@{}} \rulename{recv}\inferrule% { j\in I } { {\sf p}\ensuremath{\triangleleft{}}\proc{\sum\limits_{i\in I} \procin{\pq}{\ell_i(x)}{\ensuremath{{P}}_i} + \motion{dt}{a}.{\ensuremath{{P}}} }{\sstore{X}}{\sstore{W}} \xrightarrow{\pq?\ell_j(v)} {\sf p}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}_j\set{v/x}}{\sstore{X}}{\sstore{W}} } \\[5mm] \rulename{send} \inferrule% { \evalState{\kf{e}}{\kf{v}}{\sstore{X},\sstore{W}} }{ {\sf p}\ensuremath{\triangleleft{}}\proc{\procout{\pq}{\ell_j}{\kf{e}}{Q}}{\sstore{X}}{\sstore{W}} \xrightarrow{\pq!\ell\tuple{\kf{v}}} {\sf p}\ensuremath{\triangleleft{}}\proc{Q}{\sstore{X}}{\sstore{W}} } \quad \rulename{comm} \inferrule% { \pa{\sf p}{\ensuremath{{P}}} \xrightarrow{\pq!\ell\tuple{\kf{v}}} \pa{\sf p}{\ensuremath{{P}}'}\\ \pa\pq{\ensuremath{Q}} \xrightarrow{{\sf p}?\ell(\kf{v})} \pa\pq{\ensuremath{Q}'}\\ } { \pa{\sf p}{\ensuremath{{P}}} \ensuremath{~|~} \pa\pq{\ensuremath{Q}} % \longrightarrow{} \pa{\sf p}{\ensuremath{{P}}'} \ensuremath{~|~} \pa\pq{\ensuremath{Q}'} % } \\[6mm] \inferrule[\rulename{default}] { {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\tau} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT 0}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \\ {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT 0}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}},\xi,\nu, t} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t}.\ensuremath{{P}}}{\sstore{X}'}{\sstore{W}'} } { {\sf p}\ensuremath{\triangleleft{}} \proc{\sum\limits_{i\in I} \procin{\pq}{\ell_i(x)}{\ensuremath{{P}}_i} + \motion{\dtsess}{a}.{\ensuremath{{P}}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}},\xi,\nu, t} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t}.\ensuremath{{P}}}{\sstore{X}'}{\sstore{W}'} } \\[5mm] \inferrule[\rulename{traj-base}] { \ensuremath{\mathrm{Pre}\xspace}\{\sstore{X}/X,\sstore{W}/W, 0/\ensuremath{\mathsf{clock}}\xspace\}\quad A\{\sstore{W}/W, 0/\ensuremath{\mathsf{clock}}\xspace\}\wedge G\{\sstore{X}/X, 0/\ensuremath{\mathsf{clock}}\xspace\} \\ \geom{{\sf p}}(\sstore{X})\subseteq\ensuremath{\mathit{FP}}\set{\sstore{X}/X,0/\ensuremath{\mathsf{clock}}\xspace} } { {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\tau} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT 0}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} } \\[5mm] \rulename{traj-step} \inferrule% { \xi: [t_1,t_2] \rightarrow ℝ^X, \nu: [t_1,t_2] \rightarrow ℝ^W\\ \xi(t_1) = \sstore{X}, \xi(t_2) = \sstore{X}' \\ \nu(t_1) = \sstore{W}, \nu(t_2) = \sstore{W}' \\ \forall t\in [t_1,t_2].\ A\{\nu(t)/W, t/\ensuremath{\mathsf{clock}}\xspace\} \wedge G\{\xi(t)/X, t/\ensuremath{\mathsf{clock}}\xspace\} \ \wedge \geom{{\sf p}}(\xi(t))\subseteq\ensuremath{\mathit{FP}}\set{\sstore{X}/X,t/\ensuremath{\mathsf{clock}}\xspace} } { {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t_1}.P}{\sstore{X}}{\sstore{W}} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}},\xi,\nu, t_2-t_1} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t_2}.P}{\sstore{X}'}{\sstore{W}'} } \\[7mm] \inferrule[\rulename{t-conditional}] { \evalState{\kf{e}}{\kf{true}}{\sstore{X},\sstore{W}} } { {\sf p}\ensuremath{\triangleleft{}}\proc{\cond{\kf{e}}{\ensuremath{{P}}}{\ensuremath{Q}}}{\sstore{X}}{\sstore{W}} \xrightarrow{} {\sf p}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} } \quad \inferrule[\rulename{non-interrupt}] { t \in D\\ {\ddagger} = {\mathsf{\rightsquigarrow}}\\ \ensuremath{\mathrm{Post}\xspace}\set{\sstore{X}/X,\sstore{W}/W,t/\ensuremath{\mathsf{clock}}\xspace}\\ } { {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\tau} {\sf p}\ensuremath{\triangleleft{}} \proc{\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} } \\[5mm] \rulename{interrupt} \inferrule% { t \in D\\ {\ddagger} = {\mathsf{\lightning}}\\ \ensuremath{\mathrm{Post}\xspace}\set{\sstore{X}/X,\sstore{W}/W,t/\ensuremath{\mathsf{clock}}\xspace}\\ {\sf p}\ensuremath{\triangleleft{}} \proc{\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\pq?\ell(\kf{v})} {\sf p}\ensuremath{\triangleleft{}} \proc{\ensuremath{{P}}'}{\sstore{X}}{\sstore{W}} } { {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\pq?\ell(\kf{v})} {\sf p}\ensuremath{\triangleleft{}} \proc{\ensuremath{{P}}'}{\sstore{X}}{\sstore{W}} } \\[5mm] \rulename{m-par} \inferrule% { \exists \xi, \nu.~ \forall i,j \in I.\\ i\neq j \Rightarrow \mathsf{disjoint}(\ensuremath{\mathit{a}}_i,\ensuremath{\mathit{a}}_j) \\ {\sf p}_i\ensuremath{\triangleleft{}}\proc{P_i}{\sstore{X}_i}{\sstore{W}_i} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}_i},\xi|_{X_i}, (\xi\cup\nu)|_{W_i}, t} {\sf p}_i\ensuremath{\triangleleft{}}\proc{P_i'}{\sstore{X}'_i}{\sstore{W}'_i}\\ } { \prod_{i \in I} {\sf p}_i\ensuremath{\triangleleft{}}\proc{P_i}{\sstore{X}_i}{\sstore{W}_i} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}_i}, t} \prod_{i \in I} {\sf p}_i\ensuremath{\triangleleft{}}\proc{P_i'}{\sstore{X}'_i}{\sstore{W}'_i} } \\[6mm] \rulename{r-par$\tau$} \inferrule% { M_1 \xrightarrow{\tau} M_2 } { M_1 \ensuremath{~|~} M \xrightarrow{\tau} M_2 \ensuremath{~|~} M } \qquad \rulename{r-par} \inferrule% { M_1 \longrightarrow{} M_2 } { M_1 \ensuremath{~|~} M \longrightarrow{} M_2 \ensuremath{~|~} M } \qquad \rulename{r-struct} \inferrule% { M'_1\equiv M_1 \xrightarrow{\alpha} M_2 \equiv M'_2 } { M'_1 \xrightarrow{\alpha} M'_2 } \end{array} \] \noindent We omit \rulename{f-conditional}. We use $\xrightarrow{\alpha}$ for any labelled transition relation or reduction ($\xrightarrow{}$). \caption{Operational semantics} \label{fig:opsem} \vspace*{-0.5cm} \end{figure} \begin{figure}{} $ \small \begin{array}[t]{@{}c@{}} \inferrule[\rulename{s-rec}]{}{ \mu {\roleVar}.\ensuremath{{P}} \equiv \ensuremath{{P}}\sub{\mu {\roleVar}.\ensuremath{{P}}}{{\roleVar}} } \quad \inferrule[\rulename{s-multi}]{}{ \ensuremath{{P}} \equiv \ensuremath{Q} \Rightarrow \pa{\sf p}\ensuremath{{P}} \ | \ M\equiv\pa{\sf p}\ensuremath{Q} \ | \ M } \quad \inferrule[\rulename{s-par 1}]{}{ M \ | \ M' \equiv M' \ | \ M } \quad \inferrule[\rulename{s-par 2}]{}{ (M \ | \ M') \ | \ M'' \equiv M \ | \ ( M' \ | \ M'') } \end{array} $ \caption{Structural congruence rules} \label{tab:sync:congr} \vspace*{-0.5cm} \end{figure} For reduction rules that do not change the physical state, we omit writing the physical state in the rule. Time is global, and processes synchronize in time to make concurrent motion steps of the same (but not pre-determined) duration. Communication (\rulename{comm}) is synchronous and puts together sends and receives. Rule \rulename{default} selects the default branch. Rules for conditionals, communication without default motion and parallel composition are defined in a standard way \cite{ECOOP19,DGJPY2016,GHPSY19}. To define the operational semantics for motions, we extend the process syntax $P$ with time-annotated motion primitives, $\motion{dt}{\ensuremath{\mathit{a}}\AT t}\quad \text{ for }t\geq 0$. Let us fix a component ${\sf p}$ and its motion primitive $\judgement{\ensuremath{\mathit{a}}}{\ensuremath{\mathrm{Pre}\xspace},A,G,\ensuremath{\mathrm{Post}\xspace},\ensuremath{\mathit{FP}},D,{\ddagger}}$. Rules \rulename{traj-base} and \rulename{traj-step} set up trajectories for each motion primitive. We distinguish between interruptible (\rulename{interrupt}) and non-interruptible (\rulename{non-interrupt}) motion primitives. Non-interruptible motion primitives are consumed by the process. Interruptible motion primitives consume the motion primitive on a message receipt. The parallel composition rule \rulename{m-par} requires a consistent global trajectory and ensures that when (physical) time elapses for one process, it elapses equally for all processes. Here, $\mathsf{disjoint}(\ensuremath{\mathit{a}}_i, \ensuremath{\mathit{a}}_j)$ states that the footprints along the trajectory are disjoint: $\ensuremath{\mathit{a}}_i.\ensuremath{\mathit{FP}}\set{\xi_i(t')/X,t'/\ensuremath{\mathsf{clock}}\xspace}\cap\ensuremath{\mathit{a}}_j.\ensuremath{\mathit{FP}}\set{\xi_j(t')/X,t'/\ensuremath{\mathsf{clock}}\xspace}=\emptyset$ for all $t'\in[0,t]$. We use $\longrightarrow^*$ for the reflexive transitive closure of $\longrightarrow$. We say a program state $\prod_i {\sf p}_i \ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}_i}{\sstore{X}_i}{\sstore{W}_i}$ is \emph{collision free} if $\geom{{\sf p}_i}(\sstore{X}_i)\cap\geom{{\sf p}_j}(\sstore{X}_j) = \emptyset$ for every $i\neq j$. \subsection{Joint Compatibility of Motion Primitives} Two motion primitives are \emph{compatible} if they can be jointly executed. To decide compatibility, we compose the specifications using the following \emph{assume-guarantee proof rule}:\\ \centerline{ $ \small \begin{array}{ll} \begin{array}{ll} \rulename{AGcomp}\\\\\\\\\ \end{array} & \inferrule{ \exists \ensuremath{\mathit{FP}}_1, \ensuremath{\mathit{FP}}_2.\ G_1 \wedge G_2 \Rightarrow \ensuremath{\mathit{FP}}_1 \cap FP_2 = \emptyset\quad G_1 \wedge G_2 \Rightarrow \ensuremath{\mathit{FP}}_1 \cup FP_2 \subseteq \ensuremath{\mathit{FP}}\\\\ {\ddagger}_1 ={\mathsf{\lightning}} \vee {\ddagger}_2 = {\mathsf{\lightning}} \quad {\ddagger}_1 ={\mathsf{\rightsquigarrow}} ⇒ D₁ ⊆ D₂ \quad {\ddagger}_2 ={\mathsf{\rightsquigarrow}} ⇒ D₂ ⊆ D₁ \\\\ \ensuremath{\mathit{a}}_1 \ensuremath{\preceq} \tuple{φ₁,A∧ G₂,G₁,\ensuremath{\mathit{FP}}_1,ψ₁,D_1,{\ddagger}_1}\quad \ensuremath{\mathit{a}}_2 \ensuremath{\preceq} \tuple{φ₂,A∧ G₁,G₂,\ensuremath{\mathit{FP}}_2,ψ₂,D_2,{\ddagger}_2} } {\hspace*{-2mm}\judgement{\tuple{{\sf p}_1{:}\ensuremath{\mathit{a}}_1, {\sf p}_2{:}\ensuremath{\mathit{a}}_2}}{φ₁∧φ₂,A,G₁∧G₂,\ensuremath{\mathit{FP}},ψ₁∧ψ₂,D₁∩D₂,{\ddagger}_1\oplus{\ddagger}_2}} \end{array} $}% \noindent The $\oplus$ operator combines the interruptibility: ${\mathsf{\lightning}} \oplus {\mathsf{\lightning}} = {\mathsf{\lightning}}$ and ${\mathsf{\lightning}} \oplus {\mathsf{\rightsquigarrow}} = {\mathsf{\rightsquigarrow}} \oplus {\mathsf{\lightning}} = {\mathsf{\rightsquigarrow}} \oplus{\mathsf{\rightsquigarrow}} = {\mathsf{\rightsquigarrow}}$. The \rulename{AGcomp} rule performs three checks. First, the check on footprints ensures that the motion primitives are disjoint in space (there is a way to find subsets $\ensuremath{\mathit{FP}}_1$ and $\ensuremath{\mathit{FP}}_2$ of the footprint $\ensuremath{\mathit{FP}}$ so that the composed motion primitives are in these disjoint portions). Second, the guarantee of one motion primitive is used as the assumption of the other to check that they are compatible. Third, the checks on timing ensures that at most one process executes a non-interruptible motion primitive and the interruptible ones are ready before the non-interruptible one. We say $\motion{\dtsess}{({\sf p}_i {:} \ensuremath{\mathit{a}}_i)}$ is \emph{compatible} from $\ensuremath{\mathrm{Pre}\xspace}$ if there exist $G$, $\ensuremath{\mathrm{Post}\xspace}$, $\ensuremath{\mathit{FP}}$, and $D$ such that $\judgement{\prod_i{{\sf p}_i:\ensuremath{\mathit{a}}_i}}{\ensuremath{\mathrm{Pre}\xspace}, \kf{true}, G, \ensuremath{\mathrm{Post}\xspace}, \ensuremath{\mathit{FP}}, D, {\ddagger}}$ is derivable using \rulename{AGcomp} repeatedly. Thus, compatibility checks that motion primitive specifications can be put together if processes start from their preconditions: first, the assumptions and guarantees are compatible; second, there is no ``leftover'' assumption; and third, the footprints of the motion primitives do not intersect in space. Compatibility provides the ``converse'' condition that allows joint trajectories in \rulename{M-par} to exist. The next theorem formalizes what motion compatibility guarantees. Intuitively, motion compatibility means it is sufficient to check the compatibility of contracts to guarantee the existence of a joint trajectory, i.e., the execution is defined for all the components and the joint trajectory satisfies the composition of the contracts. \begin{restatable}[Motion Compatibility]{theorem}{theoremMC} \label{th:motion-compat} Suppose $\motion{\dtsess}{({\sf p}_1:\ensuremath{\mathit{a}}_1,{\sf p}_2:\ensuremath{\mathit{a}}_2)}$ is compatible. For every $t\in D$, if there exist trajectories $\xi_1, \xi_2,\nu_1,\nu_2$ such that $\pa{{\sf p}_i}{\ensuremath{{P}}_i} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}_i},\xi_i, \nu_i, t} \pa{{\sf p}_i}{\ensuremath{{P}}_i'}$ for $i\in \set{1,2}$, then there exist trajectories $\xi:[0,t]\rightarrow ℝ^{X_1\cup X_2}, \nu:[0,t]\rightarrow ℝ^{W_1\cup W_2 \setminus (X_1\cup X_2)}$ such that $\pa{{\sf p}_i}{\ensuremath{{P}}_i} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}_i},\xi|_{X_i}, \nu|_{W_i}, t} \pa{{\sf p}_i}{\ensuremath{{P}}_i'}$ and for all $0 \leq t' \leq t$, the footprints of ${\sf p}_1$ and ${\sf p}_2$ are disjoint: $\geom{{\sf p}_1}({\xi(t')|_{X_1}}) \cap \geom{{\sf p}_2}({\xi(t')|_{X_2}}) = \emptyset$. \end{restatable} \begin{proof} (Sketch.) % This theorem is proved along the lines of the AG rule by \citet{DBLP:conf/hybrid/HenzingerMP01}. Their proof relies on motion primitives having the following properties: prefix closure, deadlock freedom, and input permissiveness. Deadlock freedom is, in this setting \cite{DBLP:conf/hybrid/HenzingerMP01}, means that if a precond is satisfied then the trajectory must exists, and every execution that does not yet satisfies the postcondition can be prolonged be extended. Input permissiveness states that a component cannot deadlock no matter how the environment decides to change the inputs. This condition is needed to do induction over time. Input permissiveness does not directly follow from the definition of our contracts. However, it holds when the environment changes the inputs in a way that is allowed by the assumptions. As \rulename{AGcomp} checks that this is true and rejects the composition otherwise, we can reuse the same proof strategy. A process should not be allowed to block time making the system ``trivially safe'' but physically meaningless. We also need to check the disjointness of footprints which is new in our model (needed by \rulename{M-par}). This is also checked by \rulename{AGcomp}. \end{proof} \subsection{Examples for motion primitives, compatibilities and environments} \myparagraph{Motion primitives from dynamics} \label{ex:motion} For the ${\color{roleColor}{\mathsf{Cart}}}$ in {Sec.}~\ref{sec:example}, we can derive motion primitives from a simple dynamical model $\dot{x} = v, \dot{v} = u$. Here, $X = \set{x,v}$ and $W= \emptyset$. For simplicity, assume the cart moves along a straight line (its $x$-axis) and that the control $u$ can apply a fixed acceleration $a_{\max}$ or a fixed deceleration $-a_{\max}$. Consider the motion primitive $\mathsf{m\_move}$ which takes the cart from an initial position and velocity $(x_i, v_i)$ to a final position $(x_f, v_f)$. From high school physics, we can solve for $x$ and $v$, given initial values $x_i$ and $v_i$:\\ \centerline{$ x = x_i + v_it + \frac{1}{2}a_{\max} t^2 \mbox{ and } v = v_i + a_{\max} t $} from which, by eliminating $t$, we have $(v - v_i)^2 = 2 a (x - x_i)$. Suppose that the cart starts from rest ($v_i=0$), accelerates until the midpoint $\mathit{mid} = \frac{1}{2}(x_i+x_f)$, and thereafter decelerates to reach $x_f$ again with velocity $v_f= 0$. The precondition $\ensuremath{\mathrm{Pre}\xspace}$ is $x_f > x\wedge v = 0$, the first conjunction saying we move right (we can write another motion primitive for moving left). The assumption $A$ is $\kf{true}$, and the guarantee is\\ \centerline{ $x_i \leq x \leq x_f \wedge \left( \begin{array}{c} (x_i \leq x \leq \mathit{mid} \Rightarrow v^2 = 2 a_{\max} (x - x_i)) \wedge\\ (\mathit{mid} \leq x \leq x_f \Rightarrow v^2 = 2 a_{\max} (x_f - x)) \end{array} \right) $}\\[1mm] The postcondition is $x = x_f \wedge v = 0$. The footprint provides a bounding box around the cart as it moves, and is given as in Example~\ref{ex:mp-footprint}. We assume that the motion cannot be interrupted. Thus, we place the annotation ${\mathsf{\rightsquigarrow}}$. The least time to destination is $t_m = 2\sqrt{(x_f-x_i)/a_{\max}}$ and the duration (the interval when it is ready to communicate) is $[t_m, \infty)$. A simpler primitive is $\mathsf{m\_idle}$: it keeps the cart stationary. Its assumption is again $\kf{true}$, guarantee (and postcondition) is $x = x_i \wedge v = 0$, footprint is a bounding box around the fixed position. It is interruptible by messages from other components (annotation ${\mathsf{\lightning}}$) at any time: $D = [0,\infty)$. \myparagraph{Compatibility} Now consider the constraints that ensure the joint trajectories involving the ${\color{roleColor}{\mathsf{Cart}}}$'s motion and the ${\color{roleColor}{\mathsf{Prod}}}$'s $\mathsf{work}$ primitive are compatible. First, note that the motion of the cart is non-interruptible (${\mathsf{\rightsquigarrow}}$) but we assume the arm is interruptible, satisfying the constraint in \rulename{AGcomp} that at most one motion is not interruptible. Instead of the complexities of modeling the geometry and the dynamics of the arm, we approximate the footprint of the arm (the geometric space it occupies) as a half-sphere centered at the base of the arm and extending upward. Assume first that the motion primitive guarantees that the state is always within this half-sphere. In order for the cart and the robot arm to be compatible, we have to check that the footprints do not overlap. Our guarantee is too weak to prove compatibility, as the footprint of the cart and the arm can intersect when the cart is close to the arm. Instead, we strengthen the guarantee to state that the arm can use the entire sphere when the cart is far and as the cart comes closer the arm effector moves up to make space. To realise this motion, the cart sends the arm the following information with $\mathit{arrive}$:\footnote{ For clarity, the type in Figure~\ref{fig:basic-example} omits parameters to messages. Our type system uses predicated refinements to reason about parameters. } its current position $x_i$, its target position $x_f$, and a lower bound $t_{\mathit{ref}}$ on the time it will take to arrive at $x_f$. The footprint for the cart's motion can be specified by $\set{(\mathsf{x}, \mathsf{y}, \mathsf{z}) \mid \mathsf{x} ≤ x_0 + l/2 + (x_1 - x_0) * t / t_{\mathit{ref}} ∧ … }$. For the producer, suppose $R_{\mathit{base}}$ is the radius of its base and $x_{{\color{roleColor}{\mathsf{Prod}}}}$ its $x$ coordinate. The footprint of the $\mathsf{work}$ action is strengthened as $\set{(\mathsf{x}, \mathsf{y}, \mathsf{z}) \mid (\mathsf{z} > \min(c t, h) \lor |\mathsf{x} - x_{\color{roleColor}{\mathsf{Prod}}}| ≤ R_{\mathit{base}}) ∧ … }$, where $c ≥ h \cdot |x_0 -l - x_{\color{roleColor}{\mathsf{Prod}}} - R_{\mathit{base}}| / t_{\mathit{ref}}$. Finally, for compatibility, we need to check that both ${\color{roleColor}{\mathsf{Cart}}}$ and ${\color{roleColor}{\mathsf{Prod}}}$ can adhere to their footprint and that the footprints are disjoint. Disjointness is satisfied if $x_1 + l < x_{\color{roleColor}{\mathsf{Prod}}} - R_{\mathit{base}}$, set this as a precondition to $\mathsf{m\_move}$. \myparagraph{Environment Assumptions} We can model a more complex cart moving in a dynamic environment by adding a new component (participant) ${\color{roleColor}{\mathsf{Env}}}$ (for \emph{environment}). The physical variables of the environment process encode dynamic properties of the state, such as obstacles in the workspace or external disturbances acting on the cart. We can abstract the environment assumptions into a single motion primitive whose guarantees provide assumptions about the environment behavior to the other components. For example, the environment providing a bounded disturbance of magnitude to the cart's acceleration could be modeled as the guarantee $-1 \leq d \leq 1$ for a physical variable $d$ (for \emph{disturbance}) of ${\color{roleColor}{\mathsf{Env}}}$. The cart can include this input variable in its dynamics: $\dot{v} = u + d$. We can also model sensor and actuator errors in this way. Likewise, we can model obstacles by a physical variable in the environment that denotes the portions of the state space occupied by obstacles, exporting this information through the guarantees, and using this information when the cart plans its trajectory in $\mathsf{m\_move}$. \begin{comment} \RMi{NEED TO FIX FROM HERE} We impose more structured communications by checking the compatibility of assume-guarantee contracts in motion types. Suppose that $\Gmotion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}{\ensuremath{{\sf G}}}$ appears in the global type. This indicates that the specification expects the components ${\sf p}_i$, $i\in I$, to jointly execute motion primitives $\ensuremath{\mathit{a}}_i$. The proof rules of {Sec.}~\ref{sec:motion} provide contracts for each individual motion primitive. Compatibility checks that these contracts can be put together: first, the assumptions and guarantees are compatible; second, there is no ``leftover'' assumption; and third, the footprints of the motion primitives do not intersect in space. The compatibility check is performed bottom up in the tree structure of a program. For this, we introduce the program-level judgement $\pjudgement{\Pi}{\phi,A, G, \psi,\ensuremath{\mathit{FP}}, {\ddagger}}$ extending the judgement $\judgement{{\roleP}\ensuremath{\triangleleft{}} S}{\cdot}$ in Figure~\ref{fig:proof-system} to programs. At the leaves, the program-level judgement holds if the corresponding motion primitive holds: \[ \small \inferrule*[Left=\rulename{HCompBase}]{ \judgement{{\sf p} \ensuremath{\triangleleft{}} S}{φ,A,G,ψ,\ensuremath{\mathit{FP}},D,{\ddagger}} }{ \pjudgement{{\sf p} \ensuremath{\triangleleft{}} S}{φ,A,G,ψ,\ensuremath{\mathit{FP}},D,{\ddagger}} } \] Recursively, the program-level judgement composes the motion primitives: \[ \small \inferrule[\rulename{HComp}] { ∃ \ensuremath{\mathit{FP}}_1, \ensuremath{\mathit{FP}}_2.\\ G₁\wedge G₂ ⇒ \ensuremath{\mathit{FP}}_1 ∩ \mu(\ensuremath{\mathit{FP}}_2) = ∅ \\ G₁ \wedge G₂ ⇒ \ensuremath{\mathit{FP}}_1 ∪ \mu(\ensuremath{\mathit{FP}}_2) ⊆ \ensuremath{\mathit{FP}} \\ {\ddagger}_1 ={\mathsf{\lightning}} \vee {\ddagger}_2 = {\mathsf{\lightning}} \\\\ {\ddagger}_1 ={\mathsf{\rightsquigarrow}} ⇒ D₁ ⊆ D₂ \\ {\ddagger}_2 ={\mathsf{\rightsquigarrow}} ⇒ D₂ ⊆ D₁ \\\\ \pjudgement{P}{φ₁,A∧\con(G₂),G₁,\ensuremath{\mathit{FP}}_1,ψ₁,D_1,{\ddagger}_1} \\\\ \pjudgement{Q}{\mu^{-1}(φ₂),\mu^{-1}(A∧\con(G₁)),\mu^{-1}(G₂),\ensuremath{\mathit{FP}}_2,\mu^{-1}(ψ₂),D_2,{\ddagger}_2} \\ } {\pjudgement{\comp{P}{\con}{\mu}{Q}}{φ₁∧φ₂,A,G₁∧G₂,\ensuremath{\mathit{FP}},ψ₁∧ψ₂,D₁∩D₂,{\ddagger}_1\oplus{\ddagger}_2}} \] There are three checks. First, the check on footprints ensures that the motion primitives are disjoint in space (there is a way to find subsets $\ensuremath{\mathit{FP}}_1$ and $\ensuremath{\mathit{FP}}_2$ of the footprint $\ensuremath{\mathit{FP}}$ so that the composed motion primitives are in these disjoint portions). Second, the guarantee of one motion primitive is used as the assumption of the other to check that they are compatible. Third, at most one process executes a non-interruptible motion primitive. We say $\Gmotion{\dtsess}{({\sf p}_i {:} \ensuremath{\mathit{a}}_i)}{\ensuremath{{\sf G}}}$ is \emph{compatible} if $\pjudgement{\Pi}{\kf{true}, \kf{true}, \cdot, \cdot, \ensuremath{\mathit{FP}}, {\ddagger}}$ is derivable using these rules. Note that the composition rule restricts the use of joint motion primitives to the common case that at most one component executes a non-interruptible motion primitive while the others execute interruptible ones. This is sufficient for a number of common robotics coordination case studies \cite{PGCD}, e.g., our running example. A more complex rule that allows multiple non-interruptible trajectories that require different execution times would additionally track the minimum and maximum durations of trajectories but we prefer our current rule for simplicity. Theorem~\ref{th:motion-compatibility} below lifts Theorem~\ref{th:motion-soundness} to programs using (\rulename{HComp}) to combine processes. \begin{theorem}[Compatibility] \label{th:motion-compatibility} Let $\pjudgement{P}{\phi,A,G,ψ,\ensuremath{\mathit{FP}}, {\ddagger}}$. For any $\rbtstate{P}{\sstore{X}_0}{\sstore{W}_0}{\sstore{V}_0}$, if $\sstore{X}_0, \sstore{W}_0, \sstore{V}_0$ satisfies $\phi$ then for all $\rbtstate{P_1}{\sstore{X}_1}{\sstore{W}_1}{\sstore{V}_1}$ $n$-reachable from $\rbtstate{P}{\sstore{X}_0}{\sstore{W}_0}{\sstore{V}_0}$ under $A$ for some hyperinteger $n\geq 0$, we have $\sstore{X}_1$ satisfies $G[n\cdot\ensuremath{\mathsf{dt}}\xspace/\ensuremath{\mathsf{clock}}\xspace]$ and one of the following holds. \begin{enumerate} \item There is no $\rbtstate{P_2}{\sstore{X}_2}{\sstore{W}_2}{\sstore{V}_2}$ such that $\rbtstate{P_1}{\sstore{X}_1}{\sstore{W}_1}{\sstore{V}_1} \rightarrow \rbtstate{P_2}{\sstore{X}_2}{\sstore{W}_2}{\sstore{V}_2}$ and $\sstore{X}_1,\sstore{W}_1,\sstore{V}_1$ satisfies $\psi$. \item For every $\rbtstate{P_1}{\sstore{X}_1}{\sstore{W}_1}{\sstore{V}_1} \xrightarrow{\tau} \rbtstate{P_2}{\sstore{X}_2}{\sstore{W}_2}{\sstore{V}_2}$ we have $\sstore{X}_2$ satisfies $G[n\cdot \ensuremath{\mathsf{dt}}\xspace/\ensuremath{\mathsf{clock}}\xspace]$ and $\geom{{\roleP}}(\sstore{X}_2,\sstore{V}_2)\subseteq \ensuremath{\mathit{FP}}[n \cdot \ensuremath{\mathsf{dt}}\xspace/\ensuremath{\mathsf{clock}}\xspace]$; and for every $\rbtstate{P_1}{\sstore{X}_1}{\sstore{W}}{\sstore{V}} \xrightarrow{\ensuremath{\mathsf{dt}}\xspace} \rbtstate{P_2}{\sstore{X}_2}{\sstore{W}_2}{\sstore{V}_2}$ we have $\sstore{X}_2$ satisfies $G[(n+1)\cdot \ensuremath{\mathsf{dt}}\xspace/\ensuremath{\mathsf{clock}}\xspace]$ and $\geom{{\roleP}}(\sstore{X}_2,\sstore{V}_2)\subseteq \ensuremath{\mathit{FP}}[(n+1) \cdot \ensuremath{\mathsf{dt}}\xspace/\ensuremath{\mathsf{clock}}\xspace]$. \end{enumerate} \end{theorem} \end{comment} \section{Motion Choreographies} \label{sec:proof-system} In this section, we develop a multiparty session typing discipline to prove communication safety and collision freedom. Our session types extend usual multiparty session types by introducing new operators and by reasoning about joint motion in real-time. Moreover, as message exchanges can be a proxy to exchange permissions for motion primitives, our types have predicates as guards in order to model permissions for motion primitives. \subsection{Global Types with Motions and Predicates} \label{subsec:global} We start with a choreography given as a \emph{global type}. The global type constrains the possible sequences of messages and controller actions that may occur in any execution of the system. We extend \cite{ECOOP19} by framing and predicate refinements, together with separation conjunctions. {\em Sorts}, ranged over by $\ensuremath{{\sf S}},$ are used to define base types: \[\ensuremath{{\sf S}} \quad::=\quad \mathtt{unit} \ensuremath{~~\mathbf{|\!\!|}~~ } \mathtt{real} \ensuremath{~~\mathbf{|\!\!|}~~ } \text{\sf{point}}(ℝ³) \ensuremath{~~\mathbf{|\!\!|}~~ } \text{\sf{vector}} \ensuremath{~~\mathbf{|\!\!|}~~ } \ldots \ensuremath{~~\mathbf{|\!\!|}~~ } \ensuremath{{\sf S}}\times \ensuremath{{\sf S}}\] A \emph{predicate refinement} is of the form $\set{\nu : \ensuremath{{\sf S}}\mid \mathcal{P}}$, where $\nu$ is a \emph{value variable} not appearing in the program, $\ensuremath{{\sf S}}$ a sort, and $\mathcal{P}$ a Boolean predicate. Intuitively, a predicate refinement represents assumptions on the state of the sender and the communicated value to the recipient. We write $\ensuremath{{\sf S}}$ as abbreviation for $\set{\nu: \ensuremath{{\sf S}}\mid\kf{true}}$ and $\mathcal{P}$ for $\set{\nu:\ensuremath{{\sf S}}\mid \mathcal{P}}$ if $\ensuremath{{\sf S}}$ is not important. \begin{definition}[Global types] \label{def:global-types}% {\em Global types} ($\ensuremath{{\sf G}}, \ensuremath{{\sf G}}', ...$) are generated by the following grammar: \[ \begin{array}{rcl} \ensuremath{{\sf G}} & ::= & % \ensuremath{g}.\ensuremath{{\sf G}} \;\ensuremath{~~\mathbf{|\!\!|}~~ }\; \mathbf{t} \;\ensuremath{~~\mathbf{|\!\!|}~~ }\; \mu \mathbf{t}.\ensuremath{{\sf G}} \\[1mm] \ensuremath{g} & ::= & \motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}\;\ensuremath{~~\mathbf{|\!\!|}~~ }\; \GvtPre{{\sf p}}{\pq}{[\mathcal{P}]\ell}{\set{\nu:\ensuremath{{\sf S}}\mid\mathcal{P}'}} \; \ensuremath{~~\mathbf{|\!\!|}~~ } \; \ensuremath{g}.\ensuremath{g} \;\ensuremath{~~\mathbf{|\!\!|}~~ }\; \ensuremath{g} + \ensuremath{g} \;\ensuremath{~~\mathbf{|\!\!|}~~ }\; \ensuremath{g} \ensuremath{\ast} \ensuremath{g} \end{array} \] where ${\sf p}, \pq$ range over $\ensuremath{\Bbb P}$, $\ensuremath{\mathit{a}}_i$ range over abstract motion primitives, and $\mathcal{P}_i, \mathcal{P}'$ range over predicates. $\ensuremath{g}$ corresponds to the prefix of global types where we do not allow the recursion. We require that ${\sf p} \neq \pq$, $I \neq \emptyset$, $\ensuremath{\mathit{fv}}(\mathcal{P}_i) ⊆ {\sf p}.X ∪ {\sf p}.W$, $\ensuremath{\mathit{fv}}(\mathcal{P}'_i) ⊆ {\sf p}.X ∪ {\sf p}.W ∪ \set{\nu}$, and $\ell_i \neq \ell_j$ whenever $i \neq j,$ for all $i,j\in I$. We postulate that recursion is guarded and recursive types with the same regular tree are considered equal. We omit the predicate annotation if the predicate is $\kf{true}$ or not important. \end{definition} In Definition~\ref{def:global-types}, the main syntax follows the standard definition of global types in multiparty session types \cite{KY13,KY2015,DGJPY15}, with the inclusion of more flexible syntax of choreographies (\emph{separation} $\ensuremath{g} \ensuremath{\ast} \ensuremath{g}$, \emph{sequencing} $\ensuremath{g}.\ensuremath{g}$ and summation $\ensuremath{g} + \ensuremath{g}$) and \emph{motion} primitive $\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}$ extended from \cite{ECOOP19}, and branching $\GvtPre{{\sf p}}{\pq}{[\mathcal{P}]\ell}{\set{\nu:\ensuremath{{\sf S}}\mid\mathcal{P}'}}$. The motion primitive explicitly declares a \emph{synchronisation} by AG contracts among all the participants ${\sf p}_i$. The {\em branching} type formalises a protocol where participant ${\sf p}$ first tests if the guard $[\mathcal{P}]$, then sends to ${\sf q}$ one message with label $\ell$ and a value satisfying the predicate refinement $\mathcal{P}'$. Recursion is modelled as $\mu\mathbf{t}.\ensuremath{{\sf G}}$, % where variable $\mathbf{t}$ is bound and guarded in $G$, e.g., $\mu\mathbf{t}.\mathbf{t}$ is not a valid type. Following the standard session types, in $\ensuremath{g}_1 + \ensuremath{g}_2 + ... + \ensuremath{g}_n$, we assume: $g_i = \GvtPre{{\sf p}}{\pq}{[\mathcal{P}_i]\ell_i}{\set{\nu:\ensuremath{{\sf S}}\mid\mathcal{P}'_i}}.g_i'$ and $\ell_i \not=\ell_j$; and similarly for $\ensuremath{{\sf G}}$. By this rule, hereafter we write: $\Gvti{{\sf p}}{{\sf q}}{[\mathcal{P}_i]\ell}{\mathcal{P}'}{\ensuremath{{\sf G}}}$, combining summations and branchings and putting $\ensuremath{{\sf G}}$ in the tail into each branching as the standard multiparty session types. $\participant{\ensuremath{{\sf G}}}$ denotes a set of participants appeared in $\ensuremath{{\sf G}}$, inductively defined by $\participant{\motion{\dtsess}{({\sf p}_1{:}\ensuremath{\mathit{a}}_1,\ldots,{\sf p}_k{:}\ensuremath{\mathit{a}}_k)}} = \set{{\sf p}_1,\ldots,{\sf p}_k}$ and $\participant{\GvtPre{{\sf p}}{\pq}{\ell_i[\mathcal{P}]}{\set{\nu:\ensuremath{{\sf S}}\mid\mathcal{P}'}}}=\{{\sf p},\pq\}$ with other homomorphic rules. A ``separating conjunction'' $\ensuremath{\ast}$ allows us to reason about subsets of participants. It places two constraints on the processes and motion primitives on the two sides of $\ensuremath{\ast}$: first, there should not be any communication that crosses the boundary and second, the motion primitives executed on one side should not be coupled (through physical inputs) with motion primitives on the other. We call $\ensuremath{g}_1 \ensuremath{\ast} \ensuremath{g}_2$ \textbf{\emph{fully-separated}} if $\participant{\ensuremath{g}_1} \cap \participant{\ensuremath{g}_2} = \emptyset$, there exist $\ensuremath{\mathit{FP}}_1$, $\ensuremath{\mathit{FP}}_2$ with $\ensuremath{\mathit{FP}}_1\cap \ensuremath{\mathit{FP}}_2 = \emptyset$, and for every motion primitive $\judgement{\ensuremath{\mathit{a}}}{\ensuremath{\mathrm{Pre}\xspace},A, G,\ensuremath{\mathrm{Post}\xspace}, \ensuremath{\mathit{FP}}, D,{\ddagger}}$ in $\ensuremath{g}_i$, we have $A$ depends only on state variables in $\participant{\ensuremath{g}_i}$ and for all $t$, $\ensuremath{\mathit{FP}}\{t/\ensuremath{\mathsf{clock}}\xspace\} \subseteq \ensuremath{\mathit{FP}}_i\{t/\ensuremath{\mathsf{clock}}\xspace\}$, for $i\in\set{1,2}$. $\ensuremath{{\sf G}}$ is \textbf{\emph{fully-separated}} if each $\ensuremath{g}_1 \ensuremath{\ast} \ensuremath{g}_2$ in $\ensuremath{{\sf G}}$ is fully-separated. Our global type does not include an $\mathtt{end}$ type. An $\mathtt{end}$ introduces an implicit global synchronisation that requires all components to finish exactly at the same time. Informally, ``ending'' a program is interpreted as robots stopping their motion and staying idle forever (by forever executing an ``idle'' primitive). Our progress theorem will show that well-typed programs have infinite executions. \myparagraph{Data Flow Analysis on Choreographies} Not every syntactically correct global type is meaningful. We need to check that the AG contracts work together and that the sends and receive work w.r.t the time taken by the different motions. These checks can be performed as a ``dataflow analysis'' on the tree obtained by unfolding the global type. We start with a few definitions and properties. \textbf{\emph{Well-scopedness.}} Consider the unfolding of a global type $\ensuremath{{\sf G}}$ as a tree. The leaves of the tree are labeled with motions $\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}$ or message ${\sf p}\to\pq$, and internal nodes are labeled with the operators $.$, $\ensuremath{\ast}$, or $+$. By our assumption, we decorate each $+$ node with the sender and receiver ${\sf p}\to\pq$ below it. We say the tree is \textbf{\emph{well-scoped}} if there is a way to label the nodes of the tree following the rules below: (1) The root is labeled with the set $\ensuremath{\Bbb P}$ of all participants. (2) If a ``.'' node labeled with $\ensuremath{\Bbb P}'$, both its children are also labeled with $\ensuremath{\Bbb P}'$, if possible. (3) If a ``+'' node associated with a message exchange ${\sf p}\to\pq$ is labeled with $\ensuremath{\Bbb P}'$, and both ${\sf p},\pq\in \ensuremath{\Bbb P}'$, then each of its children are also labeled with $\ensuremath{\Bbb P}'$, if possible. (4) If a ``\ensuremath{\ast}'' node is labeled with $\ensuremath{\Bbb P}'$, then we label its children with $\ensuremath{\Bbb P}_1$ and $\ensuremath{\Bbb P}_2$ such that $\ensuremath{\Bbb P}_1 \cap \ensuremath{\Bbb P}_2 = \emptyset$ and $\ensuremath{\Bbb P}_1 \cup \ensuremath{\Bbb P}_2 = \ensuremath{\Bbb P}'$. (5) A leaf node $\motion{\dtsess}{{\roleP}_i:\ensuremath{\mathit{a}}_i}$ is labeled with $\ensuremath{\Bbb P}'$ if all ${\roleP}_i$ are in $\ensuremath{\Bbb P}'$, otherwise the labeling fails. (6) A leaf node ${\sf p} \to \pq$ is labeled with $\ensuremath{\Bbb P}'$ if both ${\sf p}, \pq$ are in $\ensuremath{\Bbb P}'$, otherwise the labeling fails. Such a scope labeling is unique if the global type is fully-separated and no participant is ``dropped,'' and so we can define the scope of a node in an unambiguous way. \textbf{\emph{Unique minimal communication}.}\ We first define a notion of \emph{happens-before} with \emph{events} as nodes labeled with motions $\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}$ or message exchanges ${\sf p}\to \pq$. We define a \emph{happens before} relation on events as the smallest strict partial order such that: there is an edge $n:e \to n':e'$ if there is an internal node $n^*$ in the tree labeled with $.$ and $n$ is in the left subtree of $n^*$ and $n'$ is in the right subtree of $n^*$, and one of the following holds: (1)~$e \equiv {\sf p}\to\pq$, $e' \equiv {\sf p}'\to\pq'$ and ${\sf p}'$ is either ${\sf p}$ or $\pq$; or (2)~$\participant{e} \cap \participant{e'} \not = \emptyset$. We say there is an \emph{immediate happens before} edge $n\to n'$ if $n\to n'$ is in the happens before relation but there is no $n''$ such that $n \to n''$ and $n''\to n'$. A global type has \textbf{\emph{unique minimal communication}} after motion iff every motion node $n:\motion{\dtsess}{{\sf p}_i:\ensuremath{\mathit{a}}_i}$ has a \emph{unique} immediate happens before edge to some node $n':{\sf p}\to\pq$. \textbf{\emph{Sender readiness}.}\ Consider now a type with unique minimal communication after motion and consider the unique immediate happens before edge $n:\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)} \to n':({\sf p}\to\pq)$. Suppose ${\sf p}$ is among the processes executing the motion primitives. Since the motion primitives are assumed to be compatible, we know that at most one process is executing a non-interruptible motion, and all the others are executing interruptible motions. Since ${\sf p}$ is the next process to send a message, we must ensure that it is the unique process executing the non-interruptible motion. Compatibility ensures that the durations of all other processes are such that they are ready to receive the message from ${\sf p}$. We call this condition \textbf{\emph{sender readiness}}: whenever there is a communication after a motion, the sender of the communication was the unique participant executing a non-interruptible motion; or every process in the motion was executing an interruptible motion. On the other hand, if ${\sf p}$ is not among the processes (this can happen when to parallel branches merge), every participant in the motion must have been executing an interruptible motion. \textbf{\emph{Total synchronisation}.}\ It is not enough that ${\sf p}$ sends a message to only one other participant: if ${\sf p}$ and $\pq$ decide to switch to a different motion primitive, every other participant in scope must also be informed. This is ensured by the \textbf{\emph{total synchronisation}} between motions: we require that whenever there is a happens before edge between $n:\motion{\dtsess}{({\sf p}_i:\ensuremath{\mathit{a}}_i)}$ to $n':\motion{\dtsess}{({\sf p}'_i:\ensuremath{\mathit{a}}'_i)}$, then for every ${\sf p}_i$, there is a node where ${\sf p}_i$ is a sender or a recipient that happens before $n'$. \textbf{\emph{Synchronisability}.} \ We call a global type is \textbf{\emph{synchronisable}} if it satisfies unique minimal communication, sender readiness, and total synchronisation. Synchronisability of a global type can be checked in time polynomial in the size of the type by unfolding each recursive type once. \begin{example}[Synchronisability] \rm We illustrate the synchronisability condition. In general, a node can have multiple outgoing immediate happens before edges. Consider, for distinct participants ${\sf p},\pq,{\sf p}'$, the type ${{\sf p}}\rightarrow {\pq}:{\ell}. {{\sf p}'}\rightarrow {\pq}:{\ell'}.\ensuremath{{\sf G}}$. The minimal senders are ${\sf p}$ and ${\sf p}'$, because these two sends cannot be uniquely ordered in an execution. We avoid such a situation because in a process $\pq$ we would not know whether to expect a message from ${\sf p}$ or from ${\sf p}'$ or from both. Note that synchronisability disallows a sequence of two motions without an intervening message exchange. Thus, $\motion{\dtsess}{({\sf p}{:}\ensuremath{\mathit{a}}_1,\pq{:}\ensuremath{\mathit{a}}_1')}.\motion{\dtsess}{({\sf p}{:}\ensuremath{\mathit{a}}_2, \pq{:}\ensuremath{\mathit{a}}_2')}.\ensuremath{{\sf G}}$ is not well-formed. This is because the implementation of the participants do not have any mechanism to synchronize when to shift from the first motion primitive to the second. We require the total synchronisation between motions to notify every participant by some message between any change of motion primitives. We disallow the type $\motion{\dtsess}{({\sf p}{:}\ensuremath{\mathit{a}}_{11},{\sf q}{:}\ensuremath{\mathit{a}}_{12}, {\sf r}{:}\ensuremath{\mathit{a}}_{13})}.{{\sf p}}\rightarrow{{\sf q}}:\ell.\motion{\dtsess}{({\sf p}{:}\ensuremath{\mathit{a}}_{21}, {\sf q}{:}\ensuremath{\mathit{a}}_{22}, {\sf r}{:}\ensuremath{\mathit{a}}_{23})}.\ensuremath{{\sf G}}$. because ${\sf r}$ does not know when to shift from $\ensuremath{\mathit{a}}_{13}$ to $\ensuremath{\mathit{a}}_{23}$. Note however, that the scoping introduced by $\ensuremath{\ast}$ requires messages to be sent only to ``local'' subgroups. The following type is fine, even though ${\sf p}_3$ was not informed when ${\sf p}_1$ and ${\sf p}_2$ changed motion primitives, as it is in a different branch and there is no happens before edge: \begin{align*} \left(( \begin{array}{l} % (\motion{\dtsess}{({\sf p}_1{:}\ensuremath{\mathit{a}}_1, {\sf p}_2{:}\ensuremath{\mathit{a}}_2)}. {{\sf p}_1}\rightarrow{{\sf p}_2}:{\ell_1}. \motion{\dtsess}{({\sf p}_1{:}\ensuremath{\mathit{a}}_1',{\sf p}_2{:}\ensuremath{\mathit{a}}_2')}) \end{array} ) \ensuremath{\ast} \motion{\dtsess}{{\sf p}_3{:}\ensuremath{\mathit{a}}_3} \right) .{{\sf p}_1}\rightarrow{{\sf p}_2}{:\ell_1}.{{\sf p}_1}\rightarrow{{\sf p}_3}{:\ell_3}.G \end{align*} \end{example} \begin{example}\rm By inspection, the motion type in Figure~\ref{fig:basic-example} is well-scoped and fully separated. It is also synchronizable: to see this, note that for every joint motion primitive, there is at most one motion which is non-interruptible and the participant corresponding to that motion primitive is the unique minimal sender. Moreover, the unique minimal sender sends messages to every participant in the scope of the separating conjunction, thus the type is totally synchronized. \end{example} We are ready to define when global types are well-formed. \begin{definition}[Well-formed global types] \label{def:well-formed} A global type $\ensuremath{{\sf G}}$ is \emph{well-formed} if it satisfies the following conditions: \begin{enumerate} \item \emph{Total choice:} for each branching type $\Gvti{{\sf p}}{\pq}{[\mathcal{P}_i]\ell}{\mathcal{P}'}{G}$, we have $\bigvee_i \mathcal{P}_i$ is valid. \item \emph{Well-scoped:} $\ensuremath{{\sf G}}$ is well-scoped and fully-separated. \item \emph{Total and compatible motion:} For every motion type $\motion{\dtsess}{({\sf p}_i {:} \ensuremath{\mathit{a}}_i)}$, there exists a motion primitive for each participant in scope and moreover the tuple of motion primitives $({\sf p}_i{:}\ensuremath{\mathit{a}}_i)$ is compatible. \item \emph{Synchronisability:} The global type is synchronisable. \end{enumerate} \end{definition} \noindent Hereafter we assume global types are well-formed. \begin{restatable}[Well-formedness]{proposition}{theoremWF} \label{pro:WF} Synchronisability is decidable in polynomial time. Checking well-formedness of global types reduces to checking validity in the underlying logic of predicates in global types and motion primitives. \end{restatable} \begin{proof} All causalities in global types can be checked when unfolding each recursive type once (cf.~\cite[{Sec.}.~3.5]{HYC2016}). Hence synchronisability of a global type can be checked in time polynomial in the size of the type by checking unique minimum communication, sender readiness and total synchronisation simultaneously. By Definition \ref{def:well-formed}, checking well-formedness depends on checking validity in the underlying logic. \end{proof} \subsection{Local Types and Projection} \label{sec:local} Next, we project global types to their end points against which each end-point process is typed. The syntax of \emph{local types} extends local types from \cite{ECOOP19}. Each local type represents a specification for each component. \begin{definition}[Local motion session types] \label{def:session-types}% The grammar of local types, ranged over by $T$, is: \begin{align*} T ::= \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \ensuremath{~~\mathbf{|\!\!|}~~ } \oplus\{[\mathcal{P}_i]\tout\pq{\ell_i}{\mathcal{P}_i'}.T_i\}_{i\in I} \ensuremath{~~\mathbf{|\!\!|}~~ } \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i}.T_i\}_{i\in I} \ensuremath{~~\mathbf{|\!\!|}~~ } \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i}.T_i\}_{i\in I}\ \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \ensuremath{~~\mathbf{|\!\!|}~~ } \mu \mathbf{t}.T \ensuremath{~~\mathbf{|\!\!|}~~ } \mathbf{t} \end{align*} where $\ensuremath{\mathit{a}}$ ranges over motion primitives. We require that $\ell_i \neq \ell_j$ whenever $i \neq j$, for all $i,j\in I$. We postulate that recursion is always guarded. Unless otherwise noted, types are closed. \end{definition} Our goal is to \emph{project} a global type onto a participant to get a local type. To define this notion formally, we first need the following definition that merges two global types. \begin{definition}[Merging] \label{def:merge}% We define a \emph{merging operator} $\bigsqcap$, which is a partial operation over global types, as: \[ \small \textstyle% T_1 \mathbin{\bigsqcap} T_2 \;=\; % % \left\{% \text{% \begin{tabular}{@{\hskip 0mm}l} $T_1$ \hfill if $T_1 = T_2$ \hspace{2mm} \iftoggle{full}{$\rulename{mrg-id}$}{} \\[2mm]% $\&\{\tin{{\sf p}'}{\ell_k}{\mathcal{P}_k}{.T_k}\}_{k \in I \cup J}$ \quad\quad \hfill if \(% \left\{% \begin{array}{l} T_1 = \&\{ \tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \hfill \text{ and}\\% T_2 = \&\{ \tin{{\sf p}'}{\ell_j}{\mathcal{P}_j}{.T_j}\}_{j \in J}% \end{array} \right.% \)\\[3mm] \iftoggle{full}{\hfill $\rulename{mrg-bra1}$\\}{} $\&\{\tin{{\sf p}'}{\ell_k}{\mathcal{P}_k}{.T_k}\}_{k \in I \cup J} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}} \bigsqcap \ensuremath{\mathit{a}}'}{T'}$ \quad\quad \hfill if \(% \left\{% \begin{array}{l} T_1 = \&\{ \tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'} \hfill \text{ and}\\% T_2 = \&\{ \tin{{\sf p}'}{\ell_j}{\mathcal{P}_j}{.T_j}\}_{j \in J} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'}% \end{array} \right.% \)\\[3mm] \iftoggle{full}{\hfill $\rulename{mrg-bra2}$\\}{} $\&\{\tin{{\sf p}'}{\ell_k}{\mathcal{P}_k}{.T_k}\}_{k \in I \cup J} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'}$ \hfill if \(% \left\{% \begin{array}{l} T_1 = \&\{ \tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \hfill \text{ and} \\ T_2 = \&\{ \tin{{\sf p}'}{\ell_j}{\mathcal{P}_j}{.T_j}\}_{j \in J} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'}% \end{array} \right.% \) \\[3mm] \iftoggle{full}{\hfill $\rulename{mrg-bra3}$\\}{} $\&\{\tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}} \bigsqcap \ensuremath{\mathit{a}}'}{T'}$ \hfill if \(% \left\{% \begin{array}{l} T_1 = \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'} \hfill \text{ and} \\% T_2 = \&\{ \tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'}% \end{array} \right.% \) \\[3mm] \iftoggle{full}{\hfill $\rulename{mrg-bra4}$\\}{} $\&\{\tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'}$ \hfill if \(% \left\{% \begin{array}{l} T_1 = \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'} \hfill \text{ and} \\% T_2 = \&\{ \tin{{\sf p}'}{\ell_j}{\mathcal{P}_j}{.T_j}\}_{i \in I}% \end{array} \right. % \) \\[3mm] \if{\hfill $\rulename{mrg-bra5}$\\}\else{}\fi $T_2 \mathbin{\bigsqcap} T_1$ \hfill if $T_2 \mathbin{\bigsqcap} T_1$ is defined, \\[2mm] undefined \hfill otherwise. \end{tabular} } % \right.% \] % The merge operator for motion $\ensuremath{\mathit{a}} \bigsqcap \ensuremath{\mathit{a}}'$ returns a motion primitive $\ensuremath{\mathit{a}}''$ such that $\ensuremath{\mathit{a}}'' \ensuremath{\preceq} \ensuremath{\mathit{a}}$ and $\ensuremath{\mathit{a}}'' \ensuremath{\preceq} \ensuremath{\mathit{a}}'$. We can build such $\ensuremath{\mathit{a}}''$ by taking the union of the assumptions and precondition and the intersection of the guarantees, postcondition, and footprint. \end{definition} \begin{definition}[Projection] \label{pro}% \label{def:projection}% The \emph{projection of a global type onto a participant ${\sf r}$} is the largest relation $\proj{}{{\sf r}}{}$ between global and session types such that, whenever $\proj{\ensuremath{{\sf G}}}{{\sf r}}{T}$: \begin{enumerate} \item if ${\ensuremath{{\sf G}}}=\Gvti{{\sf p}}{{\sf r}}{[\mathcal{P}_i]\ell}{\mathcal{P}'}{\ensuremath{{\sf G}}}$ then ${T}=\&\{ \tin{\sf p}{\ell_i}{\mathcal{P}'_i}.{T_i}\}_{i\in I}$ with $\proj{\ensuremath{{\sf G}}_i} {\sf r} T_i$; \item if ${\ensuremath{{\sf G}}}=\Gvti{{\sf r}}{\pq}{[\mathcal{P}_i]\ell}{\mathcal{P}'}{\ensuremath{{\sf G}}}$ then ${T}= \oplus\{[\mathcal{P}_i]\tout{\sf q}{\ell_i}{\mathcal{P}'_i}.{T_i}\}_{i\in I} $ and $\proj{\ensuremath{{\sf G}}_i}{\sf r} T_i,$ $\forall i \!\in\! I$; \item if ${\ensuremath{{\sf G}}}=\Gvti{{\sf p}}{{\sf q}}{[\mathcal{P}_i]\ell}{\mathcal{P}'}{\ensuremath{{\sf G}}}$ and ${\sf r} \!\not\in\! \{{\sf p},{\sf q}\}$ then there are $T_{\!i},$ $i \in I$ s.t. ${T} = \bigsqcap_{i \in I}\!\!{T_{\!i}}$, and $\proj{\ensuremath{{\sf G}}_i\!}{{\sf r}}{\!T_{\!i}},$ for every $i\in I$; \item if $\ensuremath{{\sf G}} = \mu\mathbf{t}. \ensuremath{{\sf G}}'$ then $T=\mu\mathbf{t}.T'$ with $\proj{\ensuremath{{\sf G}}'}{\sf r} T'$ if ${\sf r}$ occurs in $\ensuremath{{\sf G}}'$, otherwise undefined; and \item if $\ensuremath{{\sf G}} = \ensuremath{g}. \ensuremath{{\sf G}}$ then $T=T' . T''$ with $\proj{\ensuremath{g}}{{\sf r}}{T'}$ and $\proj{\ensuremath{{\sf G}}}{{\sf r}}{T''}$.\footnote{We abuse $T$ to denote \emph{a local type prefix} which is given replacing $\mathbf{t}$ and $\mu\mathbf{t}.T$ by $\ensuremath{\epsilon}$ (as defined for global type prefix $g$).} \item $\proj{\motion{\dtsess}{({\sf p}_i {:} \ensuremath{\mathit{a}}_i)}}{{\sf r}}{ \motion{\dtsess}{a_j}}$ with ${\sf r} = {\sf p}_j$; \item $\proj{(\ensuremath{g}_1 \ensuremath{\ast} \ensuremath{g}_2)}{{\sf r}}{\ensuremath{T}_i}$ and $\proj{\ensuremath{g}_i}{{\sf r}}{\ensuremath{T}_i}$ if ${\sf r} \in \participant {\ensuremath{g}_i}$ ($i\in \{1,2\}$) \item $\proj{\ensuremath{g}_1.\ensuremath{g}_2}{{\sf r}}{\ensuremath{T}_1.\ensuremath{T}_2}$ with $\proj{\ensuremath{g}_i}{{\sf r}}{\ensuremath{T}_i}$ ($i=1,2$) \end{enumerate} We omit the cases for recursions and selections (defined as \cite[Section~3]{SY2019}). The branching prefix is defined as the branching in (1-3). \end{definition} \begin{example}[Projection of Figure~\ref{fig:basic-example}]\rm For the example from {Sec.}~\ref{sec:example}, the local type of the cart is: \begin{align*} \small \mu \mathbf{t}.\left( \begin{array}{l} \ ({\color{roleColor}{\mathsf{GRobot}}}!\mathit{arrive}(t).{\color{roleColor}{\mathsf{RRobot}}}!\mathit{free}.\\ \ \ \motion{\dtsess}{\mathsf{m\_move}({\color{roleColor}{\mathsf{GRobot}}})}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{ready}. \motion{\dtsess}{\mathsf{m\_idle}}.{\color{roleColor}{\mathsf{GRobot}}}?\mathit{ok}.\motion{\dtsess}{\mathsf{m\_move}}) \\ \& \ ({\color{roleColor}{\mathsf{RRobot}}}!\mathit{arrive}(t).{\color{roleColor}{\mathsf{GRobot}}}!\mathit{free}. \ldots \text{symmetric} \ldots)\ \end{array} \right).\mathbf{t} \end{align*} \end{example} \subsection{Subtyping and Typing Processes} The local types are a specification for the processes and there is some freedom to implement these specifications. The subtyping relation helps bridge the gap between the specification and the implementation. \begin{definition}[Subtyping] \label{def:subt}% \label{tab:sync:subt}% {\em Subtyping} $\leqslant$ is the largest relation between session types coinductively defined by rules in Figure~\ref{fig:subtyping}. \end{definition} \begin{figure}[t] \[ \small \begin{array}{@{}c@{}} \cinferrule[\rulename{sub-motion}]{ \ensuremath{\mathit{a}} \ensuremath{\preceq} \ensuremath{\mathit{a}}' \\ T \leqslant T' }{ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'} }\quad \cinferrule[\rulename{sub-out}]{ \forall i\in I.\ \mathcal{P}_i ⇒ \mathcal{P}''_i ∧ \mathcal{P}'_i ⇒ \mathcal{P}'''_i ∧ T_i \leqslant T'_i }{ \oplus\{[\mathcal{P}_i]\tout{\sf p}{\ell_i}{\mathcal{P}'_i}.T_i\}_{i\in I} \leqslant \oplus\{[\mathcal{P}''_i]\tout{\sf p}{\ell_i}{\mathcal{P}_i'''}.T_i'\}_{i\in I\cup J} } \\[5mm] \cinferrule[\rulename{sub-in1}]{ \forall i\in I.\ \mathcal{P}_i' ⇒ \mathcal{P}_i ∧ T_i \leqslant T_i' \\ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'} }{ \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i}.T_i\}_{i\in I\cup J} \ \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i'}.T_i'\}_{i\in I}\ \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'} } \\[5mm] \cinferrule[\rulename{sub-in2}]{ \forall i\in I.\ \mathcal{P}_i' ⇒ \mathcal{P}_i ∧ T_i \leqslant T_i'}{ \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i}.T_i\}_{i\in I\cup J}\ \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i'}.T_i'\}_{i\in I} } \quad \cinferrule[\rulename{sub-in3}]{ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'} }{ \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i}.T_i\}_{i\in I}\ \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'} } \end{array} \] \caption{Subtyping rules\label{fig:subtyping}} \end{figure} A subtype has fewer requirements and provide stronger guarantees. The subtyping of motion primitives (\rulename{sub-motion}) allows replacing an abstract motion primitive by a concrete one if $\ensuremath{\mathit{a}}$ refines $\ensuremath{\mathit{a}}'$ and $T \leqslant T'$. For internal choice and sending (\rulename{sub-out}), the subtyping ensure the all the messages along with the associated predicate are allowed by the supertype. Predicate refinements are converted to logical implication. For the external choice and message reception (\rulename{sub-in1,2,3}), subtyping makes sure the process reacts properly to the messages expected by the super type. A subtype can have cases for more messages but they don't matter. The subtype guarantees that the process will never receive theses messages. On the other hand, the sender of the messages has to be the same. We enforce this directly in the syntax of the programming language and the type system. It may seem that (\rulename{sub-in3}) introduces a new sender in the subtype but this rule is correct because, in our synchronous model, sending is blocking and cannot be delayed. Therefore, if the supertype only contains a motion, we know for a fact that no messages can arrive unexpectedly in the subtype. Our subtyping conditions generalise those of motion session types of \citet{ECOOP19} in multiple ways. First, we allow refinement of motion primitives (\rulename{sub-motion}) as a way to abstract trajectories. In \cite{ECOOP19}, the actions are abstract symbols and are fixed statically. Second, the rules for communication must check predicate refinements---in \cite{ECOOP19}, global types did not have refinements. The final step in our workflow checks that the process of each participant in a program implements its local type using the typing rules from Table~\ref{tab:sync:typing}. Our typing rules additionally maintain a logical context to deal with the predicate refinements \cite{LiquidTypes}. We write $\der{\Gamma,\Sigma}{S}{T}$ to indicate the statement $S$ has type $T$ under the variable context $Γ$ and the logical context $Σ$. $\Gamma$ is the usual typing context; $\Sigma$ is a formula characterising what is known about the state of the system when a process is about to execute. The typing rules are shown in Table~\ref{tab:sync:typing}. \rulename{t-motion} considers $\Sigma$ derives the pre-condition of motion $a$, while $Q$ guarantees its post-condition. \rulename{t-out} assumes $\Sigma$ of $P$ derives a conjunction of the guard and refined predicates declared in types. \rulename{t-choice1} is its dual and \rulename{t-choice2} includes the default motion branch. \rulename{t-cond} is similar with the usual conditional proof rule. \rulename{t-sess} combines well-typed participants each of which follows a projection of some global type $\ensuremath{{\sf G}}$ given assumptions over the initial state $\bigwedge_{i\in I}𝓟_i$ of each participant. We requires the initial state to be collision free as the global types only maintains collision freedom. \begin{table}[t] \caption{\label{tab:sync:typing} Typing rules for motion processes.} \centerline{$ \small \begin{array}{c} \inferrule[\rulename{t-sub}]{ \der{\Gamma,\Sigma}{\ensuremath{{P}}}T \quad T\leqslant T' }{ \der{\Gamma,\Sigma}{\ensuremath{{P}}}T' } \qquad \inferrule[\rulename{t-rec}]{\der{\Gamma\cup\set{{\roleVar}:T},\kf{true}}{\ensuremath{{P}}}{T}}{\der{\Gamma,\Sigma}{\mu {\roleVar}.\ensuremath{{P}}}T} \qquad \inferrule[\rulename{t-motion}]{ \der{\Gamma,a.\ensuremath{\mathrm{Post}\xspace}}{{Q}}{T}\\ \Sigma \Rightarrow a.\ensuremath{\mathrm{Pre}\xspace}\\ }{\der{\Gamma,\Sigma}{\motion{dt}{a}.{Q}}{\Lmotion{dt}{a}{T}}} \\\\ \inferrule[\rulename{t-out}]{ \Sigma \Rightarrow \mathcal{P}\wedge \mathcal{P}'\set{e/\nu}\\ \der{\Gamma,\Sigma}{\kf{e}}{S}\\ \der{\Gamma,\Sigma}{P}T }{ \der{\Gamma,\Sigma}{{\pq}!{\ell(\kf{e})}.{P}}{[\mathcal{P}]\pq!\ell(\set{\nu: S\mid\mathcal{P}'}).T} } \quad \inferrule[\rulename{t-choice1}]{ \forall i\in I \quad \der{\Gamma\cup\set{x_i:\S_i},\Sigma\wedge \mathcal{P}_i\set{x_i/\nu}}{\ensuremath{{P}}_i}T_i }{ \der{\Gamma,\Sigma}{\sum\limits_{i\in I}{\procin \pq {\ell_i(x_i)} \ensuremath{{P}}_i}}{\&\{\pq?\ell_i(\mathcal{P}_i).T_i}\}_{i\in I} } \\\\ \rulename{t-choice2} \inferrule% { \forall i\in I \quad \der{\Gamma\cup \set{x_i:\S_i},\Sigma\wedge \mathcal{P}_i\set{x_i/\nu}}{\ensuremath{{P}}_i}T_i \quad \der{\Gamma,\Sigma}{\motion{dt}{a}.{Q}}{T} }{ \der{\Gamma,\Sigma}{\sum\limits_{i\in I}{\procin \pq {\ell_i(x_i)} \ensuremath{{P}}_i}+\motion{dt}{a}.{Q}}{\&\{\pq?\ell_i(\set{\nu:S\mid\mathcal{P}_i}).T_i}\}_{i\in I}\ \&\ T } \\\\ \rulename{t-cond} \inferrule% { \der\Gamma\kf{e}\mathtt{bool} \ \exists k \in I \ \Sigma \wedge \kf{e} \Rightarrow \mathcal{P}_k\ \der{\Gamma,\Sigma\wedge \kf{e}}{\ensuremath{{P}}_1}{T_k} \ \der{\Gamma, \Sigma\wedge \lnot \kf{e}}{\ensuremath{{P}}_2}{\oplus\{[\mathcal{P}_i]T_i\}_{i \in I \setminus \{k\}}} }{ \der{\Gamma,\Sigma}{{\cond{\kf{e}}{\ensuremath{{P}}_1}{\ensuremath{{P}}_2}}}{ \oplus\{[\mathcal{P}_i]T_i\}_{i\in I}} } \\\\ \rulename{t-sess} \inferrule% { \forall i\in I\quad\der{∅,𝓟_i}{\ensuremath{{P}}_i}{\projt \ensuremath{{\sf G}} {{{\sf p}_i}}} \\ \participant \ensuremath{{\sf G}} = \ensuremath{\Bbb P} \\ \forall j\in I.\ j≠i ⇒ \geom{{\sf p}_i}(𝓟_i)\cap\geom{{\sf p}_j}(𝓟_j) = \emptyset }{ \der{\bigwedge\limits_{i\in I}𝓟_i}{\prod\limits_{i\in I}\pa {{\sf p}_i}\ensuremath{{P}}_i}\ensuremath{{\sf G}} } \end{array} $} \vspace*{-1em} \end{table} \begin{comment} \RMi{We don't have the process description. I don't know if we should add this in the main text or have it in the appendix.} \begin{example}{(Local Types for Load Transfer)}\label{ex:overview:mpst}\rm \ In our example, the local types for the ${\color{roleColor}{\mathsf{Trolley}}}$, ${\color{roleColor}{\mathsf{Cart}}}$, and ${\color{roleColor}{\mathsf{Crane}}}$ are: \NYi{I commented out the old example} We type check the process (code) from Figure~\ref{fig:cart-crane-code} against these types. \rulename{motion} rule connects the predicate refinements to the motion primitives. The typing of the ${\color{roleColor}{\mathsf{Crane}}}$ uses unfolding and subtyping to go from the type \NYi{I commented out the old example of types} \[ \small \mu \mathbf{t}.\&\left\{ \begin{array}{l} \end{array}\right\}\&\dtsess\tuple{\mathsf{c\_idle}} \] to the type above. \qed \end{example} \end{comment} \subsection{Soundness} The soundness of multiparty sessions is shown, using subject reduction (typed sessions reduce to typed sessions) and progress. In order to state soundness, we need to formalise how global types are reduced when local session types evolve. To define the consumption of global types, as done for processes in {Sec.}~\ref{sec:opsem}, we extend the syntax of global types to allow \emph{partial consumption} of motion types. In addition, we extend $\ensuremath{g}$, annotating each motion type with its unique minimal sender, $\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t}^{{\sf p}}$ for $t\geq 0$. \begin{definition}[Global types consumption and reduction] \label{def:global-type-consumption}% \label{def:global-type-reduction}% The {\em consumption} of the communication ${\sf p}\lts{\ell}\pq$ or motion $\motion{\dtsess}{a}[t_1,t_2]$ % for the global type $\ensuremath{{\sf G}}$ (notation $\redG \ensuremath{{\sf G}}{\sf p}\ell\pq$ and $\redGM{\ensuremath{{\sf G}}}{\motion{\dtsess}{a}[t_1,t_2]}$) % is the global type % defined (up to unfolding of recursive types) using the following rules: \begin{enumerate} \item\label{Item:GC1} $\redG{\big(\GvtPair {\sf p}\pq {{\ell}_i.{\ensuremath{{\sf G}}_i}}\big)}{\sf p}\ell\pq = \ensuremath{{\sf G}}_{k}$ if there exists $k \in I$ with $\ell = \ell_k$; \item\label{Item:GC1} $\redG{\big(\GvtPair {\sf r}{\sf s} {{\ell}_i.{\ensuremath{{\sf G}}_i}}\big)}{\sf p}\ell\pq =\GvtPair {\sf r} {\sf s} {{\ell}_i.{(\redG{\ensuremath{{\sf G}}_i}{{\sf p}}{\ell}{\pq})}}$ if $\{{\sf r}, {\sf s}\} \cap \{{\sf p}, \pq\} = \emptyset$; \item\label{Item:GC3} $\redG{(\ensuremath{g}₁ \ast \ensuremath{g}₂)}{\sf p}\ell\pq = (\ensuremath{g}₁' \ast \ensuremath{g}₂)$ if $\set{{\sf p},\pq}\subseteq \participant{\ensuremath{g}_1}$ and $\redG{\ensuremath{g}₁}{\sf p}\ell\pq = \ensuremath{g}₁'$ and symmetrically if $\set{{\sf p},\pq}\subseteq\participant{\ensuremath{g}_2}$; % \item\label{Item:GC41} $\redGM{\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}} {\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i[t_i;t'_i])}} = \motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT 0}^{\sf p}$ % where ${\sf p}$ is the unique minimal sender in $\ensuremath{{\sf G}}$. \item\label{Item:GC4} $\redGM{\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t}^{\sf p}} {\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i[t_i;t'_i])}} = \motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t'}^{\sf p}$ if $t' > t$ and for all $i$, $t'_i-t_i = t'-t$ and $t' \leq \lceil\ensuremath{\mathit{a}}_i.D\rceil$ where $\lceil D\rceil$ denotes the upper bound of the interval $D$; \item\label{Item:GC5} $\redGM{(\ensuremath{g}₁ \ensuremath{\ast} \ensuremath{g}₂)} {\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i[t_i;t'_i])_{{\sf p}_i∈ \participant{\ensuremath{g}_1} \uplus \participant{\ensuremath{g}_2}}}} = (\ensuremath{g}₁' \ensuremath{\ast} \ensuremath{g}₂')$ if $\redGM{\ensuremath{g}_j}{\motion{\dtsess}{({\sf p}_i:\ensuremath{\mathit{a}}_i[t_i;t'_i])_{{\sf p}_i∈\participant{\ensuremath{g}_j}}}} = \ensuremath{g}_j'$ ($j=1,2$) \item\label{Item:GC6} $\redGM{\ensuremath{g}}{x}= \ensuremath{g}'$ then $\redGM{\ensuremath{g}.\ensuremath{g}_1}{x}= \ensuremath{g}'.\ensuremath{g}_1$ and $\redGM{\ensuremath{g}.\ensuremath{{\sf G}}}{x}= \ensuremath{g}'.\ensuremath{{\sf G}}$. \item\label{Item:GC7} $\redGM{\ensuremath{g}}{x} = \ensuremath{g}'$ if $∃\ensuremath{g}''.\exists \ASENDPC.\, \redastGequiv{\emptyset\rhd \ensuremath{g}}{\ASENDPC \rhd \ensuremath{g}''}$ and $\redGM{\ensuremath{g}''}{x} = \ensuremath{g}'$ where $C$ is a reduction context of the prefix defined as: $C = C.g \ensuremath{~~\mathbf{|\!\!|}~~ } C\ensuremath{\ast} g \ensuremath{~~\mathbf{|\!\!|}~~ } g \ensuremath{\ast} C \ensuremath{~~\mathbf{|\!\!|}~~ } [\ ]$ and $\ASENDPC$ is a set of enabled senders such that $\ASENDPC\subseteq \ensuremath{\Bbb P}$ and \begin{enumerate} \item\label{Item:GC7A} $\redGequiv{\ASENDPC\rhd C[\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t}^{\sf p}]}{ \ASENDPC \cup\set{{\sf p}} \rhd C }$ if $∃ i.~{\sf p}_i = {\sf p} \wedge t ∈ D_i \wedge {\ddagger}_i = {\mathsf{\rightsquigarrow}}$. \item\label{Item:GC7B} $\redGequiv{\ASENDPC\rhd C[\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t}^{\sf p}]}{\ASENDPC \rhd C}$ with ${\sf p}\in\ASENDPC$ and for all $i$, ${\sf p}_i\not = {\sf p}$ and $t\in D_i$. \end{enumerate} \begin{comment} \RMi{OLD 7a, 7b:} \item $\redGM{\ensuremath{g}}{x} =\ensuremath{g}'$ and if $∃\ensuremath{g}''.\, \redGequiv{\ensuremath{g}}{\ensuremath{g}''} ∧ \redGM{\ensuremath{g}''}{x} = \ensuremath{g}'$ \begin{enumerate} \item $\redGequiv{C[\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t}]}{C}$ if $∃ i.~ t ∈ D_i ∧ {\ddagger}_i = {\mathsf{\rightsquigarrow}}$ where $C$ is a reduction context of the prefix defined as: $C = C.g \ensuremath{~~\mathbf{|\!\!|}~~ } C\ensuremath{\ast} g \ensuremath{~~\mathbf{|\!\!|}~~ } g \ensuremath{\ast} C \ensuremath{~~\mathbf{|\!\!|}~~ } [\ ]$. \item $\redGequiv{C^-[\motion{\dtsess}{({\sf p}_i: \ensuremath{\mathit{a}}_i)\AT t}]}{C^-}$ if $\forall i.~ t ∈ D_i ∧ {\ddagger}_i = {\mathsf{\lightning}}$ where $C^-$ is a separation reduction context of the prefix defined as: $C^- = C^-\ensuremath{\ast} g \ensuremath{~~\mathbf{|\!\!|}~~ } C^- \ensuremath{\ast} g \ensuremath{~~\mathbf{|\!\!|}~~ } [\ ]$. \end{enumerate} \end{comment} \end{enumerate} \begin{comment} \[ \small \begin{array}{r@{\hskip 2mm}c@{\hskip 2mm}l} \redG{\big(\Gvti {\sf p}\pq {[\mathcal{P}_i]\ell} {\mathcal{P}'}{\ensuremath{{\sf G}}}\big)}{\sf p}\ell\pq & = & \ensuremath{{\sf G}}_{k} \\ & & \text{if\; }\exists k \in I : \ell = \ell_k \\[3mm] \redG{\big(\Gvti {\sf r}{\sf s} {[\mathcal{P}_i]\ell} {\mathcal{P}'} {\ensuremath{{\sf G}}}\big)}{\sf p}\ell\pq & = & \Gvtir {\sf r} {\sf s} \ell {\mathcal{P}'}{\ensuremath{{\sf G}}} \\ & & \hspace{1mm} \text{if\; } \{{\sf r}, {\sf s}\} \cap \{{\sf p}, \pq\} = \emptyset ~\land~ \forall i \!\in\! I: \{{\sf p}, \pq\} \!\subseteq\! G_i \\[3mm] \redG{(\ensuremath{{\sf G}}₁ ∥ \ensuremath{{\sf G}}₂).\ensuremath{{\sf G}}}{\sf p}\ell\pq & = & (\ensuremath{{\sf G}}₁' ∥ \ensuremath{{\sf G}}₂).\ensuremath{{\sf G}} \\ & & \hspace{1mm} \text{if\; }\exists \redG{\ensuremath{{\sf G}}₁}{\sf p}\ell\pq = \ensuremath{{\sf G}}₁' \\[3mm] \redG{(\ensuremath{{\sf G}}₁ ∥ \ensuremath{{\sf G}}₂).\ensuremath{{\sf G}}}{\sf p}\ell\pq & = & (\ensuremath{{\sf G}}₁ ∥ \ensuremath{{\sf G}}₂').\ensuremath{{\sf G}} \\ & & \hspace{1mm} \text{if\; }\exists \redG{\ensuremath{{\sf G}}₁}{\sf p}\ell\pq = \ensuremath{{\sf G}}₂' \\[3mm] \redGM{\Gmotion{\dtsess}{\{a_i\}{i∈I}@t}{\ensuremath{{\sf G}}} }{\motion{\dtsess}{\{a_i[t_i;t'_i]\}_{i∈I}}} & = & \Gmotion{\dtsess}{\{a_i\}_{i∈I}@t'}{\ensuremath{{\sf G}}} \\[3mm] & & \hspace{1mm} \text{if\; } ∀ i, j.~ t'_i-t_i = t'_j-t_j = t'-t ∧ t' > t ∧ t' ∈ D_i\\[3mm] \redGM{(\ensuremath{{\sf G}}₁ ∥ \ensuremath{{\sf G}}₂).\ensuremath{{\sf G}}}{\motion{\dtsess}{\{a_i[t_i;t'_i]\}_{i∈I⊎J}}} & = & (\ensuremath{{\sf G}}₁' ∥ \ensuremath{{\sf G}}₂').\ensuremath{{\sf G}} \\ & & \hspace{1mm} \text{if\; } \redGM{\ensuremath{{\sf G}}₁}{\motion{\dtsess}{\{a_i[t_i;t'_i]\}_{i∈I}}} = \ensuremath{{\sf G}}₁' ∧ \redGM{\ensuremath{{\sf G}}₂}{\motion{\dtsess}{\{a_i[t_i;t'_i]\}_{i∈J}}} = \ensuremath{{\sf G}}₂' \\[3mm] \redGM{\ensuremath{{\sf G}}}{x} & = & \ensuremath{{\sf G}}' \\ & & \hspace{1mm} \text{if\;} ∃\ensuremath{{\sf G}}''.\, \redGequiv{\ensuremath{{\sf G}}}{\ensuremath{{\sf G}}''} ∧ \redGM{\ensuremath{{\sf G}}''}{x} = \ensuremath{{\sf G}}' \\[3mm] \end{array} \] \end{comment} In (6) and (7), we write $x$ as either ${{\sf p}}\rightarrow{\pq}$ or $\motion{\dtsess}{a}[t_1,t_2]$. The \emph{reduction of global types} % is the smallest pre-order relation closed under the rule: \( \ensuremath{{\sf G}}\Longrightarrow\redG \ensuremath{{\sf G}}{\sf p}{\ell}\pq \quad \text{and} \quad \ensuremath{{\sf G}}\Longrightarrow\redGM{\ensuremath{{\sf G}}}{\motion{\dtsess}{{\sf p}_i{:}\ensuremath{\mathit{a}}_i[t_i,t'_i]}} \). \end{definition} \noindent Note that the above reduction preserves well-formedness of global types. We can now state the main results. Our typing system is based on one in \cite{DBLP:journals/jlp/GhilezanJPSY19} with motion primitives and refinements. Since the global type reduction in Definition~\ref{def:global-type-consumption} is only related to communications or synchronisation of motions but not refinements, (1) when the two processes ${\sf p}$ and $\pq$ synchronise by a communication, its global type can always reduce; or (2) when all processes synchronise by the same motion action, their corresponding global type can always be consumed. Thus process behaviours correspond to reductions of global types, which is formulated as in the following theorem. Recall $\xrightarrow{\alpha}$ denotes any transition relation or reduction. \begin{restatable}[Subject Reduction]{theorem}{theoremSR} \label{th:SR} Let $M$ be a multiparty session, $\ensuremath{{\sf G}}$ be a well-formed global type, and a physical state $I$ such that $\der{I}{M}{\ensuremath{{\sf G}}}$. For all $M'$, if $M \xrightarrow{\alpha} M'$, then $\der{I'}{M'}{{\ensuremath{{\sf G}}}'}$ for some ${\ensuremath{{\sf G}}}'$, $I'$ such that ${\ensuremath{{\sf G}}}\Longrightarrow{\ensuremath{{\sf G}}}'$. Thus, if $M\equiv M'$ or $M \xrightarrow{\alpha_1}\cdots\xrightarrow{\alpha_n} M'$, then $\der{}{M'}{{\ensuremath{{\sf G}}}'}$ for some ${\ensuremath{{\sf G}}}'$ such that ${\ensuremath{{\sf G}}}\Longrightarrow{\ensuremath{{\sf G}}}'$. \end{restatable} \iftoggle{full}{ See Appendix~\ref{app:sr} for the detailed proofs. }{ See \cite{fullversion} for the detailed proofs. } Below we state the two progress properties as already explained in {Sec.}~\ref{sec:example}. The first progress is related to communications, while the second one gurantees the typed multiparty session processes are always collision free. As a consequence, if $\der{I}M{\ensuremath{{\sf G}}}$ for a well-formed type, then $M$ does not get stuck and can always reduce. \begin{restatable}[Progress]{theorem}{theoremPROG} \label{th:progress} Let $M$ be a multiparty session, $\ensuremath{{\sf G}}$ be a well-formed type, and a physical state $I$. If $\der{I}M{\ensuremath{{\sf G}}}$ then: \begin{enumerate} \item {\sc (Communication and Motion Progress)} there is $M'$ such that $M \longrightarrow M'$ and \item {\sc (Collision-free Progress)} If $M \longrightarrow^\ast M'$, then $M'$ is also collision free. \end{enumerate} \end{restatable} \begin{proof} ({\em Outline -- \iftoggle{full}{ see Appendix~\ref{app:sr} for the detailed proofs }{ see \cite{fullversion} for the detailed proofs. } }) {\em (Communication Progress)} The proof is divided into two cases: (a) the guard appearing in the branching type followed by (b) a message exchange between two parties. Case (a) follows from the fact that there is always at least one guard in a choice whose predicate is evaluated to true (Definition \ref{def:well-formed}(1)). The typing rules ensure that the predicates are satisfied when a message is sent. Case (b) is proved using Theorem~\ref{th:SR} with Definition \ref{def:well-formed}(4) since the unique minimal sender in $G$ can always send a message. {\em (Motion Progress)} For executing motions, Definition~\ref{def:well-formed}(3) and Theorem~\ref{th:motion-compat} ensure local trajectories can be composed into global trajectories. {\em (Collision-free Progress)} By induction. Under $I$ and by \rulename{t-sess}, $M$ is initially collision free. For the communication, note that it does not change the physical state, and therefore, does not impact the geometric footprint used by a process. Hence the case $\redG \ensuremath{{\sf G}}{\sf p}\ell\pq$ is straightforward. For motion actions, Definition~\ref{def:well-formed}(3) and Theorem~\ref{th:motion-compat} ensures collision freedom through execution steps. For a collision free program, collision freedom of the next state follows from compatibility of motion. \end{proof} \begin{comment} \begin{remark}[Time Divergence] \label{rem:timediv} \NYi{We can look at our CONCUR paper today. This remark sounds a bit weak} \DZi{The CONCUR paper looks at a sightly different problem. There the issue comes from the asynchronous communication. Here the issue comes from the flow and the imperative loops. For the communication, we could do like in the ECOOP paper: force loops to contain a flow. However, it would not fix the issue completely. Example such the bouncing ball (\url{https://www.mathworks.com/help/simulink/examples/simulation-of-a-bouncing-ball.html}) can be encoded with a flow and a loop, no communication needed.} The progress theorem checks that a program can always make a step. However, it does not guarantees that time progresses. For instance, there could be a $0$ time loop where processes send and receive an unbounded number of messages. Similarly, the proof system for motion primitive does not guarantee that a motion terminates. Progress of time is a challenging issue when modeling cyber-physical systems. Not only can there be $0$ time loops, there can as also be Zeno traces, i.e. flows which progress by smaller and smaller amount until they converge to a finite value. Often, one simply assumes that time diverges \cite{Henzinger96}. % As future work, we plan to investigate liveness concern and how to modify our proof and type system to also provide liveness guarantees. \end{remark} \end{comment} \subsection{A More Complex Coordination Example with Producer} \label{subsec:large} We now discuss an extended version of the coordination example from {Sec.}~\ref{sec:example} that we shall implement on physical robots in {Sec.}~\ref{sec:eval}. In addition to cart and two arms, we add a producer robot. The ${\color{roleColor}{\mathsf{Prod}}}$ generates green or red parts and places them on to the cart. The cart ${\color{roleColor}{\mathsf{Cart}}}$ carries the part to the two robot arms as before. We shall use this extended version as the basis for one of our case studies. The coordination protocol is as follows. First, the protocol starts by syncing all participants. Then, the cart moves to the producer after announcing a message $\mathit{arrive}$. While the cart moves to the producer, the two consumer robots can work independently. When the cart is at the producer, it synchronises through a message $\mathit{ready}$, and idles while the producer places an object on to it. When the producer is done, it synchronises with the cart, and tells it whether the object is green or red. Based on this information, the cart tells one of the consumers that it is arriving with a part and tells the other consumer that it is free to work. Subsequently, the cart moves to the appropriate consumer to deposit the part, while the other consumer as well as the producer is free to continue their work. When the robot is at the consumer, it syncs through a message, and idles until the part is taken off. After this, the protocol starts again as the cart makes its journey back to the producer, while the consumers independently continue their work. \begin{figure*}[t] {\small \begin{align*} \text{Initial Phase} \ \equiv\ \begin{array}{l} {\color{roleColor}{\mathsf{Cart}}} \to {\color{roleColor}{\mathsf{Prod}}}: \mathit{arrive}. {\color{roleColor}{\mathsf{Cart}}}\to {\color{roleColor}{\mathsf{GRobot}}}: \mathit{start}.{\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{RRobot}}}:\mathit{start}.\\ \left( \begin{array}{ccc} \left( \begin{array}{l} (\motion{\dtsess}{\tuple{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_move}^{\mathsf{\rightsquigarrow}}({\color{roleColor}{\mathsf{Prod}}}), {\color{roleColor}{\mathsf{Prod}}}:\mathsf{work}^{\mathsf{\lightning}}}}^{\color{roleColor}{\mathsf{Cart}}}.\\ {\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{Prod}}}:\mathit{ready}.\motion{\dtsess}{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_idle}^{\mathsf{\lightning}},{\color{roleColor}{\mathsf{Prod}}}:\mathsf{place}^{\mathsf{\rightsquigarrow}}})^{\color{roleColor}{\mathsf{Prod}}}. \end{array} \right) \\ \quad\quad ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{RRobot}}}: \mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Prod}}} ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{GRobot}}}: \mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Prod}}} \end{array} \right) \end{array} \end{align*} \begin{align*} \begin{array}{l} \text{Process Green Item} \ \equiv\ \\ \quad \quad \left( \begin{array}{cc} \motion{\dtsess}{{\color{roleColor}{\mathsf{Prod}}}:\mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Cart}}}) ~\ensuremath{\ast}~ & \left( \begin{array}{l} {\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{GRobot}}}:\mathit{arrive}.{\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{RRobot}}}:\mathit{free}. \\ \left(\begin{array}{cc} \text{as in the green box in Figure~\ref{fig:basic-example}} % % % % % % & ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{RRobot}}}:\mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Cart}}} \end{array}\right) \end{array} \right) \end{array} \right) \\ \end{array} \end{align*} \begin{align*} \text{Global Type} \ \equiv \ \mu \mathbf{t}. & \langle \text{Initial Phase}\rangle. \left( \begin{array}{l} ({\color{roleColor}{\mathsf{Prod}}} \to{\color{roleColor}{\mathsf{Cart}}}:\mathit{green}. \langle \text{Process Green Item} \rangle)\\ + ({\color{roleColor}{\mathsf{Prod}}}\to{\color{roleColor}{\mathsf{Cart}}}:\mathit{red}. \langle \text{Process Red Item} \rangle) \end{array} \right) .\mathbf{t} \end{align*} } \vspace{-3mm} \caption{Motion session type annotated with minimal senders. For readability, we have broken the type into sub-parts: the initial phase, and processing items (the type for processing red items is symmetric and omitted)\label{fig:annotated-global-session-type}} \end{figure*} \myparagraph{Global Type} The global type for the example extends one in Figure~\ref{fig:basic-example}, and is shown in Figure~\ref{fig:annotated-global-session-type}. It can be seen that the global type has total choice (trivially), and is well-scoped and synchronisable. The motion primitive specifications are omitted; we ensure in our evaluation that the motion primitives are compatible and the type is fully separated using calls to the SMT solver dReal. \myparagraph{Processes} The processes in this example extend the processes from {Sec.}~\ref{sec:example} but the ${\color{roleColor}{\mathsf{RRobot}}}$ and ${\color{roleColor}{\mathsf{GRobot}}}$ processes are as before: \[ \begin{array}{ll} {\color{roleColor}{\mathsf{Cart}}}: & \begin{array}{l}\small \mu {\roleVar}. {\color{roleColor}{\mathsf{Prod}}}!\mathit{arrive}.{\color{roleColor}{\mathsf{RRobot}}}!\mathit{start}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{start}.\mathsf{m\_move}(\text{co-ord of }{\color{roleColor}{\mathsf{Prod}}}).{\color{roleColor}{\mathsf{Prod}}}!\mathit{ready}.\mathsf{m\_idle}.\\ \ ({\color{roleColor}{\mathsf{Prod}}}?\mathit{red}.{\color{roleColor}{\mathsf{RRobot}}}!\mathit{arrive}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{free}.\mathsf{m\_move}(\text{co-ord of }{\color{roleColor}{\mathsf{RRobot}}}).\\ \ \ \ \quad\quad {\color{roleColor}{\mathsf{RRobot}}}!\mathit{ready}.\mathsf{m\_idle}.{\color{roleColor}{\mathsf{RRobot}}}?\mathit{ok}.{\roleVar}\\ \ + {\color{roleColor}{\mathsf{Prod}}}?\mathit{green}.\textrm{ symmetrically for ${\color{roleColor}{\mathsf{GRobot}}}$ }) \end{array} \\[3mm] {\color{roleColor}{\mathsf{Prod}}}: & \begin{array}{l}\small \mu {\roleVar}.{\color{roleColor}{\mathsf{Cart}}}?\mathit{arrive}.\mathsf{work}.{\color{roleColor}{\mathsf{Cart}}}?\mathit{ready}.\mathsf{place}. ({\color{roleColor}{\mathsf{Cart}}}!\mathit{green} + {\color{roleColor}{\mathsf{Cart}}}!\mathit{red}).\mathsf{work}.{\roleVar} \end{array} \end{array} \] \begin{comment} \[ \begin{array}{c|c} \begin{array}{rl}\small {\color{roleColor}{\mathsf{Cart}}}:\!\!\!\!\!\!\\ \mu {\roleVar}.\!\!\!\!\!\! & {\color{roleColor}{\mathsf{Prod}}}!\mathit{arrive}.{\color{roleColor}{\mathsf{RRobot}}}!\mathit{start}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{start}.\\ & \mathsf{m\_move}(\text{co-ord of }{\color{roleColor}{\mathsf{Prod}}}).{\color{roleColor}{\mathsf{Prod}}}!\mathit{ready}.\mathsf{m\_idle}.\\ & \ ({\color{roleColor}{\mathsf{Prod}}}?\mathit{red}.{\color{roleColor}{\mathsf{RRobot}}}!\mathit{arrive}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{free}.\\ & \ \quad \mathsf{m\_move}(\text{co-ord of }{\color{roleColor}{\mathsf{RRobot}}}).{\color{roleColor}{\mathsf{RRobot}}}!\mathit{ready}.\\ & \ \quad \mathsf{m\_idle}.{\color{roleColor}{\mathsf{RRobot}}}?\mathit{ok}.{\roleVar}\\ & \ + {\color{roleColor}{\mathsf{Prod}}}?\mathit{green}.\textrm{ symmetrically for ${\color{roleColor}{\mathsf{GRobot}}}$ }) \end{array} & \begin{array}{rl}\small {\color{roleColor}{\mathsf{Prod}}}:\!\!\!\!\!\!\!\!\!\!\\ \mu {\roleVar}.\!\!\!\!\!\!& {\color{roleColor}{\mathsf{Cart}}}?\mathit{arrive}.\mathsf{work}.\\ & {\color{roleColor}{\mathsf{Cart}}}?\mathit{ready}.\mathsf{place}.\\ & ({\color{roleColor}{\mathsf{Cart}}}!\mathit{green} + {\color{roleColor}{\mathsf{Cart}}}!\mathit{red}).\mathsf{work}.{\roleVar} \end{array} \end{array} \] \end{comment} \myparagraph{Local Types} The local types for the components are: \begin{align*} \small \begin{array}{c|c} \small \begin{array}{rl} {\color{roleColor}{\mathsf{Cart}}}:\!\!\!\!\!\!\\ \mu \mathbf{t}. & {\color{roleColor}{\mathsf{Prod}}}!\mathit{arrive}(t).{\color{roleColor}{\mathsf{RRobot}}}!\mathit{start}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{start}.\\ & \motion{\dtsess}{\mathsf{m\_move}({\color{roleColor}{\mathsf{Prod}}})}.{\color{roleColor}{\mathsf{Prod}}}!\mathit{ready}.\motion{\dtsess}{\mathsf{m\_idle}}.\\ & (\ ({\color{roleColor}{\mathsf{Prod}}}?\mathit{green}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{arrive}(t).{\color{roleColor}{\mathsf{RRobot}}}!\mathit{free}.\\ & \ \ \motion{\dtsess}{\mathsf{m\_move}({\color{roleColor}{\mathsf{GRobot}}})}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{ready}.\\ & \ \ \motion{\dtsess}{\mathsf{m\_idle}}.{\color{roleColor}{\mathsf{GRobot}}}?\mathit{ok}) \\ & \& \ ({\color{roleColor}{\mathsf{Prod}}}?\mathit{red}. \ldots \text{symmetric} \ldots)\ ).\mathbf{t} \end{array} & \begin{array}{l} {\color{roleColor}{\mathsf{Prod}}}:\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\\ \quad\mu \mathbf{t}. {\color{roleColor}{\mathsf{Cart}}}?\mathit{arrive}(t).\motion{\dtsess}{\mathsf{work}}.{\color{roleColor}{\mathsf{Cart}}}?\mathit{ready}.\motion{\dtsess}{\mathsf{place}}.\\ \quad\quad ({\color{roleColor}{\mathsf{Cart}}}!\mathit{green}.\motion{\dtsess}{\mathsf{work}}.\mathbf{t}\; \oplus \; {\color{roleColor}{\mathsf{Cart}}}!\mathit{red}.\motion{\dtsess}{\mathsf{work}}.\mathbf{t})\\ {\color{roleColor}{\mathsf{RRobot}}},{\color{roleColor}{\mathsf{GRobot}}}:\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\\ \quad\mu \mathbf{t}. ({\color{roleColor}{\mathsf{Cart}}}?\mathit{start}.\motion{\dtsess}{\mathsf{work}}.\\ \quad\quad(\ ({\color{roleColor}{\mathsf{Cart}}}?\mathit{arrive}(t).\motion{\dtsess}{\mathsf{work}}.\\ \quad\quad {\color{roleColor}{\mathsf{Cart}}}?\mathit{ready}.\motion{\dtsess}{\mathsf{pick}}.{\color{roleColor}{\mathsf{Cart}}}!\mathit{ok}) \\ \quad\quad\& \; ({\color{roleColor}{\mathsf{Cart}}}?\mathit{free}.\motion{\dtsess}{\mathsf{work}}) \ ).\mathbf{t} \end{array} \end{array} \end{align*} We can show that all the processes type check. From the soundness theorems, we conclude that the example satisfies communication safety, motion compatibility, and collision freedom. \section{Implementation and Case Study} \label{sec:eval} \myparagraph{Implementation} Our implementation has two parts. The first part takes a program, a specification for each motion primitive, and a global type and checks that the type is well-formed and that each process satisfies its local type. The second part implements the program on top of the Robotic Operating System (ROS)~\cite{ROS}, a software ecosystem for robots. We reuse the infrastructure of motion session types \cite{ECOOP19}; for example, we write programs in \textsf{PGCD}\xspace syntax \cite{PGCD}. The verification infrastructure is about 4000 lines of Python code, excluding the solver. The code is available at \url{https://github.com/MPI-SWS/pgcd} and instructions to run these experiments are located in the \texttt{oopsla20\_artifact} branch. Internally, we represent programs and global types as state machines \cite{DBLP:conf/esop/DenielouY12}, and implement the dataflow analysis on this representation. Additionally, we specify motion primitives in the local co-ordinate system for each robot and automatically perform frame transformations between two robots. The core of ROS is a publish-subscribe messaging system; we extend the messaging layer to implement a synchronous message-passing layer. Our specifications contain predicates with nonlinear arithmetic, for example, to represent footprints of components as spheres. Obstacle are represented as passive components, i.e., components which have a physical footprint but do not execute program. Such components can interact with normal components through input and state variables and their are considered when checking the absence of collision. On the other hand, the obstacles are excluded from the checks related to communication, e.g., synchronisability. We use the dReal4 SMT solver \cite{dReal} to discharge validity queries. The running times are obtained on a Intel i7-7700K CPU at $4.2$GHz and dReal4 running in parallel on 6 cores. \myparagraph{Tests} We evaluate our system on two benchmarks and a more complex case study: (1) We test scalability of the verification using micro-benchmarks. (2) We compare our approach with previous approaches on a set of robotic coordination scenarios from the literature \cite{PGCD,ECOOP19}, and (3) As a large case study, we verify and implement a complex choreography example based on a variation of the example from {Sec.}~\ref{subsec:large}. \begin{wrapfigure}{r}{5cm} \centering \includegraphics[width=45mm]{figs/lanes.pdf} \vspace{-2ex} \caption{Parallel lanes micro-benchmarks} \label{fig:lanes} \vspace{-2ex} \end{wrapfigure} \myparagraph{(1) Micro-benchmarks} The micro-benchmarks comprise a parametric family of examples that highlight the advantage of our motion session calculus, specifically the separating conjunction, over previous typing approaches \cite{ECOOP19}. The scenario consists of carts moving back and forth along parallel trajectories, and is parameterised by the number of carts. Fig.~\ref{fig:lanes} shows the verification times for this example in the two systems. We start with 2 robots and increase the number of robots until we reach a $200$ s. timeout for the verification. The previous calculus is discrete-time and does not separate independent components. Thus, the type system synchronises every process and, therefore, generates complex collision checks which quickly overwhelms the verifier. Our global types use the separating conjunction to split the specifications into independent pieces and the verifcation time increases linearly in the number of processes. \myparagraph{Setup for (2) and (3)} For examples used previously in related works \cite{PGCD,ECOOP19}, we write specifications using our motion session types, taking advantage of the modularity of the type system. For the new case study (part (3)), we implement a variation of the example presented in {Sec.}~\ref{sec:example}, where we decouple the producer placing an object and a sensor that determines if the object is green or red. Thus, after the producer places an object on the cart, the cart first moves to the sensor, communicates with the sensor to get the color, and then delivers the object as described in the protocol. We filmed our experiments and a short video can be seen in the \textbf{\emph{supplementary materials}}. We use three robots: a custom-built robot arm modified from an open-source arm, a commercial manipulator, and a mobile cart, as shown in Figure~\ref{fig:robots-xp}. We use placeholders for the producer arm and color sensor, as we do not have additional hardware (and arms are expensive). The robots are built with a mix of off-the-self parts and 3D printed parts as described below. \textbf{\emph{Arm}.}\ The arm is a modified BCN3D MOVEO ({\url{https://github.com/BCN3D/BCN3D-Moveo}}). The upper arm section is shortened to make it lighter and easier to mount on a mobile cart. % It has three degrees of freedom. % % The motion primitives consist of moving between poses and opening/closing the gripper. The motion is a straight line in the configuration space (angles of the joints) which corresponds to curves in physical space. \textbf{\emph{Panda Arm.}} \ The Panda arm by Franka Emika ({\url{https://www.franka.de/technology}}) is a seven degrees of freedom commercial manipulator platform. It is controlled similarly to the MOVEO arm but with a more complex configuration space. The Panda arm has a closed-loop controller and can get to a pose with an error less than 0.1mm. The controller also comes with collision detection using feedback from the motors. We command this arm using a library of motion primitives provided by the manufacturer. \textbf{\emph{Mobile Carts}.} \ There are two carts. Both are omnidirectional driving platforms. One uses mecanum wheels and the other omniwheels to get three degrees of freedom (two in translation, one in rotation) and can move between any two positions on a flat ground. The advantage of using such wheels is that all the three degrees of freedom are controllable and movement does not require complex planning. Its basic motion primitives are moving in the direction of the wheels, moving perpendicularly to the direction of the wheels, and rotating around its center. % The arm and cart are equipped with RaspberryPi 3 model B to run their processes and use stepper motors. This enables a control of the joints and wheels with less than 1.8 degree of error. However, these robots do not have global feedback on their position and keep track of their state using \emph{dead reckoning}. This can be a challenge for the cart, which keeps accummulating error over time. As our example is a loop, we manually reset the cart's position when it gets back to the producer after delivering the object. (A more realistic implementation would use feedback control, but we omit this because control algorithms are a somewhat orthogonal concern.) For the producer and the color sorter, we run the processes but have placeholders in the physical world and realise the corresponding action manually. All computers run Ubuntu 18.04 with ROS 2 Dashing Diademata. Table~\ref{tbl:xp1} shows the specification for the robots and their motions. As the two carts share most of their specification, we group them together. The specification includes the geometrical description of the robots and the motion primitives. \myparagraph{(2) Revisiting the Examples from \textsf{PGCD}\xspace} As we build on top of \textsf{PGCD}\xspace, we can use the examples used to evaluate that system. We take 4 examples, for which we compare the specification effort in the previous calculus \cite{ECOOP19} to our new calculus. As the two calculi have different models for the time and synchronisation, we made some minor adaptations such that the same programs can be described by the two calculi. The old calculus requires motion primitives to have fixed duration and does not support interruptible motions. Furthermore, there is no ``$\ensuremath{\ast}$'' in the old calculus so all the motions are always synchronised. In our new specification, we take advantage of our richer calculus to better decompose the protocol. We use the following scenarios. \begin{description} \item[Fetch.] in this experiment, the Moveo arm is attached on top of a cart. The goal is to get an object. The cart moves toward the object until the object if within the arm's reach. The arm grabs the object and the cart goes back to its initial position. \item[Handover.] This experiment is a variation of the previous one. There are two carts instead of one and the object to fetch is on top of the new cart. The two carts meet before the arm takes an object placed on top of the second cart and then, both go back to their initial positions. \item[Twist and Turn.] In this experiment, the two carts start in front of the each other. The arm takes an object from the small cart. Then all three robots move simultaneously. The cart carrying the arm rotates in place, the other cart describes a curve around the first cart, and arm moves from one side of the cart to the other side. At the end, the arm puts the object on the carrier. \item[Underpass.] In this experiment, the arm and the cart cooperate to go under an obstacle. First, the cart goes toward the arm, which takes the object from the cart. The cart goes around the arm passing under an obstacle. Finally, the arm puts the object back on the cart on the other side of the obstacle. \end{description} Table~\ref{tbl:xp-revisit} reports the size of the examples and their specifications, as well as the verification time. The verification time is broken down into syntactic well-formedness checks on the choreography, the motion compatibility checks for the trajectories, and typing the processes w.r.t.\ local types. The motion compatibility checks dominate the verification time. When we compare our new calculus to the previous approach, we can observe that the global types are slightly larger but the verification time can be significantly smaller. The increase in specification size comes with the addition of new Assume-Guarantee contracts when $\ensuremath{\ast}$ is used. The verification time from the existing specification are higher than the time reported in the previously published results. When implementing our new calculus, we found and fixed some bugs in the verifier code from \textsf{PGCD}\xspace. Those bugs resulted in incomplete collision checks and fixing them increased the burden on the SMT solver.\footnote{\label{note:dreal} Two out of 217 queries in the Fetch example are particularly hard for the solver and could not be solved with 1 hour. We suspect a bug in the solver as all the other queries are solved in $134$s. } \newcommand{\centercell}[1]{\multicolumn{2}{c}{#1}} \begin{table}[t] \centering \caption{Programs, specification, and verification time for the \textsf{PGCD}\xspace examples. ``Prev'' refers to \cite{ECOOP19}.} \vspace{-1ex} \scriptsize \begin{tabular}{lrrr|cc|cc|cc|cc} \toprule Scenario & \multicolumn{3}{c}{Program (Loc)} & \centercell{Global Type} & \centercell{Syntactic} & \centercell{Motion} & \centercell{Typing (s.)} \\ & & & & \centercell{(LoC)} & \centercell{Checks (s.)} & \centercell{Compatibility (s.)} & \\ & Arm & Cart 1 & Cart 2 & Prev & This work& Prev & This work & Prev & This work & Prev & This work \\ \midrule Fetch & $14$ & $19$ & $-$ & $22$ & $42$ & $0.1$ & $0.1$ & $> 3600$ \footnoteref{note:dreal} & $\bf 7$ & $0.1$ & $0.1$ \\ Handover & $9$ & $8$ & $6$ & $14$ & $26$ & $0.1$ & $0.1$ & $2224$ & $\bf 70$ & $0.1$ & $0.1$ \\ Twist and turn & $12$ & $16$ & $6$ & $15$ & $17$ & $0.1$ & $0.1$ & $599$ & $\bf 203$ & $0.1$ & $0.1$ \\ Underpass & $18$ & $3$ & $14$ & $21$ & $65$ & $0.1$ & $0.1$ & $187$ & $\bf 114$ & $0.1$ & $0.1$ \\ \bottomrule \end{tabular} \label{tbl:xp-revisit} \end{table} \begin{figure}[t] \centering \begin{subfigure}[b]{0.4\textwidth} \includegraphics[width=0.965\textwidth]{sorting_setup.jpg} \caption{Setup} \label{fig:robots-xp-setup} \end{subfigure} \begin{subfigure}[b]{0.4\textwidth} \includegraphics[width=\textwidth]{sorting.jpg} \caption{Sequence of motions} \label{fig:robots-xp} \end{subfigure} \vspace{-1ex} \caption{Experimental setup for the sorting example} \vspace{-1ex} \end{figure} \myparagraph{(3) A Complex Case Study} The purpose of the case study is to show that we can semi-automatically verify systems beyond the scope of previous work. Table~\ref{tbl:xp1} shows the sizes of the processes (in lines of code, in the syntax of \textsf{PGCD}\xspace) and statistics related to the global specification and verification time. The global specification consists of the global type, the environment description, and (manually provided) annotations for the verification. The annotations are mostly related to the footprints and the parallel composition. Each time we use the parallel composition operator we specify a partition of the current footprint (the ``$\exists \ensuremath{\mathit{FP}}_1,\ensuremath{\mathit{FP}}_2$'' in rule \rulename{AGcomp}). In Table~\ref{tbl:xp1}, we split the running times into the well-formedness checks which can be done syntactically, the verification conditions for the execution of the motion primitives, and the typing. We did not try to encode this example using the older \textsf{PGCD}\xspace specifications for two reasons. First, the stronger requirement on discrete time steps and global synchronisation in time in the previous calculus would subtantially change this example. Remember that motions in \cite{ECOOP19} are specified simultaneously for all the robots and must have the same duration. When multiple motion primitives have different durations, a motion step can only be as long as the shortest motion. Thus, we would need to chunk the longer motions into a sequence of smaller steps. This would, in turn, make the (sub)typing much more difficult as one motion step in the code would correspond to a sequence of motion steps in the specification. Second, as the previous calculus does not include the separating conjunction, there is little hope that the SMT solver can cope with the compelxity of this example: it contains more robots and more complex ones. Because our global types include separating conjunctions, we can more efficiently generate and discharge the verification conditions. At the modest cost of specifying the footprints for each thread, the collision checks only need to consider the robots within a thread and not all the robots in the system. This brings a substantial reduction in the complexity of the verification conditions. In conclusion, the case study demonstrates the power of our method in specifying and verifying non-trivial coordination tasks between multiple robots. It requires the expressiveness of our motion primitive specifications and the modularity of our separating conjunction. \begin{table}[t] \centering \caption{Programs, motion specification, type, and verification time} \vspace{-1ex} \small \begin{tabular}{lcc|lrl} \toprule Robot & Motion Spec (LoC) & Program (LoC) & Specification \\ \midrule Moveo arm & 306 & 28 & Global type & 96 & LoC \\ Panda arm & 348 & 31 & Syntactic checks & 0.2 & s. \\ Carts & 404 & 45 & Compatibility checks & 2410 & s. \\ Sensor/Producer & 105 & 17 / 10 & Typing & 3.1 & s. \\ \bottomrule \end{tabular} \label{tbl:xp1} \vspace{-1ex} \end{table} \section{Related Work} \label{sec:related} The field of concurrent robotics has made enormous progress---from robot soccer to self-driving systems and to industrial manufacturing. However, to the best of our knowledge, none of these impressive systems come with formal guarantees of correctness. Our motivation, like many other similar projects in the area of high-confidence robotics and cyber-physical systems design, is to be able to reason formally about such systems. A spectrum of computer-assisted formal methods techniques can be, and have been, applied to reasoning about concurrent robotics, ranging from interactive theorem proving to automated analysis via model checking. As is well known, these techniques provide a tradeoff between manual effort and the expressiveness of specifications and the strength of guarantees. Our choice using manually specified choreographies and motion primitive specifications and automatically checked type correctness attempts to explore a point in the design space that requires manual abstraction of motion and geometry but provides automated checks for the interaction. We build on a type-based foundation rather than global model checking to again reflect the tradeoff: our use of choreographies and projections from global to local types restricts the structure of programs that can be type checked but enables a more scalable \emph{local} check for each process; in contrast, a model checking approach could lead to state-space explosion already at the level of concurrency. There are a vast number of extensions and applications of session types and choreographies~\cite{Huttel:2016:FST:2911992.2873052,ABBCCDGGGHJMMMNNPVY2016,BETTY2017}, but little work bringing types to practical programming in the domain of robotics or cyber-physical systems. We discuss the most related work. Our starting point was the theory of motion session types and PGCD \cite{PGCD,ECOOP19}, whose goals are similar to ours. We considerably extend the scope and expressiveness of motion session types: through \emph{continuous-time} motion primitives and through separating conjunction for modular synchronisation. Syntactic extensions of original global types \cite{HYC08} to represent more expressive communication structures have been studied, e.g.,~in \cite{DBLP:conf/popl/LangeTY15}, in the context of synthesis from communicating automata; in~\cite{DBLP:journals/corr/abs-1203-0780} to include parallel and choices; in \cite{DH2012} to represent nested global types. Our aim is to include the minimum syntax extension to \cite{HYC08} to represent separation and synchronisations best suited to implementing robotics applications. In turn, a combination of motion primitives and predicates required us to develop a novel and non-trivial data flow analysis of global choreographies for the well-formedness check. Hybrid extensions to process algebras \cite{RoundsS03,DBLP:journals/iandc/LynchSV03,BERGSTRA2005215,DBLP:conf/aplas/LiuLQZZZZ10} extend process algebras with hybrid behaviour and study classical concurrency issues such as process equivalences. Extensions to timed (but not hybrid) specifications in the $\pi$-calculus are studied in \citet{BYY2014,BMVY2019} to express properties on times on top of \emph{binary} session typed processes. The theory of hybrid automata \cite{ACHH,Henzinger96} provides a foundation for verifying models of hybrid systems. The main emphasis in hybrid automaton research has been in defining semantics and designing model checking algorithms---too many to enumerate, see \cite{Henzinger96,Platzer18}---and not on programmability. Assume guarantee reasoning for hybrid systems has been studied, e.g.~\cite{Nuzzo:EECS-2015-189,DBLP:journals/fteda/BenvenisteCNPRR18,DBLP:journals/pieee/NuzzoSBGV15,DBLP:journals/pieee/Tripakis16}. These works do not consider programmability or choreography aspects. Deductive verification for hybrid systems attempts to define logics and invariant-based reasoning to hybrid systems. Differential dynamic logic (dL) \cite{Platzer18,PlatzerT18} is a general logical framework to deductively reason about hybrid systems. It extends \emph{dynamic logic} with differential operators and shows sound and (relatively) complete axiomatisations for the logic. Keymaera \cite{DBLP:conf/cade/FultonMQVP15} and HHL Prover \cite{HHL} are interactive theorem provers based on hybrid progam logics. These tools can verify complex properties of systems at the cost of intensive manual effort. In contrast, we explore a point in the design space with more automation but less expressiveness. The ``trusted base'' in an interactive theorem prover is the core logic; optimizing the trusted base was not one of our goals. A well-studied workflow in high-confidence cyber-physical systems is model-based design (see, e.g., \cite{HenzingerSifakis07} for an overview), where a system is constructed by successive refinement of an abstract model down to an implementation. An important problem in model-based design is to ensure property-preserving refinement: one verifies properties of the system at higher levels of abstraction, and ensures that properties are preserved through refinement. In the presence of continuous dynamics, defining an appropriate notion of refinement and proving property-preserving compilation formally are hard problems \cite{DBLP:journals/tosem/YanJWWZ20,DBLP:conf/pldi/BohrerTMMP18}. In our implementation, we use \emph{automated} tools based on the dReal SMT solver \cite{dReal}. Our verification is \emph{semi-automatic}, as we require user annotations for footprints or for the motion primitive specifications, but discharge verification conditions through dReal. Of course, there are programs that go past the capability of the solver---this is already true for systems that \emph{only} have concurrency or only deal with dynamics. Our proof rules is to allow sound reasoning, potentially inside an interactive prover. Our implementation shows that---at least some---nontrivial examples do allow automation. Non-linear arithmetic is difficult to scale. Our observation is that a combination of manual specification of \emph{abstract} footprints that replace complex geometrical shapes with simpler over-approximations along with the power of state-of-the-art SMT solvers is reasonably effective even for complicated examples. Our choice of dReal (as opposed to a different SMT solver) is dReal's ``off the shelf'' support for non-linear arithmetic and trigonometric functions. Trigonometry shows up in our handling of frame shifts. Note that dReal only considers $\delta$-decidability and can be incomplete in theory. We expect that most implementations will be collision free in a ``robust'' way (that is, two robots will not just not collide, they would be separated by a minimum distance). Therefore we believe the potential incompleteness is less of a concern. Indeed, the main limiting factor in our experiments was scalability for larger verification conditions. Formal methods have been applied to multi-robot planning \cite{Drona,Antlab}. These systems ignore programming or geometry concerns and view robots as sequences of motion primitives. \begin{comment} Assume guarantee reasoning for hybrid systems has been studied, e.g.~\cite{Nuzzo:EECS-2015-189,DBLP:journals/fteda/BenvenisteCNPRR18,DBLP:journals/pieee/NuzzoSBGV15,DBLP:journals/pieee/Tripakis16}. However, much of this work is described at the level of abstract models and not at the level of programs. Moreover, usually assume guarantee reasoning and contracts do not, at the same time, consider the effects of message based synchronisation. Our work shows how assume guarantee contracts can be propagated through program syntax. Systems such as Drona \cite{Drona} or Antlab \cite{Antlab} model robots as discrete systems with motion primitives, and the main technical contribution is to perform temporal multi-agent non-modular planning for tasks. Instead, we provide a concurrency model, a modular typing discipline, and proof rules that model correct interaction between dynamics (time is ignored in other task management and synthesis systems beyond atomic discrete-time motion primitives) and concurrency, and geometry (also ignored in these systems---robots are ``point objects”). The theory of hybrid automata \cite{ACHH,Henzinger96} provides a foundation for verifying abstract models of hybrid systems. The main emphasis in hybrid automaton research has been in defining semantics and designing model checking algorithms---too many to enumerate, see \cite{Henzinger96,Platzer18}---and not on programmability or compositional reasoning. In particular, most analysis techniques for hybrid automata construct the product automaton to reason about concurrent subsystems. Hybrid extensions to process algebras \cite{RoundsS03,DBLP:journals/iandc/LynchSV03,BERGSTRA2005215} extend process algebras with hybrid behaviour; the emphasis is to define a formal model and study classical concurrency issues such as process equivalences. Programming languages incorporating hybrid behaviour have been studied in the synchronous programming literature \cite{Zelus,Averest}. Hybrid synchronous languages, such as Zelus, extend a synchronous model with differential equations to capture continuous-time evolution of state. While these languages come with simulation, verification, and compilation tools, they restrict concurrency and there is little work in compositional reasoning or geometric reasoning. The use of nonstandard models to provide semantics to hybrid systems goes back to Iwasaki et al.~\cite{DBLP:conf/ijcai/IwasakiFSBG95}. Our inspiration came from the use of nonstandard analysis to provide semantics for hybrid synchronous languages \cite{DBLP:journals/fuin/BliudzeK09,DBLP:journals/jcss/BenvenisteBCP12,DBLP:conf/hybrid/BenvenisteBCPP14}. \citet{DBLP:conf/icalp/SuenagaH11,DBLP:conf/cav/HasuoS12} give a nonstandard semantics for a hybrid ``while-language'' and use it as the basis for deductive program verification and static analysis \cite{DBLP:conf/vmcai/KidoCH16}. In all these approaches, the discrete steps appear because of evaluating predicates: the semantics provides a clear notion of when a signal crosses zero. The languages do not have additional concurrency features, such as synchronisation through messages. Moreover, none of the existing approaches consider compositional proof systems and, in particular, local reasoning based on physical-variables-as-resource. \citet{CardelliG12} define a process algebra for geometric interaction. Their formalism combines communication and frame shifting. However, they do not consider dynamics, which is crucial in a robotics context. We were inspired by concurrent separation logics, which combine reasoning about concurrency, state, and separation \cite{CSL,JungSSSTBD15,DBLP:conf/wollic/GardnerZ07,DBLP:conf/concur/VafeiadisP07}. These logics have mostly been studied for discrete systems, but our nonstandard view makes them applicable to continuous systems as well. Our reasoning about geometric separation and about passing permissions through predicate refinements is reminiscent of similar principles in concurrent separation logics. The main obstacle to using separation logics in our context is the use of frame shifts, which make the footprint of a process not a local property of a process but the property of its ancestors in the attached composition. It is an interesting open problem to model geometric space as a resource in an appropriate separation logic; we leave it for future work. \end{comment} \section{Discussion and Future Directions} \label{sec:discussion} In this paper, we have shown how choreographies can be extended with dynamic motion primitives to enable compositional reasoning in the presence of continuous-time dynamics. We have developed an automated verification tool and a compiler from type-correct programs to distributed robotics applications using ROS and commercial and custom-made robotics hardware. Our goal is to \emph{integrate} types and static analysis techniques into existing robotics frameworks, rather than provide fully verified stacks (see, e.g., \cite{DBLP:conf/pldi/BohrerTMMP18}). We explain our language features in terms of a calculus but session processes can be easily embedded into existing frameworks for robot programming. % We have demonstrated that the language and type system are expressive enough to statically verify distributed manoeuvres on top of existing hardware and software. We view our paper as a first step in verifying robotics programs. There are many other important but yet unmodelled aspects. We outline several directions not addressed in our work. For example, we omit \emph{probabilistic robotics} aspects, including the perception stack (vision, LIDAR, etc.), and aspects such as filtering, localisation, and mapping \cite{ProbabilisticRobotics,LaValle2012}. These will require a probabilistic extension to our theory. Such a theory requires a nontrivial extension of program logics and analyses for probabilistic programs \cite{McIverMorgan} with the verification and synthesis for stochastic continuous-state systems \cite{ZamaniEMAL14}. We also omit any modeling of the perception stack or dynamic techniques, often based on machine learning, of learning the environment. Instead, our models \emph{assume} worst-case disturbance bounds on the sensing or dynamics. We believe an integration of learning techniques with formal methods is an interesting challenge but goes beyond the scope of this paper. Our framework statically verifies properties of a program. In practice, robots work in dynamic, often unknown, environments \cite{LaValle,LaValle2012,Siegwart,ProbabilisticRobotics}. When confronted with a formal method, domain experts often expect that a verification methodology should be able to verify correctness of behaviors in an \emph{arbitrary} dynamic environment and any failure to do so simply shows the inadequacy of verification techniques. Formal methods cannot prove correctness in an \emph{arbitrary} dynamic environment. When we verify a system, it is---as true in any formal methods---\emph{relative} to an environment assumption; such assumptions are usually implicit in robotics implementations. Thus, we can model moving obstacles, etc.\ in the environment through assumptions on the behaviour of such obstacles (e.g., limits on their speed or trajectories); these assumptions are propagated by our assume-guarantee proof system, and show up as a premise in the eventual correctness proof. We focus on communication safety and collision freedom as the basic correctness conditions any system has to satisfy. An interesting next step is to extend the reasoning to more expressive specifications. For safety specifications, such as invariants, one could reduce the problem to checking communication safety. For liveness specifications, the proof system would need to be extended with ranking arguments. While all the above problems are interesting in their own right, they are orthogonal to our main contribution that one can reason about concurrency and dynamics in continuous time in a type-based setting. Our future work will look at more expressive scenarios, but the setting in our paper already required complex proofs and it was important for us to get the core correct. We believe a verification system that can faithfully model and uniformly reason about more complex interactions and that scales to larger implementations remains a grand challenge in computer science (see, e.g., \cite{Lozano-Perez} for an articulation of these challenges). \begin{acks} % We thank the OOPSLA reviewers for useful comments and suggestions; and Julia Gabet for testing the artifact. Majumdar and Zufferey are supported in part by the Deutsche Forschungsgemeinschaft project 389792660 TRR 248--CPEC and by the European Research Council under the Grant Agreement 610150 (http://www.impact-erc.eu/) (ERC Synergy Grant ImPACT). Yoshida is supported in part by EPSRC EP/T006544/1, EP/K011715/1, EP/K034413/1, EP/L00058X/1, EP/N027833/1, EP/N028201/1, EP/T006544/1, EP/T014709/1 and EP/V000462/1, and NCSS/EPSRC VeTSS. \end{acks} \section{Multiparty Motion Session Calculus} \label{sec:calculus} We now describe the motion session calculus, extending from \cite{ECOOP19}. \subsection{Syntax} \myparagraph{Physical Components and Processes} We assume a fixed static set $\ensuremath{\Bbb P}$ of \emph{physical components} (ranged over by ${\sf p}$, $\pq$,...), which are often called \emph{participants} or \emph{roles}; these are the different components that constitute the overall system. Each physical component executes a software process, which takes care of communication, synchronisation and motion. We describe the motion session calculus, which forms the core of the software process. A value $\kf{v}$ can be a natural number $\kf{n}$, an integer $\kf{i}$, a boolean $\kf{true}$/$\kf{false}$, or a real number. % An expression $\kf{e}$ can be a variable, a value, or a term built from expressions by applying (type-correct) computable operators. A \emph{motion primitive} (\ensuremath{\mathit{a}}, \ensuremath{\mathit{b}}, $\ldots$) is an abstraction of underlying physical trajectories; for the moment, consider a motion primitive simply as a name and describe its semantics later. We use the notation $\motion{dt}{\ensuremath{\mathit{a}}}$ to represent that a motion primitive executes and time elapses. We write the tuple $\motion{dt}{({\sf p}_i: \ensuremath{\mathit{a}}_i)}$ to denote a group of processes executing their respective motion primitives at the same time. For the sake of simplicity, we sometimes use $\ensuremath{\mathit{a}}$ for both single or grouped motions. The \emph{processes} ($\ensuremath{{P}},Q,R,...$) of the multiparty motion session calculus are defined by: \[ \begin{array}{lll}\ensuremath{{P}} ::= \procout {{\sf p}}{\ell}{\kf{e}}{\ensuremath{{P}}} \ensuremath{~~\mathbf{|\!\!|}~~ } \sum\limits_{i\in I} \procin{{\sf p}}{\ell_i(x_i)}{\ensuremath{{P}}_i} \ensuremath{~~\mathbf{|\!\!|}~~ } \cond{\kf{e}}\ensuremath{{P}} \ensuremath{{P}} \ensuremath{~~\mathbf{|\!\!|}~~ } \sum\limits_{i\in I} \procin{{\sf p}}{\ell_i(x_i)}{\ensuremath{{P}}_i}+\motion{dt}{a}.{\ensuremath{{P}}} \ensuremath{~~\mathbf{|\!\!|}~~ } \motion{dt}{\ensuremath{\mathit{a}}}.\ensuremath{{P}} \ensuremath{~~\mathbf{|\!\!|}~~ } \mu{\roleVar}.\ensuremath{{P}} \ensuremath{~~\mathbf{|\!\!|}~~ } {\roleVar} \end{array} \] The output process $\procout{{\sf p}}{\ell}{\kf{e}}{\ensuremath{Q}}$ sends the value of expression $\kf{e}$ with label $\ell$ to participant ${\sf p}$. The sum of input processes (external choice) $\sum_{i\in I}\procin{{\sf p}}{\ell_i(x_i)}{\ensuremath{{P}}_i}$ is a process that can accept a value with label $ \ell_i $ from participant $ {\sf p}$ for any $ i\in I$; $\sum_{i\in I}\procin{{\sf p}}{\ell_i(x_i)}{\ensuremath{{P}}_i}+\motion{dt}{a}.{\ensuremath{{P}}}$ is an external choice with a \emph{default branch} with a motion action $\motion{dt}{a}.{\ensuremath{{P}}}$ which can always proceed when there is no message to receive. According to the label $\ell_i$ of the received value, the variable $x_i$ is instantiated with the value in the continuation process $ \ensuremath{{P}}_i$. We assume that the set $I$ is always finite and non-empty. Motion primitives are indicated by $\motion{dt}{\ensuremath{\mathit{a}}}$; the $\kf{dt}$ denoting that real time progresses when a motion primitive $\ensuremath{\mathit{a}}$ is executed. The conditional process $\cond{\kf{e}}{\ensuremath{{P}}}{Q} $ represents the internal choice between processes $ \ensuremath{{P}} $ and $ \ensuremath{Q} $. Which branch of the conditional process will be taken depends on the evaluation of the expression $ \kf{e}. $ The process $\mu {\roleVar}.\ensuremath{{P}}$ is a recursive process. Note that our processes do not have a null process: this is because a physical component does not ``disappear'' when the program stops. Instead, we model inaction with an iteration of some default motion primitive. \begin{example}[Processes]\rm The processes for the cart and the two robots from Figure~\ref{fig:basic_example_fig} are given as: \[ \begin{array}{cc} \begin{array}{rl}\small {\color{roleColor}{\mathsf{Cart}}}:\!\!\!\!\!\!\!\!\!\!\!\!\\ \mu {\roleVar}.\!\!\!\!\!\! & ({\color{roleColor}{\mathsf{GRobot}}}!\mathit{arrive}.{\color{roleColor}{\mathsf{RRobot}}}!\mathit{free}.\\ & \quad \motion{dt}{\mathsf{m\_move}(\text{co-ord of }{\color{roleColor}{\mathsf{GRobot}}})}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{ready}.\\ & \quad \motion{dt}{\mathsf{m\_idle}}.{\color{roleColor}{\mathsf{GRobot}}}?\mathit{ok}.\motion{dt}{\mathsf{m\_move}(\text{base})}.{\roleVar}\\ & + \textrm{ symmetrically for ${\color{roleColor}{\mathsf{RRobot}}}$ }) \end{array} & \!\!\!\!\!\!\!\! \begin{array}{rl} \small {\color{roleColor}{\mathsf{RRobot}}},\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\\\ {\color{roleColor}{\mathsf{GRobot}}}:\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\\ \mu {\roleVar}.\!\!\!\!\!\!& ({\color{roleColor}{\mathsf{Cart}}}?\mathit{arrive}.\motion{dt}{\mathsf{work}}.{\color{roleColor}{\mathsf{Cart}}}?\mathit{ready}.\\ & \quad \ \motion{dt}{\mathsf{pick}}.{\color{roleColor}{\mathsf{Cart}}}!\mathit{ok}.\motion{dt}{\mathsf{work}}).{\roleVar}\\ & \ + \ ({\color{roleColor}{\mathsf{Cart}}}?\mathit{free}.\motion{dt}{\mathsf{work}}).{\roleVar}\\ \end{array} \end{array} \] Note that for both processes, the recursion ensures that the program does not terminate. Motion primitives for the cart involve moving to various locations $\mathsf{m\_move}(\mathit{pos})$ and idling at a location ($\mathsf{m\_idle}$), and those for the robots involve doing some (unspecified) work $\mathsf{work}$ or picking items off the cart $\mathsf{pick}$ (internally, these motion primitives would involve motion planning and inverse kinematics for the robot arms). Next, we describe the modelling and representation of motion primitives in more detail. \end{example} \myparagraph{Physical Variables and Footprint} Motion primitives make the robot ``move'' in the physical world. Each motion primitive represents an abstraction of an underlying controlled dynamical system, such as the controller for the robot arm or the controller for a cart. The dynamical system changes underlying physical state (such as the position and orientation of the arm or the position and velocity of the cart). The dynamics can be coupled: for example, if an arm is mounted on a cart, then the motion of the cart is influenced by the mass and position of the arm. We model the underlying physical system using \emph{physical variables}, and we partition these into state variables $X$ (dynamical variables read and controlled by the component), input variables $W$ (dynamical variables read by the component, whose values are provided by the environment). The specification of a motion primitive will constrain the values of these variables over time. We make the physical variables clear by writing ${\roleP} \ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}}{{X}}{{W}}$ for a physical component ${\roleP}\in \ensuremath{\Bbb P}$ with state and input variables $X$ and $W$, respectively, which executes the process $\ensuremath{{P}}$. Each physical component ${\roleP}\in \ensuremath{\Bbb P}$ has a \emph{geometric footprint} $\geom{{\roleP}}$ associated with it. This represents the physical space occupied by the component, and will be used to ensure that two components do not collide. The footprint is a function from valuations to variables in $X$ to a subset of $ℝ^3$. It describes an overapproximation of the space occupied by the component as a function of the current state. Note that the footprint can depend on the state. \begin{example}\rm \label{ex:mp-footprint} Let $x$ and $v$ denote the position and the velocity of the cart, respectively, restricting the discussion only on one axis. Thus, $X = \set{x, v}$. If we assume there are no external influences on the cart, we can take $W = \emptyset$. The footprint provides a bounding box around the cart as it moves. If the cart has dimensions $(l, w, h)$, the footprint at the location $(x, y, z)$ is \begin{align} \set{(\mathsf{x}, \mathsf{y}, \mathsf{z}) \mid x-\frac{l}{2} \leq \mathsf{x} \leq x+\frac{l}{2} \wedge 0\leq \mathsf{y} \leq h \wedge z -\frac{w}{2} \leq \mathsf{z} \leq z+\frac{w}{2} } \end{align} \end{example} \myparagraph{Composition} We now define parallel composition of physical components. Composition of physical components ensure the following aspects. First, like process calculi, parallel composition provides a locus for message exchange: a physical component can send messages to, or receive messages from, another one. Second, composition connects physical state variables of one component to the physical input variables of another---this enables the coupling of the underlying dynamics. To ease reasoning about connections between physical variables, we assume that the components in a composition have disjoint sets of physical and logical variables, and connections occur through syntactic naming of input variables. Thus, a component with an input variable $x$ gets its value from the unique component that has a physical state variable called $x$. Hence, there is no ambiguity in forming connections. We refer to the variables of ${\roleP}$ as ${\roleP}.X$ and ${\roleP}.W$. We define a \emph{multiparty session} as a parallel composition of pairs of participants and processes: \[ \begin{array}{lll} M & ::= & {\sf p}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}}{X}{W} \ensuremath{~~\mathbf{|\!\!|}~~ } M \ensuremath{~|~} M \end{array} \] with the intuition that process $\ensuremath{{P}}$ plays the role of participant ${\sf p}$, % and can interact with other processes playing other roles in $M$. % A multiparty session is \emph{well-formed} if all its participants are different, and for each input variable of each participant there is a syntactically unique state variable in a different participant so that connections between physical variables is well-defined. We consider only well-formed processes. \begin{example}\rm For the example from {Sec.}~\ref{sec:example}, the multiparty session is \[ {\color{roleColor}{\mathsf{Cart}}}\ensuremath{\triangleleft{}}\proc{\text{proc.\ for ${\color{roleColor}{\mathsf{Cart}}}$}}{\set{x,v}}{\emptyset} \ensuremath{~|~} {\color{roleColor}{\mathsf{RRobot}}} \ensuremath{\triangleleft{}}\proc{\text{proc.\ for ${\color{roleColor}{\mathsf{RRobot}}}$}}{\cdot}{\cdot} \ensuremath{~|~} {\color{roleColor}{\mathsf{GRobot}}} \ensuremath{\triangleleft{}}\proc{\text{proc.\ for ${\color{roleColor}{\mathsf{GRobot}}}$}}{\cdot}{\cdot} \] (we have omitted the physical variables for the robot arms for simplicity). \end{example} \subsection{Motion Primitives} \label{sec:mp-rules} Before providing the operational semantics, we first consider how motion primitives are specified. Recall that motion primitives of a component ${\roleP}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}}{X}{W}$ abstract a trajectory arising out of the underlying dynamics. A first idea is to represent a motion primitive as a pair $\tuple{\ensuremath{\mathrm{Pre}\xspace}, \ensuremath{\mathrm{Post}\xspace}}$---this provides a precondition $\ensuremath{\mathrm{Pre}\xspace}$ that specifies the condition on the state under which the motion primitive can be applied and a postcondition $\ensuremath{\mathrm{Post}\xspace}$ that specifies the effect of applying the motion primitive on the physical state. However, this is not sufficient: the motion of two components can be coupled in time and the trajectory of a component depends on the inputs it gets from other components and, in turn, its trajectory influences the trajectories of the other components. Therefore, a motion primitive also needs to specify \emph{assumptions} on its external inputs and \emph{guarantees} it provides to other processes over time. These predicates are used to decouple the dynamics. Our motion primitive has three more ingredients. The first is the \emph{footprint}: the geometric space used by a process over time while it executes its trajectory and is used to ensure geometric separation between components. The second is a pair $(D, {\ddagger})$ of a \emph{time interval and an annotation}: the time interval bounds the \emph{minimal} and \emph{maximal times} between which a motion primitive is ready to communicate via message passing, and the ${\ddagger}$ annotation distinguishes between motion primitives that are interruptible by external messages from those that cannot be interrupted. We assume preconditions and postconditions only depend on the state, while assumptions, guarantees, and footprints may depend on both the state and the elapsed time. \begin{definition}[Motion primitive] The specification for a motion primitive $\ensuremath{\mathit{a}}$ of a physical process ${\roleP}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}}{X}{W}$, written $\judgement{\ensuremath{\mathit{a}}}{\ensuremath{\mathrm{Pre}\xspace},A,G,\ensuremath{\mathrm{Post}\xspace},\ensuremath{\mathit{FP}},D, {\ddagger}}$, consists of two predicates \emph{precondition} $\ensuremath{\mathrm{Pre}\xspace}$ and \emph{postcondition} $\ensuremath{\mathrm{Post}\xspace}$ over $X\cup W$, an \emph{input assumption} $A$ which is a predicate over $W\cup\set{\ensuremath{\mathsf{clock}}\xspace}$, an \emph{output guarantee} $G$ which is a predicate over $X\cup\set{\ensuremath{\mathsf{clock}}\xspace}$, a \emph{footprint} $\ensuremath{\mathit{FP}}$ which is a predicate over $X \cup \set{\mathsf{x},\mathsf{y},\mathsf{z},\ensuremath{\mathsf{clock}}\xspace}$, a \emph{duration} $D\in (ℝ\cup\set{\infty})^2$ which is a time interval, and ${\ddagger}\in\set{{\mathsf{\lightning}},{\mathsf{\rightsquigarrow}}}$ which indicates if the motion primitive can be interrupted by an external message (${\mathsf{\lightning}}$) or not (${\mathsf{\rightsquigarrow}}$). Given motion primitives $\ensuremath{\mathit{a}}$ and $\ensuremath{\mathit{a}}'$, we say $\ensuremath{\mathit{a}}$ \emph{refines} $\ensuremath{\mathit{a}}'$, denoted by $\ensuremath{\mathit{a}} \ensuremath{\preceq} \ensuremath{\mathit{a}}'$, with $\judgement{\ensuremath{\mathit{a}}}{φ,A,G,ψ,\ensuremath{\mathit{FP}}, D, {\ddagger}}$ and $\judgement{\ensuremath{\mathit{a}}'}{φ',A',G',ψ',\ensuremath{\mathit{FP}}', D', {\ddagger}'}$ iff (1) $φ ⇒ φ'$, (2) $A ⇒ A'$, (3) $G' ⇒ G$, (4) $ψ' ⇒ ψ$, (5) $\ensuremath{\mathit{FP}}' ⊆ \ensuremath{\mathit{FP}}$, (6) ${\ddagger} = {\ddagger}'$, and (7) either ${\ddagger} ={\mathsf{\lightning}}$ and $D⊆ D'$ or ${\ddagger}={\mathsf{\rightsquigarrow}}$ and $D' ⊆ D$. \end{definition} \subsection{Operational Semantics} \label{sec:opsem} The operational semantics is given as reduction rules relative to \emph{stores} $\sstore{X},\sstore{W}$ (Figure~\ref{fig:opsem}) that map physical variables to values. The semantics uses the standard structural rules defined in Figure~\ref{tab:sync:congr}. We adopt some standard conventions regarding the syntax of processes and sessions. Namely, we will use $\prod_{i\in I} {{\sf p}_i}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}_i}{X_i}{W_i}$ for ${{\sf p}_1}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}_1}{X_1}{W_1}\ensuremath{~|~} \ldots\ensuremath{~|~} {{\sf p}_n}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}_n}{X_n}{W_n},$ where $I=\set{1,\ldots,n}$, or simply as $\prod_{i\in I} \pa{{\sf p}_i}{\ensuremath{{P}}_i}$ when the physical variables are not important. We use infix notation for external choice process, e.g., instead of $\sum_{i\in \{1,2\}} \procin{{\sf p}}{\ell_i(x)}{\ensuremath{{P}}_i}$, we write $\procin{{\sf p}}{\ell_1(x)}{\ensuremath{{P}}_1}+\procin{{\sf p}}{\ell_2(x)}{\ensuremath{{P}}_2}.$ {\em The value $\kf{v}$ of expression $\kf{e}$ with physical state $\sstore{X}$} (notation $\evalState{\kf{e}}{\kf{v}}{\sstore{X}}$) is computed as expected. We assume that $\evalState{\kf{e}}{\kf{v}}{\sstore{X}}$ is effectively computable and takes logical ``zero time.'' \begin{figure}[!t] \label{tab:sync:red} \small \[ \begin{array}[t]{@{}c@{}} \rulename{recv}\inferrul { j\in I } { {\sf p}\ensuremath{\triangleleft{}}\proc{\sum\limits_{i\in I} \procin{\pq}{\ell_i(x)}{\ensuremath{{P}}_i} + \motion{dt}{a}.{\ensuremath{{P}}} }{\sstore{X}}{\sstore{W}} \xrightarrow{\pq?\ell_j(v)} {\sf p}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}_j\set{v/x}}{\sstore{X}}{\sstore{W}} } \\[5mm] \rulename{send} \inferrul { \evalState{\kf{e}}{\kf{v}}{\sstore{X},\sstore{W}} }{ {\sf p}\ensuremath{\triangleleft{}}\proc{\procout{\pq}{\ell_j}{\kf{e}}{Q}}{\sstore{X}}{\sstore{W}} \xrightarrow{\pq!\ell\tuple{\kf{v}}} {\sf p}\ensuremath{\triangleleft{}}\proc{Q}{\sstore{X}}{\sstore{W}} } \quad \rulename{comm} \inferrul { \pa{\sf p}{\ensuremath{{P}}} \xrightarrow{\pq!\ell\tuple{\kf{v}}} \pa{\sf p}{\ensuremath{{P}}'}\\ \pa\pq{\ensuremath{Q}} \xrightarrow{{\sf p}?\ell(\kf{v})} \pa\pq{\ensuremath{Q}'}\\ } { \pa{\sf p}{\ensuremath{{P}}} \ensuremath{~|~} \pa\pq{\ensuremath{Q}} \longrightarrow{} \pa{\sf p}{\ensuremath{{P}}'} \ensuremath{~|~} \pa\pq{\ensuremath{Q}'} } \\[6mm] \inferrule[\rulename{default}] { {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\tau} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT 0}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \\ {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT 0}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}},\xi,\nu, t} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t}.\ensuremath{{P}}}{\sstore{X}'}{\sstore{W}'} } { {\sf p}\ensuremath{\triangleleft{}} \proc{\sum\limits_{i\in I} \procin{\pq}{\ell_i(x)}{\ensuremath{{P}}_i} + \motion{\dtsess}{a}.{\ensuremath{{P}}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}},\xi,\nu, t} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t}.\ensuremath{{P}}}{\sstore{X}'}{\sstore{W}'} } \\[5mm] \inferrule[\rulename{traj-base}] { \ensuremath{\mathrm{Pre}\xspace}\{\sstore{X}/X,\sstore{W}/W, 0/\ensuremath{\mathsf{clock}}\xspace\}\quad A\{\sstore{W}/W, 0/\ensuremath{\mathsf{clock}}\xspace\}\wedge G\{\sstore{X}/X, 0/\ensuremath{\mathsf{clock}}\xspace\} \\ \geom{{\sf p}}(\sstore{X})\subseteq\ensuremath{\mathit{FP}}\set{\sstore{X}/X,0/\ensuremath{\mathsf{clock}}\xspace} } { {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\tau} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT 0}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} } \\[5mm] \rulename{traj-step} \inferrul { \xi: [t_1,t_2] \rightarrow ℝ^X, \nu: [t_1,t_2] \rightarrow ℝ^W\\ \xi(t_1) = \sstore{X}, \xi(t_2) = \sstore{X}' \\ \nu(t_1) = \sstore{W}, \nu(t_2) = \sstore{W}' \\ \forall t\in [t_1,t_2].\ A\{\nu(t)/W, t/\ensuremath{\mathsf{clock}}\xspace\} \wedge G\{\xi(t)/X, t/\ensuremath{\mathsf{clock}}\xspace\} \ \wedge \geom{{\sf p}}(\xi(t))\subseteq\ensuremath{\mathit{FP}}\set{\sstore{X}/X,t/\ensuremath{\mathsf{clock}}\xspace} } { {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t_1}.P}{\sstore{X}}{\sstore{W}} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}},\xi,\nu, t_2-t_1} {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t_2}.P}{\sstore{X}'}{\sstore{W}'} } \\[7mm] \inferrule[\rulename{t-conditional}] { \evalState{\kf{e}}{\kf{true}}{\sstore{X},\sstore{W}} } { {\sf p}\ensuremath{\triangleleft{}}\proc{\cond{\kf{e}}{\ensuremath{{P}}}{\ensuremath{Q}}}{\sstore{X}}{\sstore{W}} \xrightarrow{} {\sf p}\ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} } \quad \inferrule[\rulename{non-interrupt}] { t \in D\\ {\ddagger} = {\mathsf{\rightsquigarrow}}\\ \ensuremath{\mathrm{Post}\xspace}\set{\sstore{X}/X,\sstore{W}/W,t/\ensuremath{\mathsf{clock}}\xspace}\\ } { {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\tau} {\sf p}\ensuremath{\triangleleft{}} \proc{\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} } \\[5mm] \rulename{interrupt} \inferrul { t \in D\\ {\ddagger} = {\mathsf{\lightning}}\\ \ensuremath{\mathrm{Post}\xspace}\set{\sstore{X}/X,\sstore{W}/W,t/\ensuremath{\mathsf{clock}}\xspace}\\ {\sf p}\ensuremath{\triangleleft{}} \proc{\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\pq?\ell(\kf{v})} {\sf p}\ensuremath{\triangleleft{}} \proc{\ensuremath{{P}}'}{\sstore{X}}{\sstore{W}} } { {\sf p}\ensuremath{\triangleleft{}} \proc{\motion{\dtsess}{\ensuremath{\mathit{a}}\AT t}.\ensuremath{{P}}}{\sstore{X}}{\sstore{W}} \xrightarrow{\pq?\ell(\kf{v})} {\sf p}\ensuremath{\triangleleft{}} \proc{\ensuremath{{P}}'}{\sstore{X}}{\sstore{W}} } \\[5mm] \rulename{m-par} \inferrul { \exists \xi, \nu.~ \forall i,j \in I.\\ i\neq j \Rightarrow \mathsf{disjoint}(\ensuremath{\mathit{a}}_i,\ensuremath{\mathit{a}}_j) \\ {\sf p}_i\ensuremath{\triangleleft{}}\proc{P_i}{\sstore{X}_i}{\sstore{W}_i} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}_i},\xi|_{X_i}, (\xi\cup\nu)|_{W_i}, t} {\sf p}_i\ensuremath{\triangleleft{}}\proc{P_i'}{\sstore{X}'_i}{\sstore{W}'_i}\\ } { \prod_{i \in I} {\sf p}_i\ensuremath{\triangleleft{}}\proc{P_i}{\sstore{X}_i}{\sstore{W}_i} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}_i}, t} \prod_{i \in I} {\sf p}_i\ensuremath{\triangleleft{}}\proc{P_i'}{\sstore{X}'_i}{\sstore{W}'_i} } \\[6mm] \rulename{r-par$\tau$} \inferrul { M_1 \xrightarrow{\tau} M_2 } { M_1 \ensuremath{~|~} M \xrightarrow{\tau} M_2 \ensuremath{~|~} M } \qquad \rulename{r-par} \inferrul { M_1 \longrightarrow{} M_2 } { M_1 \ensuremath{~|~} M \longrightarrow{} M_2 \ensuremath{~|~} M } \qquad \rulename{r-struct} \inferrul { M'_1\equiv M_1 \xrightarrow{\alpha} M_2 \equiv M'_2 } { M'_1 \xrightarrow{\alpha} M'_2 } \end{array} \] \noindent We omit \rulename{f-conditional}. We use $\xrightarrow{\alpha}$ for any labelled transition relation or reduction ($\xrightarrow{}$). \caption{Operational semantics} \label{fig:opsem} \vspace*{-0.5cm} \end{figure} \begin{figure}{} $ \small \begin{array}[t]{@{}c@{}} \inferrule[\rulename{s-rec}]{}{ \mu {\roleVar}.\ensuremath{{P}} \equiv \ensuremath{{P}}\sub{\mu {\roleVar}.\ensuremath{{P}}}{{\roleVar}} } \quad \inferrule[\rulename{s-multi}]{}{ \ensuremath{{P}} \equiv \ensuremath{Q} \Rightarrow \pa{\sf p}\ensuremath{{P}} \ | \ M\equiv\pa{\sf p}\ensuremath{Q} \ | \ M } \quad \inferrule[\rulename{s-par 1}]{}{ M \ | \ M' \equiv M' \ | \ M } \quad \inferrule[\rulename{s-par 2}]{}{ (M \ | \ M') \ | \ M'' \equiv M \ | \ ( M' \ | \ M'') } \end{array} $ \caption{Structural congruence rules} \label{tab:sync:congr} \vspace*{-0.5cm} \end{figure} For reduction rules that do not change the physical state, we omit writing the physical state in the rule. Time is global, and processes synchronize in time to make concurrent motion steps of the same (but not pre-determined) duration. Communication (\rulename{comm}) is synchronous and puts together sends and receives. Rule \rulename{default} selects the default branch. Rules for conditionals, communication without default motion and parallel composition are defined in a standard way \cite{ECOOP19,DGJPY2016,GHPSY19}. To define the operational semantics for motions, we extend the process syntax $P$ with time-annotated motion primitives, $\motion{dt}{\ensuremath{\mathit{a}}\AT t}\quad \text{ for }t\geq 0$. Let us fix a component ${\sf p}$ and its motion primitive $\judgement{\ensuremath{\mathit{a}}}{\ensuremath{\mathrm{Pre}\xspace},A,G,\ensuremath{\mathrm{Post}\xspace},\ensuremath{\mathit{FP}},D,{\ddagger}}$. Rules \rulename{traj-base} and \rulename{traj-step} set up trajectories for each motion primitive. We distinguish between interruptible (\rulename{interrupt}) and non-interruptible (\rulename{non-interrupt}) motion primitives. Non-interruptible motion primitives are consumed by the process. Interruptible motion primitives consume the motion primitive on a message receipt. The parallel composition rule \rulename{m-par} requires a consistent global trajectory and ensures that when (physical) time elapses for one process, it elapses equally for all processes. Here, $\mathsf{disjoint}(\ensuremath{\mathit{a}}_i, \ensuremath{\mathit{a}}_j)$ states that the footprints along the trajectory are disjoint: $\ensuremath{\mathit{a}}_i.\ensuremath{\mathit{FP}}\set{\xi_i(t')/X,t'/\ensuremath{\mathsf{clock}}\xspace}\cap\ensuremath{\mathit{a}}_j.\ensuremath{\mathit{FP}}\set{\xi_j(t')/X,t'/\ensuremath{\mathsf{clock}}\xspace}=\emptyset$ for all $t'\in[0,t]$. We use $\longrightarrow^*$ for the reflexive transitive closure of $\longrightarrow$. We say a program state $\prod_i {\sf p}_i \ensuremath{\triangleleft{}}\proc{\ensuremath{{P}}_i}{\sstore{X}_i}{\sstore{W}_i}$ is \emph{collision free} if $\geom{{\sf p}_i}(\sstore{X}_i)\cap\geom{{\sf p}_j}(\sstore{X}_j) = \emptyset$ for every $i\neq j$. \subsection{Joint Compatibility of Motion Primitives} Two motion primitives are \emph{compatible} if they can be jointly executed. To decide compatibility, we compose the specifications using the following \emph{assume-guarantee proof rule}:\\ \centerline{ $ \small \begin{array}{ll} \begin{array}{ll} \rulename{AGcomp}\\\\\\\\\ \end{array} & \inferrule{ \exists \ensuremath{\mathit{FP}}_1, \ensuremath{\mathit{FP}}_2.\ G_1 \wedge G_2 \Rightarrow \ensuremath{\mathit{FP}}_1 \cap FP_2 = \emptyset\quad G_1 \wedge G_2 \Rightarrow \ensuremath{\mathit{FP}}_1 \cup FP_2 \subseteq \ensuremath{\mathit{FP}}\\\\ {\ddagger}_1 ={\mathsf{\lightning}} \vee {\ddagger}_2 = {\mathsf{\lightning}} \quad {\ddagger}_1 ={\mathsf{\rightsquigarrow}} ⇒ D₁ ⊆ D₂ \quad {\ddagger}_2 ={\mathsf{\rightsquigarrow}} ⇒ D₂ ⊆ D₁ \\\\ \ensuremath{\mathit{a}}_1 \ensuremath{\preceq} \tuple{φ₁,A∧ G₂,G₁,\ensuremath{\mathit{FP}}_1,ψ₁,D_1,{\ddagger}_1}\quad \ensuremath{\mathit{a}}_2 \ensuremath{\preceq} \tuple{φ₂,A∧ G₁,G₂,\ensuremath{\mathit{FP}}_2,ψ₂,D_2,{\ddagger}_2} } {\hspace*{-2mm}\judgement{\tuple{{\sf p}_1{:}\ensuremath{\mathit{a}}_1, {\sf p}_2{:}\ensuremath{\mathit{a}}_2}}{φ₁∧φ₂,A,G₁∧G₂,\ensuremath{\mathit{FP}},ψ₁∧ψ₂,D₁∩D₂,{\ddagger}_1\oplus{\ddagger}_2}} \end{array} $}% \noindent The $\oplus$ operator combines the interruptibility: ${\mathsf{\lightning}} \oplus {\mathsf{\lightning}} = {\mathsf{\lightning}}$ and ${\mathsf{\lightning}} \oplus {\mathsf{\rightsquigarrow}} = {\mathsf{\rightsquigarrow}} \oplus {\mathsf{\lightning}} = {\mathsf{\rightsquigarrow}} \oplus{\mathsf{\rightsquigarrow}} = {\mathsf{\rightsquigarrow}}$. The \rulename{AGcomp} rule performs three checks. First, the check on footprints ensures that the motion primitives are disjoint in space (there is a way to find subsets $\ensuremath{\mathit{FP}}_1$ and $\ensuremath{\mathit{FP}}_2$ of the footprint $\ensuremath{\mathit{FP}}$ so that the composed motion primitives are in these disjoint portions). Second, the guarantee of one motion primitive is used as the assumption of the other to check that they are compatible. Third, the checks on timing ensures that at most one process executes a non-interruptible motion primitive and the interruptible ones are ready before the non-interruptible one. We say $\motion{\dtsess}{({\sf p}_i {:} \ensuremath{\mathit{a}}_i)}$ is \emph{compatible} from $\ensuremath{\mathrm{Pre}\xspace}$ if there exist $G$, $\ensuremath{\mathrm{Post}\xspace}$, $\ensuremath{\mathit{FP}}$, and $D$ such that $\judgement{\prod_i{{\sf p}_i:\ensuremath{\mathit{a}}_i}}{\ensuremath{\mathrm{Pre}\xspace}, \kf{true}, G, \ensuremath{\mathrm{Post}\xspace}, \ensuremath{\mathit{FP}}, D, {\ddagger}}$ is derivable using \rulename{AGcomp} repeatedly. Thus, compatibility checks that motion primitive specifications can be put together if processes start from their preconditions: first, the assumptions and guarantees are compatible; second, there is no ``leftover'' assumption; and third, the footprints of the motion primitives do not intersect in space. Compatibility provides the ``converse'' condition that allows joint trajectories in \rulename{M-par} to exist. The next theorem formalizes what motion compatibility guarantees. Intuitively, motion compatibility means it is sufficient to check the compatibility of contracts to guarantee the existence of a joint trajectory, i.e., the execution is defined for all the components and the joint trajectory satisfies the composition of the contracts. \begin{restatable}[Motion Compatibility]{theorem}{theoremMC} \label{th:motion-compat} Suppose $\motion{\dtsess}{({\sf p}_1:\ensuremath{\mathit{a}}_1,{\sf p}_2:\ensuremath{\mathit{a}}_2)}$ is compatible. For every $t\in D$, if there exist trajectories $\xi_1, \xi_2,\nu_1,\nu_2$ such that $\pa{{\sf p}_i}{\ensuremath{{P}}_i} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}_i},\xi_i, \nu_i, t} \pa{{\sf p}_i}{\ensuremath{{P}}_i'}$ for $i\in \set{1,2}$, then there exist trajectories $\xi:[0,t]\rightarrow ℝ^{X_1\cup X_2}, \nu:[0,t]\rightarrow ℝ^{W_1\cup W_2 \setminus (X_1\cup X_2)}$ such that $\pa{{\sf p}_i}{\ensuremath{{P}}_i} \xrightarrow{\motion{\dtsess}{\ensuremath{\mathit{a}}_i},\xi|_{X_i}, \nu|_{W_i}, t} \pa{{\sf p}_i}{\ensuremath{{P}}_i'}$ and for all $0 \leq t' \leq t$, the footprints of ${\sf p}_1$ and ${\sf p}_2$ are disjoint: $\geom{{\sf p}_1}({\xi(t')|_{X_1}}) \cap \geom{{\sf p}_2}({\xi(t')|_{X_2}}) = \emptyset$. \end{restatable} \begin{proof} (Sketch.) This theorem is proved along the lines of the AG rule by \citet{DBLP:conf/hybrid/HenzingerMP01}. Their proof relies on motion primitives having the following properties: prefix closure, deadlock freedom, and input permissiveness. Deadlock freedom is, in this setting \cite{DBLP:conf/hybrid/HenzingerMP01}, means that if a precond is satisfied then the trajectory must exists, and every execution that does not yet satisfies the postcondition can be prolonged be extended. Input permissiveness states that a component cannot deadlock no matter how the environment decides to change the inputs. This condition is needed to do induction over time. Input permissiveness does not directly follow from the definition of our contracts. However, it holds when the environment changes the inputs in a way that is allowed by the assumptions. As \rulename{AGcomp} checks that this is true and rejects the composition otherwise, we can reuse the same proof strategy. A process should not be allowed to block time making the system ``trivially safe'' but physically meaningless. We also need to check the disjointness of footprints which is new in our model (needed by \rulename{M-par}). This is also checked by \rulename{AGcomp}. \end{proof} \subsection{Examples for motion primitives, compatibilities and environments} \myparagraph{Motion primitives from dynamics} \label{ex:motion} For the ${\color{roleColor}{\mathsf{Cart}}}$ in {Sec.}~\ref{sec:example}, we can derive motion primitives from a simple dynamical model $\dot{x} = v, \dot{v} = u$. Here, $X = \set{x,v}$ and $W= \emptyset$. For simplicity, assume the cart moves along a straight line (its $x$-axis) and that the control $u$ can apply a fixed acceleration $a_{\max}$ or a fixed deceleration $-a_{\max}$. Consider the motion primitive $\mathsf{m\_move}$ which takes the cart from an initial position and velocity $(x_i, v_i)$ to a final position $(x_f, v_f)$. From high school physics, we can solve for $x$ and $v$, given initial values $x_i$ and $v_i$:\\ \centerline{$ x = x_i + v_it + \frac{1}{2}a_{\max} t^2 \mbox{ and } v = v_i + a_{\max} t $} from which, by eliminating $t$, we have $(v - v_i)^2 = 2 a (x - x_i)$. Suppose that the cart starts from rest ($v_i=0$), accelerates until the midpoint $\mathit{mid} = \frac{1}{2}(x_i+x_f)$, and thereafter decelerates to reach $x_f$ again with velocity $v_f= 0$. The precondition $\ensuremath{\mathrm{Pre}\xspace}$ is $x_f > x\wedge v = 0$, the first conjunction saying we move right (we can write another motion primitive for moving left). The assumption $A$ is $\kf{true}$, and the guarantee is\\ \centerline{ $x_i \leq x \leq x_f \wedge \left( \begin{array}{c} (x_i \leq x \leq \mathit{mid} \Rightarrow v^2 = 2 a_{\max} (x - x_i)) \wedge\\ (\mathit{mid} \leq x \leq x_f \Rightarrow v^2 = 2 a_{\max} (x_f - x)) \end{array} \right) $}\\[1mm] The postcondition is $x = x_f \wedge v = 0$. The footprint provides a bounding box around the cart as it moves, and is given as in Example~\ref{ex:mp-footprint}. We assume that the motion cannot be interrupted. Thus, we place the annotation ${\mathsf{\rightsquigarrow}}$. The least time to destination is $t_m = 2\sqrt{(x_f-x_i)/a_{\max}}$ and the duration (the interval when it is ready to communicate) is $[t_m, \infty)$. A simpler primitive is $\mathsf{m\_idle}$: it keeps the cart stationary. Its assumption is again $\kf{true}$, guarantee (and postcondition) is $x = x_i \wedge v = 0$, footprint is a bounding box around the fixed position. It is interruptible by messages from other components (annotation ${\mathsf{\lightning}}$) at any time: $D = [0,\infty)$. \myparagraph{Compatibility} Now consider the constraints that ensure the joint trajectories involving the ${\color{roleColor}{\mathsf{Cart}}}$'s motion and the ${\color{roleColor}{\mathsf{Prod}}}$'s $\mathsf{work}$ primitive are compatible. First, note that the motion of the cart is non-interruptible (${\mathsf{\rightsquigarrow}}$) but we assume the arm is interruptible, satisfying the constraint in \rulename{AGcomp} that at most one motion is not interruptible. Instead of the complexities of modeling the geometry and the dynamics of the arm, we approximate the footprint of the arm (the geometric space it occupies) as a half-sphere centered at the base of the arm and extending upward. Assume first that the motion primitive guarantees that the state is always within this half-sphere. In order for the cart and the robot arm to be compatible, we have to check that the footprints do not overlap. Our guarantee is too weak to prove compatibility, as the footprint of the cart and the arm can intersect when the cart is close to the arm. Instead, we strengthen the guarantee to state that the arm can use the entire sphere when the cart is far and as the cart comes closer the arm effector moves up to make space. To realise this motion, the cart sends the arm the following information with $\mathit{arrive}$:\footnote{ For clarity, the type in Figure~\ref{fig:basic-example} omits parameters to messages. Our type system uses predicated refinements to reason about parameters. } its current position $x_i$, its target position $x_f$, and a lower bound $t_{\mathit{ref}}$ on the time it will take to arrive at $x_f$. The footprint for the cart's motion can be specified by $\set{(\mathsf{x}, \mathsf{y}, \mathsf{z}) \mid \mathsf{x} ≤ x_0 + l/2 + (x_1 - x_0) * t / t_{\mathit{ref}} ∧ … }$. For the producer, suppose $R_{\mathit{base}}$ is the radius of its base and $x_{{\color{roleColor}{\mathsf{Prod}}}}$ its $x$ coordinate. The footprint of the $\mathsf{work}$ action is strengthened as $\set{(\mathsf{x}, \mathsf{y}, \mathsf{z}) \mid (\mathsf{z} > \min(c t, h) \lor |\mathsf{x} - x_{\color{roleColor}{\mathsf{Prod}}}| ≤ R_{\mathit{base}}) ∧ … }$, where $c ≥ h \cdot |x_0 -l - x_{\color{roleColor}{\mathsf{Prod}}} - R_{\mathit{base}}| / t_{\mathit{ref}}$. Finally, for compatibility, we need to check that both ${\color{roleColor}{\mathsf{Cart}}}$ and ${\color{roleColor}{\mathsf{Prod}}}$ can adhere to their footprint and that the footprints are disjoint. Disjointness is satisfied if $x_1 + l < x_{\color{roleColor}{\mathsf{Prod}}} - R_{\mathit{base}}$, set this as a precondition to $\mathsf{m\_move}$. \myparagraph{Environment Assumptions} We can model a more complex cart moving in a dynamic environment by adding a new component (participant) ${\color{roleColor}{\mathsf{Env}}}$ (for \emph{environment}). The physical variables of the environment process encode dynamic properties of the state, such as obstacles in the workspace or external disturbances acting on the cart. We can abstract the environment assumptions into a single motion primitive whose guarantees provide assumptions about the environment behavior to the other components. For example, the environment providing a bounded disturbance of magnitude to the cart's acceleration could be modeled as the guarantee $-1 \leq d \leq 1$ for a physical variable $d$ (for \emph{disturbance}) of ${\color{roleColor}{\mathsf{Env}}}$. The cart can include this input variable in its dynamics: $\dot{v} = u + d$. We can also model sensor and actuator errors in this way. Likewise, we can model obstacles by a physical variable in the environment that denotes the portions of the state space occupied by obstacles, exporting this information through the guarantees, and using this information when the cart plans its trajectory in $\mathsf{m\_move}$. \begin{comment} \RMi{NEED TO FIX FROM HERE} We impose more structured communications by checking the compatibility of assume-guarantee contracts in motion types. Suppose that $\Gmotion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}{\ensuremath{{\sf G}}}$ appears in the global type. This indicates that the specification expects the components ${\sf p}_i$, $i\in I$, to jointly execute motion primitives $\ensuremath{\mathit{a}}_i$. The proof rules of {Sec.}~\ref{sec:motion} provide contracts for each individual motion primitive. Compatibility checks that these contracts can be put together: first, the assumptions and guarantees are compatible; second, there is no ``leftover'' assumption; and third, the footprints of the motion primitives do not intersect in space. The compatibility check is performed bottom up in the tree structure of a program. For this, we introduce the program-level judgement $\pjudgement{\Pi}{\phi,A, G, \psi,\ensuremath{\mathit{FP}}, {\ddagger}}$ extending the judgement $\judgement{{\roleP}\ensuremath{\triangleleft{}} S}{\cdot}$ in Figure~\ref{fig:proof-system} to programs. At the leaves, the program-level judgement holds if the corresponding motion primitive holds: \[ \small \inferrule*[Left=\rulename{HCompBase}]{ \judgement{{\sf p} \ensuremath{\triangleleft{}} S}{φ,A,G,ψ,\ensuremath{\mathit{FP}},D,{\ddagger}} }{ \pjudgement{{\sf p} \ensuremath{\triangleleft{}} S}{φ,A,G,ψ,\ensuremath{\mathit{FP}},D,{\ddagger}} } \] Recursively, the program-level judgement composes the motion primitives: \[ \small \inferrule[\rulename{HComp}] { ∃ \ensuremath{\mathit{FP}}_1, \ensuremath{\mathit{FP}}_2.\\ G₁\wedge G₂ ⇒ \ensuremath{\mathit{FP}}_1 ∩ \mu(\ensuremath{\mathit{FP}}_2) = ∅ \\ G₁ \wedge G₂ ⇒ \ensuremath{\mathit{FP}}_1 ∪ \mu(\ensuremath{\mathit{FP}}_2) ⊆ \ensuremath{\mathit{FP}} \\ {\ddagger}_1 ={\mathsf{\lightning}} \vee {\ddagger}_2 = {\mathsf{\lightning}} \\\\ {\ddagger}_1 ={\mathsf{\rightsquigarrow}} ⇒ D₁ ⊆ D₂ \\ {\ddagger}_2 ={\mathsf{\rightsquigarrow}} ⇒ D₂ ⊆ D₁ \\\\ \pjudgement{P}{φ₁,A∧\con(G₂),G₁,\ensuremath{\mathit{FP}}_1,ψ₁,D_1,{\ddagger}_1} \\\\ \pjudgement{Q}{\mu^{-1}(φ₂),\mu^{-1}(A∧\con(G₁)),\mu^{-1}(G₂),\ensuremath{\mathit{FP}}_2,\mu^{-1}(ψ₂),D_2,{\ddagger}_2} \\ } {\pjudgement{\comp{P}{\con}{\mu}{Q}}{φ₁∧φ₂,A,G₁∧G₂,\ensuremath{\mathit{FP}},ψ₁∧ψ₂,D₁∩D₂,{\ddagger}_1\oplus{\ddagger}_2}} \] There are three checks. First, the check on footprints ensures that the motion primitives are disjoint in space (there is a way to find subsets $\ensuremath{\mathit{FP}}_1$ and $\ensuremath{\mathit{FP}}_2$ of the footprint $\ensuremath{\mathit{FP}}$ so that the composed motion primitives are in these disjoint portions). Second, the guarantee of one motion primitive is used as the assumption of the other to check that they are compatible. Third, at most one process executes a non-interruptible motion primitive. We say $\Gmotion{\dtsess}{({\sf p}_i {:} \ensuremath{\mathit{a}}_i)}{\ensuremath{{\sf G}}}$ is \emph{compatible} if $\pjudgement{\Pi}{\kf{true}, \kf{true}, \cdot, \cdot, \ensuremath{\mathit{FP}}, {\ddagger}}$ is derivable using these rules. Note that the composition rule restricts the use of joint motion primitives to the common case that at most one component executes a non-interruptible motion primitive while the others execute interruptible ones. This is sufficient for a number of common robotics coordination case studies \cite{PGCD}, e.g., our running example. A more complex rule that allows multiple non-interruptible trajectories that require different execution times would additionally track the minimum and maximum durations of trajectories but we prefer our current rule for simplicity. Theorem~\ref{th:motion-compatibility} below lifts Theorem~\ref{th:motion-soundness} to programs using (\rulename{HComp}) to combine processes. \begin{theorem}[Compatibility] \label{th:motion-compatibility} Let $\pjudgement{P}{\phi,A,G,ψ,\ensuremath{\mathit{FP}}, {\ddagger}}$. For any $\rbtstate{P}{\sstore{X}_0}{\sstore{W}_0}{\sstore{V}_0}$, if $\sstore{X}_0, \sstore{W}_0, \sstore{V}_0$ satisfies $\phi$ then for all $\rbtstate{P_1}{\sstore{X}_1}{\sstore{W}_1}{\sstore{V}_1}$ $n$-reachable from $\rbtstate{P}{\sstore{X}_0}{\sstore{W}_0}{\sstore{V}_0}$ under $A$ for some hyperinteger $n\geq 0$, we have $\sstore{X}_1$ satisfies $G[n\cdot\ensuremath{\mathsf{dt}}\xspace/\ensuremath{\mathsf{clock}}\xspace]$ and one of the following holds. \begin{enumerate} \item There is no $\rbtstate{P_2}{\sstore{X}_2}{\sstore{W}_2}{\sstore{V}_2}$ such that $\rbtstate{P_1}{\sstore{X}_1}{\sstore{W}_1}{\sstore{V}_1} \rightarrow \rbtstate{P_2}{\sstore{X}_2}{\sstore{W}_2}{\sstore{V}_2}$ and $\sstore{X}_1,\sstore{W}_1,\sstore{V}_1$ satisfies $\psi$. \item For every $\rbtstate{P_1}{\sstore{X}_1}{\sstore{W}_1}{\sstore{V}_1} \xrightarrow{\tau} \rbtstate{P_2}{\sstore{X}_2}{\sstore{W}_2}{\sstore{V}_2}$ we have $\sstore{X}_2$ satisfies $G[n\cdot \ensuremath{\mathsf{dt}}\xspace/\ensuremath{\mathsf{clock}}\xspace]$ and $\geom{{\roleP}}(\sstore{X}_2,\sstore{V}_2)\subseteq \ensuremath{\mathit{FP}}[n \cdot \ensuremath{\mathsf{dt}}\xspace/\ensuremath{\mathsf{clock}}\xspace]$; and for every $\rbtstate{P_1}{\sstore{X}_1}{\sstore{W}}{\sstore{V}} \xrightarrow{\ensuremath{\mathsf{dt}}\xspace} \rbtstate{P_2}{\sstore{X}_2}{\sstore{W}_2}{\sstore{V}_2}$ we have $\sstore{X}_2$ satisfies $G[(n+1)\cdot \ensuremath{\mathsf{dt}}\xspace/\ensuremath{\mathsf{clock}}\xspace]$ and $\geom{{\roleP}}(\sstore{X}_2,\sstore{V}_2)\subseteq \ensuremath{\mathit{FP}}[(n+1) \cdot \ensuremath{\mathsf{dt}}\xspace/\ensuremath{\mathsf{clock}}\xspace]$. \end{enumerate} \end{theorem} \end{comment} \section{Motivating Example} \label{sec:example} In this section, we show a coordination example and use it to motivate the different choices of our programming model and choreography specifications. We start with a simple protocol. Consider a scenario where a cart shuttles (based on some unmodeled criterion) between two robotic arms, ``red'' and ``green'' (corresponding, e.g., to two different processing units). In each round, the cart lets the robots know of its choice and then moves to the chosen robot. On reaching its destination, the cart signals to the arm that it has arrived, and waits for the arm to finish processing. Meanwhile, the other arm can continue its own work independently. When the arm finishes its processing, it signals the cart that processing is complete. The cart moves back and then repeats the cycle. Figure~\ref{fig:basic_example_fig} shows a schematic of the system as well as a sample sequence of messages in each cycle. \myparagraph{Multiparty Motion Choreographies} We specify the global behaviour of a program using \emph{choreographies}, which describe the allowed sequence of global message exchanges and joint motion primitives as types for programs. The choreography for our example is shown in Figure~\ref{fig:basic-example}. It extends session types \cite{BLY2015,BYY2014,BMVY2019} with joint motion primitives similarly to motion session types \cite{ECOOP19} and a \emph{separating conjunction} $\ensuremath{\ast}$. {\bf\em (1) Messages and motion primitives.} The choreography in Figure~\ref{fig:basic-example} is a {\bf\emph{recursion}} ($\mu \mathbf{t}.G$), that makes a {\bf\emph{choice}} ($G_1 + G_2$) between two possibilities, corresponding to the cart interacting with the green or with the red robots (blue box). {\bf\em Message exchange} is specified by ${\sf p}\to{\sf q}:\ell$ which is a flow of a message labeled $\ell$ from process ${\sf p}$ to process ${\sf q}$. {\bf\em Joint motion primitives} $\motion{\dtsess}{{\sf p}:\ensuremath{\mathit{a}}, {\sf p}':\ensuremath{\mathit{a}}', \cdots}$ specify that the processes ${\sf p}$, ${\sf p}'$, etc.\ jointly execute motion primitives $\ensuremath{\mathit{a}}$, $\ensuremath{\mathit{a}}'$, etc.\ for the same amount of time. Global time is a global synchroniser; the type system makes sure that there is a consistent execution that advances time in the same way for every process. With just the construct for joint motion primitives, every component is forced to globally synchronise in time, preventing the robots to work independently in physically isolated spaces. We would like to specify, for example, that when the cart and the green robot ${\color{roleColor}{\mathsf{GRobot}}}$ is interacting, the red robot ${\color{roleColor}{\mathsf{RRobot}}}$ can independently perform its work without additional synchronisations. {\bf\em (2) Separating conjunctions.} To overcome this shortcoming, we introduce the {\bf\emph{separating conjunction}} $\ensuremath{\ast}$ (a novel addition from previous session types \cite{ECOOP19,BLY2015,BYY2014,BMVY2019}, explained below), which decomposes the participants into \emph{disjoint} subgroups, in terms of communication, dynamics, and use of geometric space over time, each of which can proceed independently until a merge point. The core interaction between the cart and an arm happens within the green box. Let us focus on the interaction when the green robot is picked. In this case, the cart moves to the green robot (while the green arm performs internal work), then synchronises with a $\mathit{ready}$ message, and then idles while the green arm picks an object from the cart. When the arm is done, it sends an $\mathit{ok}$ message, the cart moves back while the arm does internal work, and the protocol round ends. Meanwhile, the red robot can independently perform its work without synchronising with either the cart or the green robot. The other branch of $+$ is identical, swapping the roles of the red and the green robots. The separating conjunction makes it easy to specify physically and logically \emph{independent} portions of a protocol. Without it, we would be forced to send a message to the other (red) arm every time the cart and the green arm synchronised, even if the red arm proceeded independently. This would be required because time is global, and we would have to ensure that all motion primitives execute for exactly the same duration. Obviously, this leads to unwanted global synchronisations. {\bf\em (3) Interruptible and non-interruptible motions.} Our type system ensures that messages and motions alternate in the correct way. This requires differentiating between motion primitives that are {\bf\emph{interruptible}} (marked by ${\mathsf{\lightning}}$) from those that are not interruptible. An interruptible motion primitive is one that can be interrupted by a message receipt. For example, $\mathsf{m\_idle}$ or $\mathsf{work}$ in our example are interruptible. A {\bf\emph{non-interruptible}} motion primitive (marked by ${\mathsf{\rightsquigarrow}}$), on the other hand, should not be ``stopped'' by an external message. In order to ensure proper synchronisation between motion primitives and messages, we annotate motion primitives with ${\mathsf{\lightning}}$ or ${\mathsf{\rightsquigarrow}}$, which specify whether a motion can be interrupted by a message receipt or not. The type system checks that there is, at any time, at most one non-interruptible motion primitive, and moreover, the process executing that motion is the next one to send a synchronising message. This ensures that motion is compatible with synchronisation. The assumption that there is at most one non-interruptible motion primitive is a restriction; it rules out complex multi-robot maneuvres. However, there are already many ``loosely coupled'' systems that satisfy the assumption and it allows us to develop the (already complicated) theory without introducing distributed feedback control strategies to the mix. We leave lifting the assumption to future work. \myparagraph{Processes: Motion Primitives + Messages} We model robotic systems as concurrent processes in a variant of the session $\pi$-calculus for multiparty interactions \cite{YG2020}. Our calculus (defined in {Sec.}~\ref{sec:calculus}) abstracts away from the sequential operations and only considers the \emph{synchronisation behaviour} and the \emph{physical state changes}. Synchronisation is implemented through synchronous message exchanges between individual physical components (participants). Between message exchanges, each process executes \emph{motion primitives}: controller code that implements an actual robot motion. Motion primitives affect state changes in the physical world. \myparagraph{Correctness Criteria} Our type system prevents a well-typed implementation from ``going wrong'' in the following ways. \textbf{\emph{Communication Safety.}} We provide a choreography type system to ensure that programs are \emph{communication safe} and \emph{deadlock free}: a component does not get stuck sending a message with no recipient or waiting for a non-existent message. Ensuring communication safety is trickier for robotics programs because components may not be ready to receive messages because they are in the middle of executing a motion primitive that cannot be interrupted. \textbf{\emph{Motion Compatibility.}} We check that programs are able to \emph{jointly} execute motion primitives. The controllers implementing motion primitives implement control actions for coupled dynamical systems and we have to check that controllers for different components can be run together. \textbf{\emph{Collision Freedom.}} Components occupy 3D space; a correct implementation must ensure no geometric collision among objects. For example, we must ensure that the robot arms do not hit the cart when the cart is moving in their workspace. Our motion compatibility check ensures the geometric footprint of each component remains disjoint from others at all points in time. \myparagraph{Type Checking} The type checking algorithm has three parts. (1) First, we use an {\bf\emph{assume guarantee proof system}} to ensure jointly executed motion primitives are {\bf\emph{compatible}}: they allow a global trajectory for all the robots in the system and ensure there is no collision between components. (2) Second, we introduce a notion of {\bf\emph{well-formedness}} for choreographies. Well-formed choreographies ensure motion and message exchanges can be globally synchronised and that joint trajectories of the system are well-defined and collision free. (3) Finally, as in standard session types, we {\bf\emph{project a global choreography to its end-points}}, yielding a local type that can be checked for each process. The challenge is to manage the delicate interplay between time, motion, message exchanges, choices and the separating conjunction. This makes the well-formedness check more sophisticated than other choreography type systems. \section{Implementation and Case Study} \label{sec:eval} \myparagraph{Implementation} Our implementation has two parts. The first part takes a program, a specification for each motion primitive, and a global type and checks that the type is well-formed and that each process satisfies its local type. The second part implements the program on top of the Robotic Operating System (ROS)~\cite{ROS}, a software ecosystem for robots. We reuse the infrastructure of motion session types \cite{ECOOP19}; for example, we write programs in \textsf{PGCD}\xspace syntax \cite{PGCD}. The verification infrastructure is about 4000 lines of Python code, excluding the solver. The code is available at \url{https://github.com/MPI-SWS/pgcd} and instructions to run these experiments are located in the \texttt{oopsla20\_artifact} branch. Internally, we represent programs and global types as state machines \cite{DBLP:conf/esop/DenielouY12}, and implement the dataflow analysis on this representation. Additionally, we specify motion primitives in the local co-ordinate system for each robot and automatically perform frame transformations between two robots. The core of ROS is a publish-subscribe messaging system; we extend the messaging layer to implement a synchronous message-passing layer. Our specifications contain predicates with nonlinear arithmetic, for example, to represent footprints of components as spheres. Obstacle are represented as passive components, i.e., components which have a physical footprint but do not execute program. Such components can interact with normal components through input and state variables and their are considered when checking the absence of collision. On the other hand, the obstacles are excluded from the checks related to communication, e.g., synchronisability. We use the dReal4 SMT solver \cite{dReal} to discharge validity queries. The running times are obtained on a Intel i7-7700K CPU at $4.2$GHz and dReal4 running in parallel on 6 cores. \myparagraph{Tests} We evaluate our system on two benchmarks and a more complex case study: (1) We test scalability of the verification using micro-benchmarks. (2) We compare our approach with previous approaches on a set of robotic coordination scenarios from the literature \cite{PGCD,ECOOP19}, and (3) As a large case study, we verify and implement a complex choreography example based on a variation of the example from {Sec.}~\ref{subsec:large}. \begin{wrapfigure}{r}{5cm} \centering \includegraphics[width=45mm]{figs/lanes.pdf} \vspace{-2ex} \caption{Parallel lanes micro-benchmarks} \label{fig:lanes} \vspace{-2ex} \end{wrapfigure} \myparagraph{(1) Micro-benchmarks} The micro-benchmarks comprise a parametric family of examples that highlight the advantage of our motion session calculus, specifically the separating conjunction, over previous typing approaches \cite{ECOOP19}. The scenario consists of carts moving back and forth along parallel trajectories, and is parameterised by the number of carts. Fig.~\ref{fig:lanes} shows the verification times for this example in the two systems. We start with 2 robots and increase the number of robots until we reach a $200$ s. timeout for the verification. The previous calculus is discrete-time and does not separate independent components. Thus, the type system synchronises every process and, therefore, generates complex collision checks which quickly overwhelms the verifier. Our global types use the separating conjunction to split the specifications into independent pieces and the verifcation time increases linearly in the number of processes. \myparagraph{Setup for (2) and (3)} For examples used previously in related works \cite{PGCD,ECOOP19}, we write specifications using our motion session types, taking advantage of the modularity of the type system. For the new case study (part (3)), we implement a variation of the example presented in {Sec.}~\ref{sec:example}, where we decouple the producer placing an object and a sensor that determines if the object is green or red. Thus, after the producer places an object on the cart, the cart first moves to the sensor, communicates with the sensor to get the color, and then delivers the object as described in the protocol. We filmed our experiments and a short video can be seen in the \textbf{\emph{supplementary materials}}. We use three robots: a custom-built robot arm modified from an open-source arm, a commercial manipulator, and a mobile cart, as shown in Figure~\ref{fig:robots-xp}. We use placeholders for the producer arm and color sensor, as we do not have additional hardware (and arms are expensive). The robots are built with a mix of off-the-self parts and 3D printed parts as described below. \textbf{\emph{Arm}.}\ The arm is a modified BCN3D MOVEO ({\url{https://github.com/BCN3D/BCN3D-Moveo}}). The upper arm section is shortened to make it lighter and easier to mount on a mobile cart. It has three degrees of freedom. The motion primitives consist of moving between poses and opening/closing the gripper. The motion is a straight line in the configuration space (angles of the joints) which corresponds to curves in physical space. \textbf{\emph{Panda Arm.}} \ The Panda arm by Franka Emika ({\url{https://www.franka.de/technology}}) is a seven degrees of freedom commercial manipulator platform. It is controlled similarly to the MOVEO arm but with a more complex configuration space. The Panda arm has a closed-loop controller and can get to a pose with an error less than 0.1mm. The controller also comes with collision detection using feedback from the motors. We command this arm using a library of motion primitives provided by the manufacturer. \textbf{\emph{Mobile Carts}.} \ There are two carts. Both are omnidirectional driving platforms. One uses mecanum wheels and the other omniwheels to get three degrees of freedom (two in translation, one in rotation) and can move between any two positions on a flat ground. The advantage of using such wheels is that all the three degrees of freedom are controllable and movement does not require complex planning. Its basic motion primitives are moving in the direction of the wheels, moving perpendicularly to the direction of the wheels, and rotating around its center. The arm and cart are equipped with RaspberryPi 3 model B to run their processes and use stepper motors. This enables a control of the joints and wheels with less than 1.8 degree of error. However, these robots do not have global feedback on their position and keep track of their state using \emph{dead reckoning}. This can be a challenge for the cart, which keeps accummulating error over time. As our example is a loop, we manually reset the cart's position when it gets back to the producer after delivering the object. (A more realistic implementation would use feedback control, but we omit this because control algorithms are a somewhat orthogonal concern.) For the producer and the color sorter, we run the processes but have placeholders in the physical world and realise the corresponding action manually. All computers run Ubuntu 18.04 with ROS 2 Dashing Diademata. Table~\ref{tbl:xp1} shows the specification for the robots and their motions. As the two carts share most of their specification, we group them together. The specification includes the geometrical description of the robots and the motion primitives. \myparagraph{(2) Revisiting the Examples from \textsf{PGCD}\xspace} As we build on top of \textsf{PGCD}\xspace, we can use the examples used to evaluate that system. We take 4 examples, for which we compare the specification effort in the previous calculus \cite{ECOOP19} to our new calculus. As the two calculi have different models for the time and synchronisation, we made some minor adaptations such that the same programs can be described by the two calculi. The old calculus requires motion primitives to have fixed duration and does not support interruptible motions. Furthermore, there is no ``$\ensuremath{\ast}$'' in the old calculus so all the motions are always synchronised. In our new specification, we take advantage of our richer calculus to better decompose the protocol. We use the following scenarios. \begin{description} \item[Fetch.] in this experiment, the Moveo arm is attached on top of a cart. The goal is to get an object. The cart moves toward the object until the object if within the arm's reach. The arm grabs the object and the cart goes back to its initial position. \item[Handover.] This experiment is a variation of the previous one. There are two carts instead of one and the object to fetch is on top of the new cart. The two carts meet before the arm takes an object placed on top of the second cart and then, both go back to their initial positions. \item[Twist and Turn.] In this experiment, the two carts start in front of the each other. The arm takes an object from the small cart. Then all three robots move simultaneously. The cart carrying the arm rotates in place, the other cart describes a curve around the first cart, and arm moves from one side of the cart to the other side. At the end, the arm puts the object on the carrier. \item[Underpass.] In this experiment, the arm and the cart cooperate to go under an obstacle. First, the cart goes toward the arm, which takes the object from the cart. The cart goes around the arm passing under an obstacle. Finally, the arm puts the object back on the cart on the other side of the obstacle. \end{description} Table~\ref{tbl:xp-revisit} reports the size of the examples and their specifications, as well as the verification time. The verification time is broken down into syntactic well-formedness checks on the choreography, the motion compatibility checks for the trajectories, and typing the processes w.r.t.\ local types. The motion compatibility checks dominate the verification time. When we compare our new calculus to the previous approach, we can observe that the global types are slightly larger but the verification time can be significantly smaller. The increase in specification size comes with the addition of new Assume-Guarantee contracts when $\ensuremath{\ast}$ is used. The verification time from the existing specification are higher than the time reported in the previously published results. When implementing our new calculus, we found and fixed some bugs in the verifier code from \textsf{PGCD}\xspace. Those bugs resulted in incomplete collision checks and fixing them increased the burden on the SMT solver.\footnote{\label{note:dreal} Two out of 217 queries in the Fetch example are particularly hard for the solver and could not be solved with 1 hour. We suspect a bug in the solver as all the other queries are solved in $134$s. } \newcommand{\centercell}[1]{\multicolumn{2}{c}{#1}} \begin{table}[t] \centering \caption{Programs, specification, and verification time for the \textsf{PGCD}\xspace examples. ``Prev'' refers to \cite{ECOOP19}.} \vspace{-1ex} \scriptsize \begin{tabular}{lrrr|cc|cc|cc|cc} \toprule Scenario & \multicolumn{3}{c}{Program (Loc)} & \centercell{Global Type} & \centercell{Syntactic} & \centercell{Motion} & \centercell{Typing (s.)} \\ & & & & \centercell{(LoC)} & \centercell{Checks (s.)} & \centercell{Compatibility (s.)} & \\ & Arm & Cart 1 & Cart 2 & Prev & This work& Prev & This work & Prev & This work & Prev & This work \\ \midrule Fetch & $14$ & $19$ & $-$ & $22$ & $42$ & $0.1$ & $0.1$ & $> 3600$ \footnoteref{note:dreal} & $\bf 7$ & $0.1$ & $0.1$ \\ Handover & $9$ & $8$ & $6$ & $14$ & $26$ & $0.1$ & $0.1$ & $2224$ & $\bf 70$ & $0.1$ & $0.1$ \\ Twist and turn & $12$ & $16$ & $6$ & $15$ & $17$ & $0.1$ & $0.1$ & $599$ & $\bf 203$ & $0.1$ & $0.1$ \\ Underpass & $18$ & $3$ & $14$ & $21$ & $65$ & $0.1$ & $0.1$ & $187$ & $\bf 114$ & $0.1$ & $0.1$ \\ \bottomrule \end{tabular} \label{tbl:xp-revisit} \end{table} \begin{figure}[t] \centering \begin{subfigure}[b]{0.4\textwidth} \includegraphics[width=0.965\textwidth]{sorting_setup.jpg} \caption{Setup} \label{fig:robots-xp-setup} \end{subfigure} \begin{subfigure}[b]{0.4\textwidth} \includegraphics[width=\textwidth]{sorting.jpg} \caption{Sequence of motions} \label{fig:robots-xp} \end{subfigure} \vspace{-1ex} \caption{Experimental setup for the sorting example} \vspace{-1ex} \end{figure} \myparagraph{(3) A Complex Case Study} The purpose of the case study is to show that we can semi-automatically verify systems beyond the scope of previous work. Table~\ref{tbl:xp1} shows the sizes of the processes (in lines of code, in the syntax of \textsf{PGCD}\xspace) and statistics related to the global specification and verification time. The global specification consists of the global type, the environment description, and (manually provided) annotations for the verification. The annotations are mostly related to the footprints and the parallel composition. Each time we use the parallel composition operator we specify a partition of the current footprint (the ``$\exists \ensuremath{\mathit{FP}}_1,\ensuremath{\mathit{FP}}_2$'' in rule \rulename{AGcomp}). In Table~\ref{tbl:xp1}, we split the running times into the well-formedness checks which can be done syntactically, the verification conditions for the execution of the motion primitives, and the typing. We did not try to encode this example using the older \textsf{PGCD}\xspace specifications for two reasons. First, the stronger requirement on discrete time steps and global synchronisation in time in the previous calculus would subtantially change this example. Remember that motions in \cite{ECOOP19} are specified simultaneously for all the robots and must have the same duration. When multiple motion primitives have different durations, a motion step can only be as long as the shortest motion. Thus, we would need to chunk the longer motions into a sequence of smaller steps. This would, in turn, make the (sub)typing much more difficult as one motion step in the code would correspond to a sequence of motion steps in the specification. Second, as the previous calculus does not include the separating conjunction, there is little hope that the SMT solver can cope with the compelxity of this example: it contains more robots and more complex ones. Because our global types include separating conjunctions, we can more efficiently generate and discharge the verification conditions. At the modest cost of specifying the footprints for each thread, the collision checks only need to consider the robots within a thread and not all the robots in the system. This brings a substantial reduction in the complexity of the verification conditions. In conclusion, the case study demonstrates the power of our method in specifying and verifying non-trivial coordination tasks between multiple robots. It requires the expressiveness of our motion primitive specifications and the modularity of our separating conjunction. \begin{table}[t] \centering \caption{Programs, motion specification, type, and verification time} \vspace{-1ex} \small \begin{tabular}{lcc|lrl} \toprule Robot & Motion Spec (LoC) & Program (LoC) & Specification \\ \midrule Moveo arm & 306 & 28 & Global type & 96 & LoC \\ Panda arm & 348 & 31 & Syntactic checks & 0.2 & s. \\ Carts & 404 & 45 & Compatibility checks & 2410 & s. \\ Sensor/Producer & 105 & 17 / 10 & Typing & 3.1 & s. \\ \bottomrule \end{tabular} \label{tbl:xp1} \vspace{-1ex} \end{table} \section{Introduction} \label{sec:intro} Modern robotics applications are often deployed in safety- or business-critical applications and formal specifications and reasoning about their correct behaviours is a difficult and challenging problem. These applications tightly integrate computation, communication, control of physical dynamics, and geometric reasoning. Developing programming models and frameworks for such applications has been long noted as an important and challenging problem in robotics \cite{Lozano-Perez}, and yet very little support exists today for compositional specification of behaviours or their static enforcement. In this paper, we present a programming model for concurrent robotic systems and a type-based approach to statically analyse programs. Our programming model uses \emph{choreographies}---global protocols which allow implementing distributed and concurrent components without a central control---to compositionally specify and statically verify both message-based communications and jointly executed motion between robotics components in the physical world. Our choreographies extend \emph{multiparty session types} \cite{HYC08} with \emph{dynamic motion primitives}, which represent pre-verified motions that the robots can execute in the physical world. We compile well-typed programs into robotics platforms. We show through a number of nontrivial usecases how our programming model can be used to design and implement correct-by-construction, complex, robotic applications on top of commercial and custom-build robotic hardware. Our starting point is the theory of motion session types \cite{ECOOP19}, which forms a type discipline based on global types with simple, discrete-time motion primitives. For many applications, we found this existing model too restrictive: it requires that all components agree on a pre-determined, global, discrete clock and it forces \emph{global synchronisation} among all robots at the fixed interval determined by the ``tick'' of the global clock. For example, two robots engaged in independent activities in different parts of a workspace must nevertheless stop their motion and synchronise every tick. This leads to communication-heavy programs in which the programmer must either pick a global clock that ensures every motion primitive can finish within one tick (making the system very slow) or that every motion primitive is interruptible (all robots stop every tick and coordinate). Our new model enhances the scope and applicability of motion sesstion types to robots: we go from the global and discrete clock to \emph{continuous behaviours} over time, allowing complex synchronisations as well as \emph{frame separation} between independent subgroups of robots. That is, the programmer does not need to think about global ticks when writing the program. Instead, they think in terms of motion primitives and the type system enforces that concurrent composition of motions is well-formed and that trajectories exist in a global timeline. Reasoning simultaneously about dynamics and message-based synchronisation is difficult because time is global and can be used as an implicit broadcast synchronisation mechanism. The complexity of our model arises from the need to ensure that every component is simultaneously ready to let time progress (through dynamics) or ready to send or receive messages (property \emph{communication safety}). At the same time, we must ensure that systems are able to correctly execute motion primitives (property \emph{motion compatibility}); and jointly executed trajectories are separated in space and time (property \emph{collision freedom}). Our verification technique is \emph{static}: if a program type checks, then every execution of the system satisfies communication safety, motion compatibility, and collision freedom. We manage the complexity of reasoning about the interplay between dynamics and concurrency through a separation of concerns. First, we specify \emph{continuous-time trajectories} as \emph{motion primitives}. Since the dynamics of different components can be coupled, the proof system uses an \emph{assume-guarantee proof system} \cite{AbadiLamport93,ChandyMisra88,Jones83,DBLP:journals/pieee/NuzzoSBGV15} on continuous time processes to relate an abstract motion primitive to the original dynamics. The assume guarantee contracts decouple the dynamics. Additionally, the proof system also checks that trajectories ensure disjointness of the use of geometric space over time. Second, we interpret choreographic specifications in continuous time, and extend the existing formalism in \cite{ECOOP19} with \emph{predicate refinements}---to reason about permissions (i.e., what parts of the state space an individual robot can access without colliding into a different robot). This is required for motion compatibility and collision freedom. We also introduce a \emph{separating conjunction} operator to reason about disjoint frames. The combination of message passing and dynamics makes static verification challenging. We introduce a notion of \emph{well-formedness} of choreographies that ensures motion and communication can be synchronised and disallows, e.g., behaviours when a message is blocked because a motion cannot be interrupted. We give an algorithm for checking well-formedness using a dataflow analysis on choreographies. We show that well-formed types can be projected on to end-components and provide a local type checking that allows refinement between motion primitives. Checking compatibility and collision freedom reduces to validity queries in the underlying logic. Interestingly, the separating conjunction allows subgroups of robots to interact---through motion and messages---disjointly from other subgroups; this reduces the need for global communication in our implementations. We compile well-typed programs into programs in the PGCD \cite{PGCD} and ROS \cite{ROS} frameworks. We have used our implementation to program and verify a number of complex robotic coordination and manipulation tasks. Our implementation uses both commercial platforms (e.g., the Panda 7DOF manipulator, the BCN3D MOVEO arm) and custom-built components (mobile carts). In our experience, our programming model and typing discipline are sufficient to specify quite complex manoeuvres between multiple robots and to obtain verified implementations. Moreover, the use of choreographies and the separating conjunction are crucial in reducing verification effort: without the separating conjunction, verification times out on more complex examples. Our implementation uses SMT solvers to discharge validity queries arising out of the proof system; our initial experience suggests that while the underlying theories (non-linear arithmetic) are complex, it is possible to semi-automatically prove quite involved specifications. \paragraph{\bf Contributions and Outline} This paper provides a static compositional modelling, verification, and implementation framework through behavioural specifications for concurrent robotics applications that involve reasoning about message passing, continuous control, and geometric separation. We manage this complexity by decoupling dynamics and message passing and enables us to specify and implement robotic applications on top of commercial and custom-build robotic hardware. Our framework coherently integrates programming languages techniques, session type theories, and static analysis techniques; this enables us to model \emph{continuous behaviours} over time in the presence of complex synchronisations between independent subgroups of robots. We extend the global types in \cite{ECOOP19} to \emph{choreographies} including key constructs such as framing and predicate refinements, together with separation conjunctions, and integrate the typing system with an assume-guarantee proof system. We implement our verification system using a new set of robots (extending \cite{ECOOP19,PGCD}) in order to program and verify complex coordinations and manipulation tasks. The rest of the paper is organised as follows. \begin{description} \item[\underline{\sc{Sec.}~\ref{sec:example}}:] We first motivate our design for robotics specifications, and explain the correctness criteria -- \emph{communication safety}, \emph{motion compatibility}, and \emph{collision freedom} with an example. \item[\underline{\sc{Sec.}~\ref{sec:calculus}:}] We introduce a \emph{multiparty motion session calculus} with \emph{dynamic abstract motion primitives}; we provide an assume guarantee proof system to construct abstract motion primitives for maintaining geometric separation in space and time for concurrently executed motion primitives. We then prove Theorem~\ref{th:motion-compat} (\emph{Motion Compatibility}). \item[\underline{\sc{Sec.}~\ref{sec:proof-system}:}] We provide \emph{choreographic specifications} enriched with dynamic motion primitives and separation operator, and define their dataflow analysis. We propose a typing system and prove its main properties, Theorem~\ref{th:SR} (\emph{Subject Reduction}), Theorem~\ref{th:progress} (\emph{Communication and Motion Progress} and \emph{Collision-free Progress}). \item[\underline{\sc{Sec.}~\ref{sec:eval}:}] We describe our implementation, evaluation, and case studies. Our evaluation demonstrates that our framework allows specifying complex interactions and verifying examples beyond the scope of previous work. \item[\underline{\sc{Sec.}~\ref{sec:related} and {Sec.}~\ref{sec:discussion}:}] We discuss related work and conclude with a number of open challenges in reasoning about robotics applications. \end{description} Putting it all together, we obtain a compositional specification and implementation framework for concurrent robotics applications. Our paper is a starting point rather than the final word on robot programming. Indeed, we make many simplifying assumptions about world modeling, sensing and filtering, and (distributed) feedback control and planning. Even with these simplifications, the theoretical development is non-trivial. With a firm understanding of the basic theory, we hope that future work will lift many of the current limitations. \begin{comment} We expand the example in Figure~\ref{fig:cart-crane} and motivate the constructions in our language in {Sec.}~\ref{sec:example}. {Sec.}~\ref{sec:lang} defines a core language for robotic interactions and its operational semantics. Sections~\ref{sec:motion} and~\ref{sec:proof-system} build our proof system: first, by constructing abstract motion primitives from programs and then by incorporating them into a multiparty motion session type system. We discuss related work in {Sec.}~\ref{sec:related} and conclude with future work in {Sec.}~\ref{sec:conclusion}. \RMi{OLD:} In this paper, we provide a compositional proof system for robotics applications. To understand the capabilities such a proof system must provide, let us consider a simple example of a cart and crane assembly transporting a mass from a trolley (Figure~\ref{fig:cart-crane}). The cart assembly rolls on horizontal tracks and has a motor that produces a horizontal force. The crane consists of a winch with a cable that can be used to hoist a load. The combination of the cart and the crane can transport a load from some initial position to another; the cart communicates with a trolley to find the initial position for the load and to inform it when the load is picked up. Figure~\ref{fig:cart-crane}(a) shows the schematic of the system. The task of transporting the load from the trolley requires several steps and involve synchronisation between the software running on each component and joint execution of trajectories in space such that there is no collision. In more detail, a possible protocol for the task is as follows (see Figure~\ref{fig:cart-crane}(b) to see the visual flow of messages and control actions). Initially, we assume that the cart is at rest. First, the trolley sends a message giving the initial position of the load to the cart and remains at rest at that location. The cart sends a message to the crane to roll up its cable. This is to ensure the cable does not swing around (and hit objects in the workspace) while the cart moves to the load as well as to remove a drag due to the cable. While the cart remains stationary, the crane rolls its cable. When it is done, the crane sends an acknowledgement to the cart. At this point, the cart executes a motion primitive to move it on top of the load to be transported. In the meantime, the crane remains idle. Once the cart is on top of the load and stationary, it sends the crane a message to unroll the cable up to the position of the load and to grip the load. This involves the crane executing a motion primitive to unroll the cable, grab the object, and roll it up again. When this action is done, the crane synchronises with the cart. At this point, the cart confirms the pickup with the trolley and the protocol is over. In summary, a correct implementation of the task requires coordination and planning at the discrete level and executing trajectories at the continuous level, while ensuring components do not collide. Formally reasoning about such interaction between planning and control involves a number of challenges. Since the system is \emph{concurrent} and synchronises through \emph{message passing}, formal reasoning inherits the complexities of concurrent systems. Since the components control physical state in continuous space and time, and the dynamics of these states are coupled, reasoning inherits the complexities of continuous control systems and hybrid systems. Finally, since components reside in geometric space and must be collision-free, formal reasoning must consider the use of geometric space by components over time as well as reference frame transformations between components. There are many languages to model and implement robotics applications---from general purpose languages like C++ or Python on top of libraries such as ROS to domain-specific languages \cite{Nordmann2016survey} and to generic modelling languages such as Simulink or Modelica. They usually provide features for concurrency, dynamics, and geometric reasoning but little support for compositional reasoning. Typically, verification support is limited to testing/simulation or global model checking. On the other hand, models and verification tools from formal methods typically support a subset of these features. For example, \emph{hybrid automata} \cite{ACHH,Henzinger96} support continuous dynamics but little support for compositional reasoning about concurrency and geometry. \emph{Session types} \cite{THK,HKV98} support modular specifications and type-checking about message-passing but not continuous dynamics. \emph{Program logics} \cite{AptBO09,DBLP:conf/lics/Reynolds02,DBLP:conf/lics/CalcagnoOY07} support compositional reasoning about concurrency but do not support continuous dynamics or geometric reasoning. Our contribution is a compositional proof system based on session types to reason about robotics applications with support for dynamics, concurrency, and geometry. Our starting point is \textsf{PGCD}\xspace \cite{PGCD}, a recent ``core'' language for robotics applications. We extend \textsf{PGCD}\xspace with explicit support for dynamics in the language (the original papers \cite{PGCD,ECOOP19} either abstracted away the dynamics or used a discrete-time semantics) and provide an operational semantics for \textsf{PGCD}\xspace programs. One nontrivial feature of our operational semantics is the use of nonstandard models of reals to give a uniform semantics to both continuous and discrete evolution of the system as a sequence of infinitesimally small discrete steps. Reasoning about dynamics and message-based synchronisation is difficult because time is global in the system. Thus, our proof system has to ensure that every component is simultaneously ready to let time progress (through dynamics). Similarly, we must ensure that such jointly executed trajectories are separated in space and time. We manage the complexity of this reasoning through a separation of concerns. First, we abstract the original continuous-time trajectories into \emph{abstract motion primitives}. Since the dynamics of different components can be coupled, the proof system uses assume guarantee reasoning. Precisely, we use an \emph{assume-guarantee proof system} \cite{AbadiLamport93,ChandyMisra88,Jones83} on continuous time processes to relate an abstract motion primitive to the original dynamics. Our proof system uses the assume guarantee contracts to decouple the dynamics. Additionally, it also checks that trajectories ensure disjointness of the use of geometric space over time. Second, we use \emph{multiparty session types} \cite{HYC2016} over abstract motion primitives \cite{ECOOP19} as the basis for reasoning about global sequences of messages and motions. The global specification is written as a global type, which extends existing session typing systems with \emph{predicate refinements} and motion primitives connected by separating conjunction. A global type is projected onto each component to generate a local type for each component. Our soundness result states that if each component refines its local type, then the composition of the system satisfies the global type. The combination of message passing and dynamics makes static type checking challenging but our subtyping relations, which relate structured concurrency with motion, enable us to handle this complexity. In summary, we provide the first compositional reasoning framework for robotics applications that involve reasoning about concurrent message passing, continuous control, and geometric separation. Our framework manages the complexity of reasoning by decoupling dynamics and message passing. For the dynamics, we provide an assume guarantee proof system to construct abstract motion primitives. For concurrency, we define a multiparty motion session type system, which uses motion primitives as abstract actions, to specify valid sequences. We show how an implementation of a component can be type checked against the local type obtained by projecting the multiparty session type onto the component. Along the way, our proof systems maintain geometric separation in space and time for concurrently executed motion primitives. Putting it all together, we obtain a fully compositional framework for reasoning with complex, distributed robotics applications that goes significantly beyond the scope of existing techniques. The rest of the paper is organised as follows. We expand the example in Figure~\ref{fig:cart-crane} and motivate the constructions in our language in {Sec.}~\ref{sec:example}. {Sec.}~\ref{sec:lang} defines a core language for robotic interactions and its operational semantics. Sections~\ref{sec:motion} and~\ref{sec:proof-system} build our proof system: first, by constructing abstract motion primitives from programs and then by incorporating them into a multiparty motion session type system. We discuss related work in {Sec.}~\ref{sec:related} and conclude with future work in {Sec.}~\ref{sec:conclusion}. \end{comment} \section{Motion Choreographies} \label{sec:proof-system} In this section, we develop a multiparty session typing discipline to prove communication safety and collision freedom. Our session types extend usual multiparty session types by introducing new operators and by reasoning about joint motion in real-time. Moreover, as message exchanges can be a proxy to exchange permissions for motion primitives, our types have predicates as guards in order to model permissions for motion primitives. \subsection{Global Types with Motions and Predicates} \label{subsec:global} We start with a choreography given as a \emph{global type}. The global type constrains the possible sequences of messages and controller actions that may occur in any execution of the system. We extend \cite{ECOOP19} by framing and predicate refinements, together with separation conjunctions. {\em Sorts}, ranged over by $\ensuremath{{\sf S}},$ are used to define base types: \[\ensuremath{{\sf S}} \quad::=\quad \mathtt{unit} \ensuremath{~~\mathbf{|\!\!|}~~ } \mathtt{real} \ensuremath{~~\mathbf{|\!\!|}~~ } \text{\sf{point}}(ℝ³) \ensuremath{~~\mathbf{|\!\!|}~~ } \text{\sf{vector}} \ensuremath{~~\mathbf{|\!\!|}~~ } \ldots \ensuremath{~~\mathbf{|\!\!|}~~ } \ensuremath{{\sf S}}\times \ensuremath{{\sf S}}\] A \emph{predicate refinement} is of the form $\set{\nu : \ensuremath{{\sf S}}\mid \mathcal{P}}$, where $\nu$ is a \emph{value variable} not appearing in the program, $\ensuremath{{\sf S}}$ a sort, and $\mathcal{P}$ a Boolean predicate. Intuitively, a predicate refinement represents assumptions on the state of the sender and the communicated value to the recipient. We write $\ensuremath{{\sf S}}$ as abbreviation for $\set{\nu: \ensuremath{{\sf S}}\mid\kf{true}}$ and $\mathcal{P}$ for $\set{\nu:\ensuremath{{\sf S}}\mid \mathcal{P}}$ if $\ensuremath{{\sf S}}$ is not important. \begin{definition}[Global types] \label{def:global-types}% {\em Global types} ($\ensuremath{{\sf G}}, \ensuremath{{\sf G}}', ...$) are generated by the following grammar: \[ \begin{array}{rcl} \ensuremath{{\sf G}} & ::= & \ensuremath{g}.\ensuremath{{\sf G}} \;\ensuremath{~~\mathbf{|\!\!|}~~ }\; \mathbf{t} \;\ensuremath{~~\mathbf{|\!\!|}~~ }\; \mu \mathbf{t}.\ensuremath{{\sf G}} \\[1mm] \ensuremath{g} & ::= & \motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}\;\ensuremath{~~\mathbf{|\!\!|}~~ }\; \GvtPre{{\sf p}}{\pq}{[\mathcal{P}]\ell}{\set{\nu:\ensuremath{{\sf S}}\mid\mathcal{P}'}} \; \ensuremath{~~\mathbf{|\!\!|}~~ } \; \ensuremath{g}.\ensuremath{g} \;\ensuremath{~~\mathbf{|\!\!|}~~ }\; \ensuremath{g} + \ensuremath{g} \;\ensuremath{~~\mathbf{|\!\!|}~~ }\; \ensuremath{g} \ensuremath{\ast} \ensuremath{g} \end{array} \] where ${\sf p}, \pq$ range over $\ensuremath{\Bbb P}$, $\ensuremath{\mathit{a}}_i$ range over abstract motion primitives, and $\mathcal{P}_i, \mathcal{P}'$ range over predicates. $\ensuremath{g}$ corresponds to the prefix of global types where we do not allow the recursion. We require that ${\sf p} \neq \pq$, $I \neq \emptyset$, $\ensuremath{\mathit{fv}}(\mathcal{P}_i) ⊆ {\sf p}.X ∪ {\sf p}.W$, $\ensuremath{\mathit{fv}}(\mathcal{P}'_i) ⊆ {\sf p}.X ∪ {\sf p}.W ∪ \set{\nu}$, and $\ell_i \neq \ell_j$ whenever $i \neq j,$ for all $i,j\in I$. We postulate that recursion is guarded and recursive types with the same regular tree are considered equal. We omit the predicate annotation if the predicate is $\kf{true}$ or not important. \end{definition} In Definition~\ref{def:global-types}, the main syntax follows the standard definition of global types in multiparty session types \cite{KY13,KY2015,DGJPY15}, with the inclusion of more flexible syntax of choreographies (\emph{separation} $\ensuremath{g} \ensuremath{\ast} \ensuremath{g}$, \emph{sequencing} $\ensuremath{g}.\ensuremath{g}$ and summation $\ensuremath{g} + \ensuremath{g}$) and \emph{motion} primitive $\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}$ extended from \cite{ECOOP19}, and branching $\GvtPre{{\sf p}}{\pq}{[\mathcal{P}]\ell}{\set{\nu:\ensuremath{{\sf S}}\mid\mathcal{P}'}}$. The motion primitive explicitly declares a \emph{synchronisation} by AG contracts among all the participants ${\sf p}_i$. The {\em branching} type formalises a protocol where participant ${\sf p}$ first tests if the guard $[\mathcal{P}]$, then sends to ${\sf q}$ one message with label $\ell$ and a value satisfying the predicate refinement $\mathcal{P}'$. Recursion is modelled as $\mu\mathbf{t}.\ensuremath{{\sf G}}$, % where variable $\mathbf{t}$ is bound and guarded in $G$, e.g., $\mu\mathbf{t}.\mathbf{t}$ is not a valid type. Following the standard session types, in $\ensuremath{g}_1 + \ensuremath{g}_2 + ... + \ensuremath{g}_n$, we assume: $g_i = \GvtPre{{\sf p}}{\pq}{[\mathcal{P}_i]\ell_i}{\set{\nu:\ensuremath{{\sf S}}\mid\mathcal{P}'_i}}.g_i'$ and $\ell_i \not=\ell_j$; and similarly for $\ensuremath{{\sf G}}$. By this rule, hereafter we write: $\Gvti{{\sf p}}{{\sf q}}{[\mathcal{P}_i]\ell}{\mathcal{P}'}{\ensuremath{{\sf G}}}$, combining summations and branchings and putting $\ensuremath{{\sf G}}$ in the tail into each branching as the standard multiparty session types. $\participant{\ensuremath{{\sf G}}}$ denotes a set of participants appeared in $\ensuremath{{\sf G}}$, inductively defined by $\participant{\motion{\dtsess}{({\sf p}_1{:}\ensuremath{\mathit{a}}_1,\ldots,{\sf p}_k{:}\ensuremath{\mathit{a}}_k)}} = \set{{\sf p}_1,\ldots,{\sf p}_k}$ and $\participant{\GvtPre{{\sf p}}{\pq}{\ell_i[\mathcal{P}]}{\set{\nu:\ensuremath{{\sf S}}\mid\mathcal{P}'}}}=\{{\sf p},\pq\}$ with other homomorphic rules. A ``separating conjunction'' $\ensuremath{\ast}$ allows us to reason about subsets of participants. It places two constraints on the processes and motion primitives on the two sides of $\ensuremath{\ast}$: first, there should not be any communication that crosses the boundary and second, the motion primitives executed on one side should not be coupled (through physical inputs) with motion primitives on the other. We call $\ensuremath{g}_1 \ensuremath{\ast} \ensuremath{g}_2$ \textbf{\emph{fully-separated}} if $\participant{\ensuremath{g}_1} \cap \participant{\ensuremath{g}_2} = \emptyset$, there exist $\ensuremath{\mathit{FP}}_1$, $\ensuremath{\mathit{FP}}_2$ with $\ensuremath{\mathit{FP}}_1\cap \ensuremath{\mathit{FP}}_2 = \emptyset$, and for every motion primitive $\judgement{\ensuremath{\mathit{a}}}{\ensuremath{\mathrm{Pre}\xspace},A, G,\ensuremath{\mathrm{Post}\xspace}, \ensuremath{\mathit{FP}}, D,{\ddagger}}$ in $\ensuremath{g}_i$, we have $A$ depends only on state variables in $\participant{\ensuremath{g}_i}$ and for all $t$, $\ensuremath{\mathit{FP}}\{t/\ensuremath{\mathsf{clock}}\xspace\} \subseteq \ensuremath{\mathit{FP}}_i\{t/\ensuremath{\mathsf{clock}}\xspace\}$, for $i\in\set{1,2}$. $\ensuremath{{\sf G}}$ is \textbf{\emph{fully-separated}} if each $\ensuremath{g}_1 \ensuremath{\ast} \ensuremath{g}_2$ in $\ensuremath{{\sf G}}$ is fully-separated. Our global type does not include an $\mathtt{end}$ type. An $\mathtt{end}$ introduces an implicit global synchronisation that requires all components to finish exactly at the same time. Informally, ``ending'' a program is interpreted as robots stopping their motion and staying idle forever (by forever executing an ``idle'' primitive). Our progress theorem will show that well-typed programs have infinite executions. \myparagraph{Data Flow Analysis on Choreographies} Not every syntactically correct global type is meaningful. We need to check that the AG contracts work together and that the sends and receive work w.r.t the time taken by the different motions. These checks can be performed as a ``dataflow analysis'' on the tree obtained by unfolding the global type. We start with a few definitions and properties. \textbf{\emph{Well-scopedness.}} Consider the unfolding of a global type $\ensuremath{{\sf G}}$ as a tree. The leaves of the tree are labeled with motions $\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}$ or message ${\sf p}\to\pq$, and internal nodes are labeled with the operators $.$, $\ensuremath{\ast}$, or $+$. By our assumption, we decorate each $+$ node with the sender and receiver ${\sf p}\to\pq$ below it. We say the tree is \textbf{\emph{well-scoped}} if there is a way to label the nodes of the tree following the rules below: (1) The root is labeled with the set $\ensuremath{\Bbb P}$ of all participants. (2) If a ``.'' node labeled with $\ensuremath{\Bbb P}'$, both its children are also labeled with $\ensuremath{\Bbb P}'$, if possible. (3) If a ``+'' node associated with a message exchange ${\sf p}\to\pq$ is labeled with $\ensuremath{\Bbb P}'$, and both ${\sf p},\pq\in \ensuremath{\Bbb P}'$, then each of its children are also labeled with $\ensuremath{\Bbb P}'$, if possible. (4) If a ``\ensuremath{\ast}'' node is labeled with $\ensuremath{\Bbb P}'$, then we label its children with $\ensuremath{\Bbb P}_1$ and $\ensuremath{\Bbb P}_2$ such that $\ensuremath{\Bbb P}_1 \cap \ensuremath{\Bbb P}_2 = \emptyset$ and $\ensuremath{\Bbb P}_1 \cup \ensuremath{\Bbb P}_2 = \ensuremath{\Bbb P}'$. (5) A leaf node $\motion{\dtsess}{{\roleP}_i:\ensuremath{\mathit{a}}_i}$ is labeled with $\ensuremath{\Bbb P}'$ if all ${\roleP}_i$ are in $\ensuremath{\Bbb P}'$, otherwise the labeling fails. (6) A leaf node ${\sf p} \to \pq$ is labeled with $\ensuremath{\Bbb P}'$ if both ${\sf p}, \pq$ are in $\ensuremath{\Bbb P}'$, otherwise the labeling fails. Such a scope labeling is unique if the global type is fully-separated and no participant is ``dropped,'' and so we can define the scope of a node in an unambiguous way. \textbf{\emph{Unique minimal communication}.}\ We first define a notion of \emph{happens-before} with \emph{events} as nodes labeled with motions $\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}$ or message exchanges ${\sf p}\to \pq$. We define a \emph{happens before} relation on events as the smallest strict partial order such that: there is an edge $n:e \to n':e'$ if there is an internal node $n^*$ in the tree labeled with $.$ and $n$ is in the left subtree of $n^*$ and $n'$ is in the right subtree of $n^*$, and one of the following holds: (1)~$e \equiv {\sf p}\to\pq$, $e' \equiv {\sf p}'\to\pq'$ and ${\sf p}'$ is either ${\sf p}$ or $\pq$; or (2)~$\participant{e} \cap \participant{e'} \not = \emptyset$. We say there is an \emph{immediate happens before} edge $n\to n'$ if $n\to n'$ is in the happens before relation but there is no $n''$ such that $n \to n''$ and $n''\to n'$. A global type has \textbf{\emph{unique minimal communication}} after motion iff every motion node $n:\motion{\dtsess}{{\sf p}_i:\ensuremath{\mathit{a}}_i}$ has a \emph{unique} immediate happens before edge to some node $n':{\sf p}\to\pq$. \textbf{\emph{Sender readiness}.}\ Consider now a type with unique minimal communication after motion and consider the unique immediate happens before edge $n:\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)} \to n':({\sf p}\to\pq)$. Suppose ${\sf p}$ is among the processes executing the motion primitives. Since the motion primitives are assumed to be compatible, we know that at most one process is executing a non-interruptible motion, and all the others are executing interruptible motions. Since ${\sf p}$ is the next process to send a message, we must ensure that it is the unique process executing the non-interruptible motion. Compatibility ensures that the durations of all other processes are such that they are ready to receive the message from ${\sf p}$. We call this condition \textbf{\emph{sender readiness}}: whenever there is a communication after a motion, the sender of the communication was the unique participant executing a non-interruptible motion; or every process in the motion was executing an interruptible motion. On the other hand, if ${\sf p}$ is not among the processes (this can happen when to parallel branches merge), every participant in the motion must have been executing an interruptible motion. \textbf{\emph{Total synchronisation}.}\ It is not enough that ${\sf p}$ sends a message to only one other participant: if ${\sf p}$ and $\pq$ decide to switch to a different motion primitive, every other participant in scope must also be informed. This is ensured by the \textbf{\emph{total synchronisation}} between motions: we require that whenever there is a happens before edge between $n:\motion{\dtsess}{({\sf p}_i:\ensuremath{\mathit{a}}_i)}$ to $n':\motion{\dtsess}{({\sf p}'_i:\ensuremath{\mathit{a}}'_i)}$, then for every ${\sf p}_i$, there is a node where ${\sf p}_i$ is a sender or a recipient that happens before $n'$. \textbf{\emph{Synchronisability}.} \ We call a global type is \textbf{\emph{synchronisable}} if it satisfies unique minimal communication, sender readiness, and total synchronisation. Synchronisability of a global type can be checked in time polynomial in the size of the type by unfolding each recursive type once. \begin{example}[Synchronisability] \rm We illustrate the synchronisability condition. In general, a node can have multiple outgoing immediate happens before edges. Consider, for distinct participants ${\sf p},\pq,{\sf p}'$, the type ${{\sf p}}\rightarrow {\pq}:{\ell}. {{\sf p}'}\rightarrow {\pq}:{\ell'}.\ensuremath{{\sf G}}$. The minimal senders are ${\sf p}$ and ${\sf p}'$, because these two sends cannot be uniquely ordered in an execution. We avoid such a situation because in a process $\pq$ we would not know whether to expect a message from ${\sf p}$ or from ${\sf p}'$ or from both. Note that synchronisability disallows a sequence of two motions without an intervening message exchange. Thus, $\motion{\dtsess}{({\sf p}{:}\ensuremath{\mathit{a}}_1,\pq{:}\ensuremath{\mathit{a}}_1')}.\motion{\dtsess}{({\sf p}{:}\ensuremath{\mathit{a}}_2, \pq{:}\ensuremath{\mathit{a}}_2')}.\ensuremath{{\sf G}}$ is not well-formed. This is because the implementation of the participants do not have any mechanism to synchronize when to shift from the first motion primitive to the second. We require the total synchronisation between motions to notify every participant by some message between any change of motion primitives. We disallow the type $\motion{\dtsess}{({\sf p}{:}\ensuremath{\mathit{a}}_{11},{\sf q}{:}\ensuremath{\mathit{a}}_{12}, {\sf r}{:}\ensuremath{\mathit{a}}_{13})}.{{\sf p}}\rightarrow{{\sf q}}:\ell.\motion{\dtsess}{({\sf p}{:}\ensuremath{\mathit{a}}_{21}, {\sf q}{:}\ensuremath{\mathit{a}}_{22}, {\sf r}{:}\ensuremath{\mathit{a}}_{23})}.\ensuremath{{\sf G}}$. because ${\sf r}$ does not know when to shift from $\ensuremath{\mathit{a}}_{13}$ to $\ensuremath{\mathit{a}}_{23}$. Note however, that the scoping introduced by $\ensuremath{\ast}$ requires messages to be sent only to ``local'' subgroups. The following type is fine, even though ${\sf p}_3$ was not informed when ${\sf p}_1$ and ${\sf p}_2$ changed motion primitives, as it is in a different branch and there is no happens before edge: \begin{align*} \left(( \begin{array}{l} (\motion{\dtsess}{({\sf p}_1{:}\ensuremath{\mathit{a}}_1, {\sf p}_2{:}\ensuremath{\mathit{a}}_2)}. {{\sf p}_1}\rightarrow{{\sf p}_2}:{\ell_1}. \motion{\dtsess}{({\sf p}_1{:}\ensuremath{\mathit{a}}_1',{\sf p}_2{:}\ensuremath{\mathit{a}}_2')}) \end{array} ) \ensuremath{\ast} \motion{\dtsess}{{\sf p}_3{:}\ensuremath{\mathit{a}}_3} \right) .{{\sf p}_1}\rightarrow{{\sf p}_2}{:\ell_1}.{{\sf p}_1}\rightarrow{{\sf p}_3}{:\ell_3}.G \end{align*} \end{example} \begin{example}\rm By inspection, the motion type in Figure~\ref{fig:basic-example} is well-scoped and fully separated. It is also synchronizable: to see this, note that for every joint motion primitive, there is at most one motion which is non-interruptible and the participant corresponding to that motion primitive is the unique minimal sender. Moreover, the unique minimal sender sends messages to every participant in the scope of the separating conjunction, thus the type is totally synchronized. \end{example} We are ready to define when global types are well-formed. \begin{definition}[Well-formed global types] \label{def:well-formed} A global type $\ensuremath{{\sf G}}$ is \emph{well-formed} if it satisfies the following conditions: \begin{enumerate} \item \emph{Total choice:} for each branching type $\Gvti{{\sf p}}{\pq}{[\mathcal{P}_i]\ell}{\mathcal{P}'}{G}$, we have $\bigvee_i \mathcal{P}_i$ is valid. \item \emph{Well-scoped:} $\ensuremath{{\sf G}}$ is well-scoped and fully-separated. \item \emph{Total and compatible motion:} For every motion type $\motion{\dtsess}{({\sf p}_i {:} \ensuremath{\mathit{a}}_i)}$, there exists a motion primitive for each participant in scope and moreover the tuple of motion primitives $({\sf p}_i{:}\ensuremath{\mathit{a}}_i)$ is compatible. \item \emph{Synchronisability:} The global type is synchronisable. \end{enumerate} \end{definition} \noindent Hereafter we assume global types are well-formed. \begin{restatable}[Well-formedness]{proposition}{theoremWF} \label{pro:WF} Synchronisability is decidable in polynomial time. Checking well-formedness of global types reduces to checking validity in the underlying logic of predicates in global types and motion primitives. \end{restatable} \begin{proof} All causalities in global types can be checked when unfolding each recursive type once (cf.~\cite[{Sec.}.~3.5]{HYC2016}). Hence synchronisability of a global type can be checked in time polynomial in the size of the type by checking unique minimum communication, sender readiness and total synchronisation simultaneously. By Definition \ref{def:well-formed}, checking well-formedness depends on checking validity in the underlying logic. \end{proof} \subsection{Local Types and Projection} \label{sec:local} Next, we project global types to their end points against which each end-point process is typed. The syntax of \emph{local types} extends local types from \cite{ECOOP19}. Each local type represents a specification for each component. \begin{definition}[Local motion session types] \label{def:session-types}% The grammar of local types, ranged over by $T$, is: \begin{align*} T ::= \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \ensuremath{~~\mathbf{|\!\!|}~~ } \oplus\{[\mathcal{P}_i]\tout\pq{\ell_i}{\mathcal{P}_i'}.T_i\}_{i\in I} \ensuremath{~~\mathbf{|\!\!|}~~ } \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i}.T_i\}_{i\in I} \ensuremath{~~\mathbf{|\!\!|}~~ } \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i}.T_i\}_{i\in I}\ \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \ensuremath{~~\mathbf{|\!\!|}~~ } \mu \mathbf{t}.T \ensuremath{~~\mathbf{|\!\!|}~~ } \mathbf{t} \end{align*} where $\ensuremath{\mathit{a}}$ ranges over motion primitives. We require that $\ell_i \neq \ell_j$ whenever $i \neq j$, for all $i,j\in I$. We postulate that recursion is always guarded. Unless otherwise noted, types are closed. \end{definition} Our goal is to \emph{project} a global type onto a participant to get a local type. To define this notion formally, we first need the following definition that merges two global types. \begin{definition}[Merging] \label{def:merge}% We define a \emph{merging operator} $\bigsqcap$, which is a partial operation over global types, as: \[ \small \textstyle% T_1 \mathbin{\bigsqcap} T_2 \;=\; \left\{% \text{% \begin{tabular}{@{\hskip 0mm}l} $T_1$ \hfill if $T_1 = T_2$ \hspace{2mm} \iftoggle{full}{$\rulename{mrg-id}$}{} \\[2mm]% $\&\{\tin{{\sf p}'}{\ell_k}{\mathcal{P}_k}{.T_k}\}_{k \in I \cup J}$ \quad\quad \hfill if \(% \left\{% \begin{array}{l} T_1 = \&\{ \tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \hfill \text{ and}\\% T_2 = \&\{ \tin{{\sf p}'}{\ell_j}{\mathcal{P}_j}{.T_j}\}_{j \in J}% \end{array} \right.% \)\\[3mm] \iftoggle{full}{\hfill $\rulename{mrg-bra1}$\\}{} $\&\{\tin{{\sf p}'}{\ell_k}{\mathcal{P}_k}{.T_k}\}_{k \in I \cup J} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}} \bigsqcap \ensuremath{\mathit{a}}'}{T'}$ \quad\quad \hfill if \(% \left\{% \begin{array}{l} T_1 = \&\{ \tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'} \hfill \text{ and}\\% T_2 = \&\{ \tin{{\sf p}'}{\ell_j}{\mathcal{P}_j}{.T_j}\}_{j \in J} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'}% \end{array} \right.% \)\\[3mm] \iftoggle{full}{\hfill $\rulename{mrg-bra2}$\\}{} $\&\{\tin{{\sf p}'}{\ell_k}{\mathcal{P}_k}{.T_k}\}_{k \in I \cup J} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'}$ \hfill if \(% \left\{% \begin{array}{l} T_1 = \&\{ \tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \hfill \text{ and} \\ T_2 = \&\{ \tin{{\sf p}'}{\ell_j}{\mathcal{P}_j}{.T_j}\}_{j \in J} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'}% \end{array} \right.% \) \\[3mm] \iftoggle{full}{\hfill $\rulename{mrg-bra3}$\\}{} $\&\{\tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}} \bigsqcap \ensuremath{\mathit{a}}'}{T'}$ \hfill if \(% \left\{% \begin{array}{l} T_1 = \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'} \hfill \text{ and} \\% T_2 = \&\{ \tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'}% \end{array} \right.% \) \\[3mm] \iftoggle{full}{\hfill $\rulename{mrg-bra4}$\\}{} $\&\{\tin{{\sf p}'}{\ell_i}{\mathcal{P}_i}{.T_i}\}_{i \in I} \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'}$ \hfill if \(% \left\{% \begin{array}{l} T_1 = \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T'} \hfill \text{ and} \\% T_2 = \&\{ \tin{{\sf p}'}{\ell_j}{\mathcal{P}_j}{.T_j}\}_{i \in I}% \end{array} \right. % \) \\[3mm] \if{\hfill $\rulename{mrg-bra5}$\\}\else{}\fi $T_2 \mathbin{\bigsqcap} T_1$ \hfill if $T_2 \mathbin{\bigsqcap} T_1$ is defined, \\[2mm] undefined \hfill otherwise. \end{tabular} } % \right.% \] % The merge operator for motion $\ensuremath{\mathit{a}} \bigsqcap \ensuremath{\mathit{a}}'$ returns a motion primitive $\ensuremath{\mathit{a}}''$ such that $\ensuremath{\mathit{a}}'' \ensuremath{\preceq} \ensuremath{\mathit{a}}$ and $\ensuremath{\mathit{a}}'' \ensuremath{\preceq} \ensuremath{\mathit{a}}'$. We can build such $\ensuremath{\mathit{a}}''$ by taking the union of the assumptions and precondition and the intersection of the guarantees, postcondition, and footprint. \end{definition} \begin{definition}[Projection] \label{pro}% \label{def:projection}% The \emph{projection of a global type onto a participant ${\sf r}$} is the largest relation $\proj{}{{\sf r}}{}$ between global and session types such that, whenever $\proj{\ensuremath{{\sf G}}}{{\sf r}}{T}$: \begin{enumerate} \item if ${\ensuremath{{\sf G}}}=\Gvti{{\sf p}}{{\sf r}}{[\mathcal{P}_i]\ell}{\mathcal{P}'}{\ensuremath{{\sf G}}}$ then ${T}=\&\{ \tin{\sf p}{\ell_i}{\mathcal{P}'_i}.{T_i}\}_{i\in I}$ with $\proj{\ensuremath{{\sf G}}_i} {\sf r} T_i$; \item if ${\ensuremath{{\sf G}}}=\Gvti{{\sf r}}{\pq}{[\mathcal{P}_i]\ell}{\mathcal{P}'}{\ensuremath{{\sf G}}}$ then ${T}= \oplus\{[\mathcal{P}_i]\tout{\sf q}{\ell_i}{\mathcal{P}'_i}.{T_i}\}_{i\in I} $ and $\proj{\ensuremath{{\sf G}}_i}{\sf r} T_i,$ $\forall i \!\in\! I$; \item if ${\ensuremath{{\sf G}}}=\Gvti{{\sf p}}{{\sf q}}{[\mathcal{P}_i]\ell}{\mathcal{P}'}{\ensuremath{{\sf G}}}$ and ${\sf r} \!\not\in\! \{{\sf p},{\sf q}\}$ then there are $T_{\!i},$ $i \in I$ s.t. ${T} = \bigsqcap_{i \in I}\!\!{T_{\!i}}$, and $\proj{\ensuremath{{\sf G}}_i\!}{{\sf r}}{\!T_{\!i}},$ for every $i\in I$; \item if $\ensuremath{{\sf G}} = \mu\mathbf{t}. \ensuremath{{\sf G}}'$ then $T=\mu\mathbf{t}.T'$ with $\proj{\ensuremath{{\sf G}}'}{\sf r} T'$ if ${\sf r}$ occurs in $\ensuremath{{\sf G}}'$, otherwise undefined; and \item if $\ensuremath{{\sf G}} = \ensuremath{g}. \ensuremath{{\sf G}}$ then $T=T' . T''$ with $\proj{\ensuremath{g}}{{\sf r}}{T'}$ and $\proj{\ensuremath{{\sf G}}}{{\sf r}}{T''}$.\footnote{We abuse $T$ to denote \emph{a local type prefix} which is given replacing $\mathbf{t}$ and $\mu\mathbf{t}.T$ by $\ensuremath{\epsilon}$ (as defined for global type prefix $g$).} \item $\proj{\motion{\dtsess}{({\sf p}_i {:} \ensuremath{\mathit{a}}_i)}}{{\sf r}}{ \motion{\dtsess}{a_j}}$ with ${\sf r} = {\sf p}_j$; \item $\proj{(\ensuremath{g}_1 \ensuremath{\ast} \ensuremath{g}_2)}{{\sf r}}{\ensuremath{T}_i}$ and $\proj{\ensuremath{g}_i}{{\sf r}}{\ensuremath{T}_i}$ if ${\sf r} \in \participant {\ensuremath{g}_i}$ ($i\in \{1,2\}$) \item $\proj{\ensuremath{g}_1.\ensuremath{g}_2}{{\sf r}}{\ensuremath{T}_1.\ensuremath{T}_2}$ with $\proj{\ensuremath{g}_i}{{\sf r}}{\ensuremath{T}_i}$ ($i=1,2$) \end{enumerate} We omit the cases for recursions and selections (defined as \cite[Section~3]{SY2019}). The branching prefix is defined as the branching in (1-3). \end{definition} \begin{example}[Projection of Figure~\ref{fig:basic-example}]\rm For the example from {Sec.}~\ref{sec:example}, the local type of the cart is: \begin{align*} \small \mu \mathbf{t}.\left( \begin{array}{l} \ ({\color{roleColor}{\mathsf{GRobot}}}!\mathit{arrive}(t).{\color{roleColor}{\mathsf{RRobot}}}!\mathit{free}.\\ \ \ \motion{\dtsess}{\mathsf{m\_move}({\color{roleColor}{\mathsf{GRobot}}})}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{ready}. \motion{\dtsess}{\mathsf{m\_idle}}.{\color{roleColor}{\mathsf{GRobot}}}?\mathit{ok}.\motion{\dtsess}{\mathsf{m\_move}}) \\ \& \ ({\color{roleColor}{\mathsf{RRobot}}}!\mathit{arrive}(t).{\color{roleColor}{\mathsf{GRobot}}}!\mathit{free}. \ldots \text{symmetric} \ldots)\ \end{array} \right).\mathbf{t} \end{align*} \end{example} \subsection{Subtyping and Typing Processes} The local types are a specification for the processes and there is some freedom to implement these specifications. The subtyping relation helps bridge the gap between the specification and the implementation. \begin{definition}[Subtyping] \label{def:subt}% \label{tab:sync:subt}% {\em Subtyping} $\leqslant$ is the largest relation between session types coinductively defined by rules in Figure~\ref{fig:subtyping}. \end{definition} \begin{figure}[t] \[ \small \begin{array}{@{}c@{}} \cinferrule[\rulename{sub-motion}]{ \ensuremath{\mathit{a}} \ensuremath{\preceq} \ensuremath{\mathit{a}}' \\ T \leqslant T' }{ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'} }\quad \cinferrule[\rulename{sub-out}]{ \forall i\in I.\ \mathcal{P}_i ⇒ \mathcal{P}''_i ∧ \mathcal{P}'_i ⇒ \mathcal{P}'''_i ∧ T_i \leqslant T'_i }{ \oplus\{[\mathcal{P}_i]\tout{\sf p}{\ell_i}{\mathcal{P}'_i}.T_i\}_{i\in I} \leqslant \oplus\{[\mathcal{P}''_i]\tout{\sf p}{\ell_i}{\mathcal{P}_i'''}.T_i'\}_{i\in I\cup J} } \\[5mm] \cinferrule[\rulename{sub-in1}]{ \forall i\in I.\ \mathcal{P}_i' ⇒ \mathcal{P}_i ∧ T_i \leqslant T_i' \\ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'} }{ \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i}.T_i\}_{i\in I\cup J} \ \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i'}.T_i'\}_{i\in I}\ \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'} } \\[5mm] \cinferrule[\rulename{sub-in2}]{ \forall i\in I.\ \mathcal{P}_i' ⇒ \mathcal{P}_i ∧ T_i \leqslant T_i'}{ \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i}.T_i\}_{i\in I\cup J}\ \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i'}.T_i'\}_{i\in I} } \quad \cinferrule[\rulename{sub-in3}]{ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'} }{ \&\{\tin{\sf p}{\ell_i}{\mathcal{P}_i}.T_i\}_{i\in I}\ \& \ \Lmotion{\dtsess}{\ensuremath{\mathit{a}}}{T} \leqslant \Lmotion{\dtsess}{\ensuremath{\mathit{a}}'}{T'} } \end{array} \] \caption{Subtyping rules\label{fig:subtyping}} \end{figure} A subtype has fewer requirements and provide stronger guarantees. The subtyping of motion primitives (\rulename{sub-motion}) allows replacing an abstract motion primitive by a concrete one if $\ensuremath{\mathit{a}}$ refines $\ensuremath{\mathit{a}}'$ and $T \leqslant T'$. For internal choice and sending (\rulename{sub-out}), the subtyping ensure the all the messages along with the associated predicate are allowed by the supertype. Predicate refinements are converted to logical implication. For the external choice and message reception (\rulename{sub-in1,2,3}), subtyping makes sure the process reacts properly to the messages expected by the super type. A subtype can have cases for more messages but they don't matter. The subtype guarantees that the process will never receive theses messages. On the other hand, the sender of the messages has to be the same. We enforce this directly in the syntax of the programming language and the type system. It may seem that (\rulename{sub-in3}) introduces a new sender in the subtype but this rule is correct because, in our synchronous model, sending is blocking and cannot be delayed. Therefore, if the supertype only contains a motion, we know for a fact that no messages can arrive unexpectedly in the subtype. Our subtyping conditions generalise those of motion session types of \citet{ECOOP19} in multiple ways. First, we allow refinement of motion primitives (\rulename{sub-motion}) as a way to abstract trajectories. In \cite{ECOOP19}, the actions are abstract symbols and are fixed statically. Second, the rules for communication must check predicate refinements---in \cite{ECOOP19}, global types did not have refinements. The final step in our workflow checks that the process of each participant in a program implements its local type using the typing rules from Table~\ref{tab:sync:typing}. Our typing rules additionally maintain a logical context to deal with the predicate refinements \cite{LiquidTypes}. We write $\der{\Gamma,\Sigma}{S}{T}$ to indicate the statement $S$ has type $T$ under the variable context $Γ$ and the logical context $Σ$. $\Gamma$ is the usual typing context; $\Sigma$ is a formula characterising what is known about the state of the system when a process is about to execute. The typing rules are shown in Table~\ref{tab:sync:typing}. \rulename{t-motion} considers $\Sigma$ derives the pre-condition of motion $a$, while $Q$ guarantees its post-condition. \rulename{t-out} assumes $\Sigma$ of $P$ derives a conjunction of the guard and refined predicates declared in types. \rulename{t-choice1} is its dual and \rulename{t-choice2} includes the default motion branch. \rulename{t-cond} is similar with the usual conditional proof rule. \rulename{t-sess} combines well-typed participants each of which follows a projection of some global type $\ensuremath{{\sf G}}$ given assumptions over the initial state $\bigwedge_{i\in I}𝓟_i$ of each participant. We requires the initial state to be collision free as the global types only maintains collision freedom. \begin{table}[t] \caption{\label{tab:sync:typing} Typing rules for motion processes.} \centerline{$ \small \begin{array}{c} \inferrule[\rulename{t-sub}]{ \der{\Gamma,\Sigma}{\ensuremath{{P}}}T \quad T\leqslant T' }{ \der{\Gamma,\Sigma}{\ensuremath{{P}}}T' } \qquad \inferrule[\rulename{t-rec}]{\der{\Gamma\cup\set{{\roleVar}:T},\kf{true}}{\ensuremath{{P}}}{T}}{\der{\Gamma,\Sigma}{\mu {\roleVar}.\ensuremath{{P}}}T} \qquad \inferrule[\rulename{t-motion}]{ \der{\Gamma,a.\ensuremath{\mathrm{Post}\xspace}}{{Q}}{T}\\ \Sigma \Rightarrow a.\ensuremath{\mathrm{Pre}\xspace}\\ }{\der{\Gamma,\Sigma}{\motion{dt}{a}.{Q}}{\Lmotion{dt}{a}{T}}} \\\\ \inferrule[\rulename{t-out}]{ \Sigma \Rightarrow \mathcal{P}\wedge \mathcal{P}'\set{e/\nu}\\ \der{\Gamma,\Sigma}{\kf{e}}{S}\\ \der{\Gamma,\Sigma}{P}T }{ \der{\Gamma,\Sigma}{{\pq}!{\ell(\kf{e})}.{P}}{[\mathcal{P}]\pq!\ell(\set{\nu: S\mid\mathcal{P}'}).T} } \quad \inferrule[\rulename{t-choice1}]{ \forall i\in I \quad \der{\Gamma\cup\set{x_i:\S_i},\Sigma\wedge \mathcal{P}_i\set{x_i/\nu}}{\ensuremath{{P}}_i}T_i }{ \der{\Gamma,\Sigma}{\sum\limits_{i\in I}{\procin \pq {\ell_i(x_i)} \ensuremath{{P}}_i}}{\&\{\pq?\ell_i(\mathcal{P}_i).T_i}\}_{i\in I} } \\\\ \rulename{t-choice2} \inferrul { \forall i\in I \quad \der{\Gamma\cup \set{x_i:\S_i},\Sigma\wedge \mathcal{P}_i\set{x_i/\nu}}{\ensuremath{{P}}_i}T_i \quad \der{\Gamma,\Sigma}{\motion{dt}{a}.{Q}}{T} }{ \der{\Gamma,\Sigma}{\sum\limits_{i\in I}{\procin \pq {\ell_i(x_i)} \ensuremath{{P}}_i}+\motion{dt}{a}.{Q}}{\&\{\pq?\ell_i(\set{\nu:S\mid\mathcal{P}_i}).T_i}\}_{i\in I}\ \&\ T } \\\\ \rulename{t-cond} \inferrul { \der\Gamma\kf{e}\mathtt{bool} \ \exists k \in I \ \Sigma \wedge \kf{e} \Rightarrow \mathcal{P}_k\ \der{\Gamma,\Sigma\wedge \kf{e}}{\ensuremath{{P}}_1}{T_k} \ \der{\Gamma, \Sigma\wedge \lnot \kf{e}}{\ensuremath{{P}}_2}{\oplus\{[\mathcal{P}_i]T_i\}_{i \in I \setminus \{k\}}} }{ \der{\Gamma,\Sigma}{{\cond{\kf{e}}{\ensuremath{{P}}_1}{\ensuremath{{P}}_2}}}{ \oplus\{[\mathcal{P}_i]T_i\}_{i\in I}} } \\\\ \rulename{t-sess} \inferrul { \forall i\in I\quad\der{∅,𝓟_i}{\ensuremath{{P}}_i}{\projt \ensuremath{{\sf G}} {{{\sf p}_i}}} \\ \participant \ensuremath{{\sf G}} = \ensuremath{\Bbb P} \\ \forall j\in I.\ j≠i ⇒ \geom{{\sf p}_i}(𝓟_i)\cap\geom{{\sf p}_j}(𝓟_j) = \emptyset }{ \der{\bigwedge\limits_{i\in I}𝓟_i}{\prod\limits_{i\in I}\pa {{\sf p}_i}\ensuremath{{P}}_i}\ensuremath{{\sf G}} } \end{array} $} \vspace*{-1em} \end{table} \begin{comment} \RMi{We don't have the process description. I don't know if we should add this in the main text or have it in the appendix.} \begin{example}{(Local Types for Load Transfer)}\label{ex:overview:mpst}\rm \ In our example, the local types for the ${\color{roleColor}{\mathsf{Trolley}}}$, ${\color{roleColor}{\mathsf{Cart}}}$, and ${\color{roleColor}{\mathsf{Crane}}}$ are: \NYi{I commented out the old example} We type check the process (code) from Figure~\ref{fig:cart-crane-code} against these types. \rulename{motion} rule connects the predicate refinements to the motion primitives. The typing of the ${\color{roleColor}{\mathsf{Crane}}}$ uses unfolding and subtyping to go from the type \NYi{I commented out the old example of types} \[ \small \mu \mathbf{t}.\&\left\{ \begin{array}{l} \end{array}\right\}\&\dtsess\tuple{\mathsf{c\_idle}} \] to the type above. \qed \end{example} \end{comment} \subsection{Soundness} The soundness of multiparty sessions is shown, using subject reduction (typed sessions reduce to typed sessions) and progress. In order to state soundness, we need to formalise how global types are reduced when local session types evolve. To define the consumption of global types, as done for processes in {Sec.}~\ref{sec:opsem}, we extend the syntax of global types to allow \emph{partial consumption} of motion types. In addition, we extend $\ensuremath{g}$, annotating each motion type with its unique minimal sender, $\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t}^{{\sf p}}$ for $t\geq 0$. \begin{definition}[Global types consumption and reduction] \label{def:global-type-consumption}% \label{def:global-type-reduction}% The {\em consumption} of the communication ${\sf p}\lts{\ell}\pq$ or motion $\motion{\dtsess}{a}[t_1,t_2]$ % for the global type $\ensuremath{{\sf G}}$ (notation $\redG \ensuremath{{\sf G}}{\sf p}\ell\pq$ and $\redGM{\ensuremath{{\sf G}}}{\motion{\dtsess}{a}[t_1,t_2]}$) % is the global type % defined (up to unfolding of recursive types) using the following rules: \begin{enumerate} \item\label{Item:GC1} $\redG{\big(\GvtPair {\sf p}\pq {{\ell}_i.{\ensuremath{{\sf G}}_i}}\big)}{\sf p}\ell\pq = \ensuremath{{\sf G}}_{k}$ if there exists $k \in I$ with $\ell = \ell_k$; \item\label{Item:GC1} $\redG{\big(\GvtPair {\sf r}{\sf s} {{\ell}_i.{\ensuremath{{\sf G}}_i}}\big)}{\sf p}\ell\pq =\GvtPair {\sf r} {\sf s} {{\ell}_i.{(\redG{\ensuremath{{\sf G}}_i}{{\sf p}}{\ell}{\pq})}}$ if $\{{\sf r}, {\sf s}\} \cap \{{\sf p}, \pq\} = \emptyset$; \item\label{Item:GC3} $\redG{(\ensuremath{g}₁ \ast \ensuremath{g}₂)}{\sf p}\ell\pq = (\ensuremath{g}₁' \ast \ensuremath{g}₂)$ if $\set{{\sf p},\pq}\subseteq \participant{\ensuremath{g}_1}$ and $\redG{\ensuremath{g}₁}{\sf p}\ell\pq = \ensuremath{g}₁'$ and symmetrically if $\set{{\sf p},\pq}\subseteq\participant{\ensuremath{g}_2}$; \item\label{Item:GC41} $\redGM{\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)}} {\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i[t_i;t'_i])}} = \motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT 0}^{\sf p}$ % where ${\sf p}$ is the unique minimal sender in $\ensuremath{{\sf G}}$. \item\label{Item:GC4} $\redGM{\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t}^{\sf p}} {\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i[t_i;t'_i])}} = \motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t'}^{\sf p}$ if $t' > t$ and for all $i$, $t'_i-t_i = t'-t$ and $t' \leq \lceil\ensuremath{\mathit{a}}_i.D\rceil$ where $\lceil D\rceil$ denotes the upper bound of the interval $D$; \item\label{Item:GC5} $\redGM{(\ensuremath{g}₁ \ensuremath{\ast} \ensuremath{g}₂)} {\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i[t_i;t'_i])_{{\sf p}_i∈ \participant{\ensuremath{g}_1} \uplus \participant{\ensuremath{g}_2}}}} = (\ensuremath{g}₁' \ensuremath{\ast} \ensuremath{g}₂')$ if $\redGM{\ensuremath{g}_j}{\motion{\dtsess}{({\sf p}_i:\ensuremath{\mathit{a}}_i[t_i;t'_i])_{{\sf p}_i∈\participant{\ensuremath{g}_j}}}} = \ensuremath{g}_j'$ ($j=1,2$) \item\label{Item:GC6} $\redGM{\ensuremath{g}}{x}= \ensuremath{g}'$ then $\redGM{\ensuremath{g}.\ensuremath{g}_1}{x}= \ensuremath{g}'.\ensuremath{g}_1$ and $\redGM{\ensuremath{g}.\ensuremath{{\sf G}}}{x}= \ensuremath{g}'.\ensuremath{{\sf G}}$. \item\label{Item:GC7} $\redGM{\ensuremath{g}}{x} = \ensuremath{g}'$ if $∃\ensuremath{g}''.\exists \ASENDPC.\, \redastGequiv{\emptyset\rhd \ensuremath{g}}{\ASENDPC \rhd \ensuremath{g}''}$ and $\redGM{\ensuremath{g}''}{x} = \ensuremath{g}'$ where $C$ is a reduction context of the prefix defined as: $C = C.g \ensuremath{~~\mathbf{|\!\!|}~~ } C\ensuremath{\ast} g \ensuremath{~~\mathbf{|\!\!|}~~ } g \ensuremath{\ast} C \ensuremath{~~\mathbf{|\!\!|}~~ } [\ ]$ and $\ASENDPC$ is a set of enabled senders such that $\ASENDPC\subseteq \ensuremath{\Bbb P}$ and \begin{enumerate} \item\label{Item:GC7A} $\redGequiv{\ASENDPC\rhd C[\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t}^{\sf p}]}{ \ASENDPC \cup\set{{\sf p}} \rhd C }$ if $∃ i.~{\sf p}_i = {\sf p} \wedge t ∈ D_i \wedge {\ddagger}_i = {\mathsf{\rightsquigarrow}}$. \item\label{Item:GC7B} $\redGequiv{\ASENDPC\rhd C[\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t}^{\sf p}]}{\ASENDPC \rhd C}$ with ${\sf p}\in\ASENDPC$ and for all $i$, ${\sf p}_i\not = {\sf p}$ and $t\in D_i$. \end{enumerate} \begin{comment} \RMi{OLD 7a, 7b:} \item $\redGM{\ensuremath{g}}{x} =\ensuremath{g}'$ and if $∃\ensuremath{g}''.\, \redGequiv{\ensuremath{g}}{\ensuremath{g}''} ∧ \redGM{\ensuremath{g}''}{x} = \ensuremath{g}'$ \begin{enumerate} \item $\redGequiv{C[\motion{\dtsess}{({\sf p}_i{:}\ensuremath{\mathit{a}}_i)\AT t}]}{C}$ if $∃ i.~ t ∈ D_i ∧ {\ddagger}_i = {\mathsf{\rightsquigarrow}}$ where $C$ is a reduction context of the prefix defined as: $C = C.g \ensuremath{~~\mathbf{|\!\!|}~~ } C\ensuremath{\ast} g \ensuremath{~~\mathbf{|\!\!|}~~ } g \ensuremath{\ast} C \ensuremath{~~\mathbf{|\!\!|}~~ } [\ ]$. \item $\redGequiv{C^-[\motion{\dtsess}{({\sf p}_i: \ensuremath{\mathit{a}}_i)\AT t}]}{C^-}$ if $\forall i.~ t ∈ D_i ∧ {\ddagger}_i = {\mathsf{\lightning}}$ where $C^-$ is a separation reduction context of the prefix defined as: $C^- = C^-\ensuremath{\ast} g \ensuremath{~~\mathbf{|\!\!|}~~ } C^- \ensuremath{\ast} g \ensuremath{~~\mathbf{|\!\!|}~~ } [\ ]$. \end{enumerate} \end{comment} \end{enumerate} \begin{comment} \[ \small \begin{array}{r@{\hskip 2mm}c@{\hskip 2mm}l} \redG{\big(\Gvti {\sf p}\pq {[\mathcal{P}_i]\ell} {\mathcal{P}'}{\ensuremath{{\sf G}}}\big)}{\sf p}\ell\pq & = & \ensuremath{{\sf G}}_{k} \\ & & \text{if\; }\exists k \in I : \ell = \ell_k \\[3mm] \redG{\big(\Gvti {\sf r}{\sf s} {[\mathcal{P}_i]\ell} {\mathcal{P}'} {\ensuremath{{\sf G}}}\big)}{\sf p}\ell\pq & = & \Gvtir {\sf r} {\sf s} \ell {\mathcal{P}'}{\ensuremath{{\sf G}}} \\ & & \hspace{1mm} \text{if\; } \{{\sf r}, {\sf s}\} \cap \{{\sf p}, \pq\} = \emptyset ~\land~ \forall i \!\in\! I: \{{\sf p}, \pq\} \!\subseteq\! G_i \\[3mm] \redG{(\ensuremath{{\sf G}}₁ ∥ \ensuremath{{\sf G}}₂).\ensuremath{{\sf G}}}{\sf p}\ell\pq & = & (\ensuremath{{\sf G}}₁' ∥ \ensuremath{{\sf G}}₂).\ensuremath{{\sf G}} \\ & & \hspace{1mm} \text{if\; }\exists \redG{\ensuremath{{\sf G}}₁}{\sf p}\ell\pq = \ensuremath{{\sf G}}₁' \\[3mm] \redG{(\ensuremath{{\sf G}}₁ ∥ \ensuremath{{\sf G}}₂).\ensuremath{{\sf G}}}{\sf p}\ell\pq & = & (\ensuremath{{\sf G}}₁ ∥ \ensuremath{{\sf G}}₂').\ensuremath{{\sf G}} \\ & & \hspace{1mm} \text{if\; }\exists \redG{\ensuremath{{\sf G}}₁}{\sf p}\ell\pq = \ensuremath{{\sf G}}₂' \\[3mm] \redGM{\Gmotion{\dtsess}{\{a_i\}{i∈I}@t}{\ensuremath{{\sf G}}} }{\motion{\dtsess}{\{a_i[t_i;t'_i]\}_{i∈I}}} & = & \Gmotion{\dtsess}{\{a_i\}_{i∈I}@t'}{\ensuremath{{\sf G}}} \\[3mm] & & \hspace{1mm} \text{if\; } ∀ i, j.~ t'_i-t_i = t'_j-t_j = t'-t ∧ t' > t ∧ t' ∈ D_i\\[3mm] \redGM{(\ensuremath{{\sf G}}₁ ∥ \ensuremath{{\sf G}}₂).\ensuremath{{\sf G}}}{\motion{\dtsess}{\{a_i[t_i;t'_i]\}_{i∈I⊎J}}} & = & (\ensuremath{{\sf G}}₁' ∥ \ensuremath{{\sf G}}₂').\ensuremath{{\sf G}} \\ & & \hspace{1mm} \text{if\; } \redGM{\ensuremath{{\sf G}}₁}{\motion{\dtsess}{\{a_i[t_i;t'_i]\}_{i∈I}}} = \ensuremath{{\sf G}}₁' ∧ \redGM{\ensuremath{{\sf G}}₂}{\motion{\dtsess}{\{a_i[t_i;t'_i]\}_{i∈J}}} = \ensuremath{{\sf G}}₂' \\[3mm] \redGM{\ensuremath{{\sf G}}}{x} & = & \ensuremath{{\sf G}}' \\ & & \hspace{1mm} \text{if\;} ∃\ensuremath{{\sf G}}''.\, \redGequiv{\ensuremath{{\sf G}}}{\ensuremath{{\sf G}}''} ∧ \redGM{\ensuremath{{\sf G}}''}{x} = \ensuremath{{\sf G}}' \\[3mm] \end{array} \] \end{comment} In (6) and (7), we write $x$ as either ${{\sf p}}\rightarrow{\pq}$ or $\motion{\dtsess}{a}[t_1,t_2]$. The \emph{reduction of global types} % is the smallest pre-order relation closed under the rule: \( \ensuremath{{\sf G}}\Longrightarrow\redG \ensuremath{{\sf G}}{\sf p}{\ell}\pq \quad \text{and} \quad \ensuremath{{\sf G}}\Longrightarrow\redGM{\ensuremath{{\sf G}}}{\motion{\dtsess}{{\sf p}_i{:}\ensuremath{\mathit{a}}_i[t_i,t'_i]}} \). \end{definition} \noindent Note that the above reduction preserves well-formedness of global types. We can now state the main results. Our typing system is based on one in \cite{DBLP:journals/jlp/GhilezanJPSY19} with motion primitives and refinements. Since the global type reduction in Definition~\ref{def:global-type-consumption} is only related to communications or synchronisation of motions but not refinements, (1) when the two processes ${\sf p}$ and $\pq$ synchronise by a communication, its global type can always reduce; or (2) when all processes synchronise by the same motion action, their corresponding global type can always be consumed. Thus process behaviours correspond to reductions of global types, which is formulated as in the following theorem. Recall $\xrightarrow{\alpha}$ denotes any transition relation or reduction. \begin{restatable}[Subject Reduction]{theorem}{theoremSR} \label{th:SR} Let $M$ be a multiparty session, $\ensuremath{{\sf G}}$ be a well-formed global type, and a physical state $I$ such that $\der{I}{M}{\ensuremath{{\sf G}}}$. For all $M'$, if $M \xrightarrow{\alpha} M'$, then $\der{I'}{M'}{{\ensuremath{{\sf G}}}'}$ for some ${\ensuremath{{\sf G}}}'$, $I'$ such that ${\ensuremath{{\sf G}}}\Longrightarrow{\ensuremath{{\sf G}}}'$. Thus, if $M\equiv M'$ or $M \xrightarrow{\alpha_1}\cdots\xrightarrow{\alpha_n} M'$, then $\der{}{M'}{{\ensuremath{{\sf G}}}'}$ for some ${\ensuremath{{\sf G}}}'$ such that ${\ensuremath{{\sf G}}}\Longrightarrow{\ensuremath{{\sf G}}}'$. \end{restatable} \iftoggle{full}{ See Appendix~\ref{app:sr} for the detailed proofs. }{ See \cite{fullversion} for the detailed proofs. } Below we state the two progress properties as already explained in {Sec.}~\ref{sec:example}. The first progress is related to communications, while the second one gurantees the typed multiparty session processes are always collision free. As a consequence, if $\der{I}M{\ensuremath{{\sf G}}}$ for a well-formed type, then $M$ does not get stuck and can always reduce. \begin{restatable}[Progress]{theorem}{theoremPROG} \label{th:progress} Let $M$ be a multiparty session, $\ensuremath{{\sf G}}$ be a well-formed type, and a physical state $I$. If $\der{I}M{\ensuremath{{\sf G}}}$ then: \begin{enumerate} \item {\sc (Communication and Motion Progress)} there is $M'$ such that $M \longrightarrow M'$ and \item {\sc (Collision-free Progress)} If $M \longrightarrow^\ast M'$, then $M'$ is also collision free. \end{enumerate} \end{restatable} \begin{proof} ({\em Outline -- \iftoggle{full}{ see Appendix~\ref{app:sr} for the detailed proofs }{ see \cite{fullversion} for the detailed proofs. } }) {\em (Communication Progress)} The proof is divided into two cases: (a) the guard appearing in the branching type followed by (b) a message exchange between two parties. Case (a) follows from the fact that there is always at least one guard in a choice whose predicate is evaluated to true (Definition \ref{def:well-formed}(1)). The typing rules ensure that the predicates are satisfied when a message is sent. Case (b) is proved using Theorem~\ref{th:SR} with Definition \ref{def:well-formed}(4) since the unique minimal sender in $G$ can always send a message. {\em (Motion Progress)} For executing motions, Definition~\ref{def:well-formed}(3) and Theorem~\ref{th:motion-compat} ensure local trajectories can be composed into global trajectories. {\em (Collision-free Progress)} By induction. Under $I$ and by \rulename{t-sess}, $M$ is initially collision free. For the communication, note that it does not change the physical state, and therefore, does not impact the geometric footprint used by a process. Hence the case $\redG \ensuremath{{\sf G}}{\sf p}\ell\pq$ is straightforward. For motion actions, Definition~\ref{def:well-formed}(3) and Theorem~\ref{th:motion-compat} ensures collision freedom through execution steps. For a collision free program, collision freedom of the next state follows from compatibility of motion. \end{proof} \begin{comment} \begin{remark}[Time Divergence] \label{rem:timediv} \NYi{We can look at our CONCUR paper today. This remark sounds a bit weak} \DZi{The CONCUR paper looks at a sightly different problem. There the issue comes from the asynchronous communication. Here the issue comes from the flow and the imperative loops. For the communication, we could do like in the ECOOP paper: force loops to contain a flow. However, it would not fix the issue completely. Example such the bouncing ball (\url{https://www.mathworks.com/help/simulink/examples/simulation-of-a-bouncing-ball.html}) can be encoded with a flow and a loop, no communication needed.} The progress theorem checks that a program can always make a step. However, it does not guarantees that time progresses. For instance, there could be a $0$ time loop where processes send and receive an unbounded number of messages. Similarly, the proof system for motion primitive does not guarantee that a motion terminates. Progress of time is a challenging issue when modeling cyber-physical systems. Not only can there be $0$ time loops, there can as also be Zeno traces, i.e. flows which progress by smaller and smaller amount until they converge to a finite value. Often, one simply assumes that time diverges \cite{Henzinger96}. As future work, we plan to investigate liveness concern and how to modify our proof and type system to also provide liveness guarantees. \end{remark} \end{comment} \subsection{A More Complex Coordination Example with Producer} \label{subsec:large} We now discuss an extended version of the coordination example from {Sec.}~\ref{sec:example} that we shall implement on physical robots in {Sec.}~\ref{sec:eval}. In addition to cart and two arms, we add a producer robot. The ${\color{roleColor}{\mathsf{Prod}}}$ generates green or red parts and places them on to the cart. The cart ${\color{roleColor}{\mathsf{Cart}}}$ carries the part to the two robot arms as before. We shall use this extended version as the basis for one of our case studies. The coordination protocol is as follows. First, the protocol starts by syncing all participants. Then, the cart moves to the producer after announcing a message $\mathit{arrive}$. While the cart moves to the producer, the two consumer robots can work independently. When the cart is at the producer, it synchronises through a message $\mathit{ready}$, and idles while the producer places an object on to it. When the producer is done, it synchronises with the cart, and tells it whether the object is green or red. Based on this information, the cart tells one of the consumers that it is arriving with a part and tells the other consumer that it is free to work. Subsequently, the cart moves to the appropriate consumer to deposit the part, while the other consumer as well as the producer is free to continue their work. When the robot is at the consumer, it syncs through a message, and idles until the part is taken off. After this, the protocol starts again as the cart makes its journey back to the producer, while the consumers independently continue their work. \begin{figure*}[t] {\small \begin{align*} \text{Initial Phase} \ \equiv\ \begin{array}{l} {\color{roleColor}{\mathsf{Cart}}} \to {\color{roleColor}{\mathsf{Prod}}}: \mathit{arrive}. {\color{roleColor}{\mathsf{Cart}}}\to {\color{roleColor}{\mathsf{GRobot}}}: \mathit{start}.{\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{RRobot}}}:\mathit{start}.\\ \left( \begin{array}{ccc} \left( \begin{array}{l} (\motion{\dtsess}{\tuple{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_move}^{\mathsf{\rightsquigarrow}}({\color{roleColor}{\mathsf{Prod}}}), {\color{roleColor}{\mathsf{Prod}}}:\mathsf{work}^{\mathsf{\lightning}}}}^{\color{roleColor}{\mathsf{Cart}}}.\\ {\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{Prod}}}:\mathit{ready}.\motion{\dtsess}{{\color{roleColor}{\mathsf{Cart}}}:\mathsf{m\_idle}^{\mathsf{\lightning}},{\color{roleColor}{\mathsf{Prod}}}:\mathsf{place}^{\mathsf{\rightsquigarrow}}})^{\color{roleColor}{\mathsf{Prod}}}. \end{array} \right) \\ \quad\quad ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{RRobot}}}: \mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Prod}}} ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{GRobot}}}: \mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Prod}}} \end{array} \right) \end{array} \end{align*} \begin{align*} \begin{array}{l} \text{Process Green Item} \ \equiv\ \\ \quad \quad \left( \begin{array}{cc} \motion{\dtsess}{{\color{roleColor}{\mathsf{Prod}}}:\mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Cart}}}) ~\ensuremath{\ast}~ & \left( \begin{array}{l} {\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{GRobot}}}:\mathit{arrive}.{\color{roleColor}{\mathsf{Cart}}}\to{\color{roleColor}{\mathsf{RRobot}}}:\mathit{free}. \\ \left(\begin{array}{cc} \text{as in the green box in Figure~\ref{fig:basic-example}} & ~\ensuremath{\ast}~ \motion{\dtsess}{{\color{roleColor}{\mathsf{RRobot}}}:\mathsf{work}^{\mathsf{\lightning}}}^{\color{roleColor}{\mathsf{Cart}}} \end{array}\right) \end{array} \right) \end{array} \right) \\ \end{array} \end{align*} \begin{align*} \text{Global Type} \ \equiv \ \mu \mathbf{t}. & \langle \text{Initial Phase}\rangle. \left( \begin{array}{l} ({\color{roleColor}{\mathsf{Prod}}} \to{\color{roleColor}{\mathsf{Cart}}}:\mathit{green}. \langle \text{Process Green Item} \rangle)\\ + ({\color{roleColor}{\mathsf{Prod}}}\to{\color{roleColor}{\mathsf{Cart}}}:\mathit{red}. \langle \text{Process Red Item} \rangle) \end{array} \right) .\mathbf{t} \end{align*} } \vspace{-3mm} \caption{Motion session type annotated with minimal senders. For readability, we have broken the type into sub-parts: the initial phase, and processing items (the type for processing red items is symmetric and omitted)\label{fig:annotated-global-session-type}} \end{figure*} \myparagraph{Global Type} The global type for the example extends one in Figure~\ref{fig:basic-example}, and is shown in Figure~\ref{fig:annotated-global-session-type}. It can be seen that the global type has total choice (trivially), and is well-scoped and synchronisable. The motion primitive specifications are omitted; we ensure in our evaluation that the motion primitives are compatible and the type is fully separated using calls to the SMT solver dReal. \myparagraph{Processes} The processes in this example extend the processes from {Sec.}~\ref{sec:example} but the ${\color{roleColor}{\mathsf{RRobot}}}$ and ${\color{roleColor}{\mathsf{GRobot}}}$ processes are as before: \[ \begin{array}{ll} {\color{roleColor}{\mathsf{Cart}}}: & \begin{array}{l}\small \mu {\roleVar}. {\color{roleColor}{\mathsf{Prod}}}!\mathit{arrive}.{\color{roleColor}{\mathsf{RRobot}}}!\mathit{start}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{start}.\mathsf{m\_move}(\text{co-ord of }{\color{roleColor}{\mathsf{Prod}}}).{\color{roleColor}{\mathsf{Prod}}}!\mathit{ready}.\mathsf{m\_idle}.\\ \ ({\color{roleColor}{\mathsf{Prod}}}?\mathit{red}.{\color{roleColor}{\mathsf{RRobot}}}!\mathit{arrive}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{free}.\mathsf{m\_move}(\text{co-ord of }{\color{roleColor}{\mathsf{RRobot}}}).\\ \ \ \ \quad\quad {\color{roleColor}{\mathsf{RRobot}}}!\mathit{ready}.\mathsf{m\_idle}.{\color{roleColor}{\mathsf{RRobot}}}?\mathit{ok}.{\roleVar}\\ \ + {\color{roleColor}{\mathsf{Prod}}}?\mathit{green}.\textrm{ symmetrically for ${\color{roleColor}{\mathsf{GRobot}}}$ }) \end{array} \\[3mm] {\color{roleColor}{\mathsf{Prod}}}: & \begin{array}{l}\small \mu {\roleVar}.{\color{roleColor}{\mathsf{Cart}}}?\mathit{arrive}.\mathsf{work}.{\color{roleColor}{\mathsf{Cart}}}?\mathit{ready}.\mathsf{place}. ({\color{roleColor}{\mathsf{Cart}}}!\mathit{green} + {\color{roleColor}{\mathsf{Cart}}}!\mathit{red}).\mathsf{work}.{\roleVar} \end{array} \end{array} \] \begin{comment} \[ \begin{array}{c|c} \begin{array}{rl}\small {\color{roleColor}{\mathsf{Cart}}}:\!\!\!\!\!\!\\ \mu {\roleVar}.\!\!\!\!\!\! & {\color{roleColor}{\mathsf{Prod}}}!\mathit{arrive}.{\color{roleColor}{\mathsf{RRobot}}}!\mathit{start}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{start}.\\ & \mathsf{m\_move}(\text{co-ord of }{\color{roleColor}{\mathsf{Prod}}}).{\color{roleColor}{\mathsf{Prod}}}!\mathit{ready}.\mathsf{m\_idle}.\\ & \ ({\color{roleColor}{\mathsf{Prod}}}?\mathit{red}.{\color{roleColor}{\mathsf{RRobot}}}!\mathit{arrive}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{free}.\\ & \ \quad \mathsf{m\_move}(\text{co-ord of }{\color{roleColor}{\mathsf{RRobot}}}).{\color{roleColor}{\mathsf{RRobot}}}!\mathit{ready}.\\ & \ \quad \mathsf{m\_idle}.{\color{roleColor}{\mathsf{RRobot}}}?\mathit{ok}.{\roleVar}\\ & \ + {\color{roleColor}{\mathsf{Prod}}}?\mathit{green}.\textrm{ symmetrically for ${\color{roleColor}{\mathsf{GRobot}}}$ }) \end{array} & \begin{array}{rl}\small {\color{roleColor}{\mathsf{Prod}}}:\!\!\!\!\!\!\!\!\!\!\\ \mu {\roleVar}.\!\!\!\!\!\!& {\color{roleColor}{\mathsf{Cart}}}?\mathit{arrive}.\mathsf{work}.\\ & {\color{roleColor}{\mathsf{Cart}}}?\mathit{ready}.\mathsf{place}.\\ & ({\color{roleColor}{\mathsf{Cart}}}!\mathit{green} + {\color{roleColor}{\mathsf{Cart}}}!\mathit{red}).\mathsf{work}.{\roleVar} \end{array} \end{array} \] \end{comment} \myparagraph{Local Types} The local types for the components are: \begin{align*} \small \begin{array}{c|c} \small \begin{array}{rl} {\color{roleColor}{\mathsf{Cart}}}:\!\!\!\!\!\!\\ \mu \mathbf{t}. & {\color{roleColor}{\mathsf{Prod}}}!\mathit{arrive}(t).{\color{roleColor}{\mathsf{RRobot}}}!\mathit{start}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{start}.\\ & \motion{\dtsess}{\mathsf{m\_move}({\color{roleColor}{\mathsf{Prod}}})}.{\color{roleColor}{\mathsf{Prod}}}!\mathit{ready}.\motion{\dtsess}{\mathsf{m\_idle}}.\\ & (\ ({\color{roleColor}{\mathsf{Prod}}}?\mathit{green}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{arrive}(t).{\color{roleColor}{\mathsf{RRobot}}}!\mathit{free}.\\ & \ \ \motion{\dtsess}{\mathsf{m\_move}({\color{roleColor}{\mathsf{GRobot}}})}.{\color{roleColor}{\mathsf{GRobot}}}!\mathit{ready}.\\ & \ \ \motion{\dtsess}{\mathsf{m\_idle}}.{\color{roleColor}{\mathsf{GRobot}}}?\mathit{ok}) \\ & \& \ ({\color{roleColor}{\mathsf{Prod}}}?\mathit{red}. \ldots \text{symmetric} \ldots)\ ).\mathbf{t} \end{array} & \begin{array}{l} {\color{roleColor}{\mathsf{Prod}}}:\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\\ \quad\mu \mathbf{t}. {\color{roleColor}{\mathsf{Cart}}}?\mathit{arrive}(t).\motion{\dtsess}{\mathsf{work}}.{\color{roleColor}{\mathsf{Cart}}}?\mathit{ready}.\motion{\dtsess}{\mathsf{place}}.\\ \quad\quad ({\color{roleColor}{\mathsf{Cart}}}!\mathit{green}.\motion{\dtsess}{\mathsf{work}}.\mathbf{t}\; \oplus \; {\color{roleColor}{\mathsf{Cart}}}!\mathit{red}.\motion{\dtsess}{\mathsf{work}}.\mathbf{t})\\ {\color{roleColor}{\mathsf{RRobot}}},{\color{roleColor}{\mathsf{GRobot}}}:\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\\ \quad\mu \mathbf{t}. ({\color{roleColor}{\mathsf{Cart}}}?\mathit{start}.\motion{\dtsess}{\mathsf{work}}.\\ \quad\quad(\ ({\color{roleColor}{\mathsf{Cart}}}?\mathit{arrive}(t).\motion{\dtsess}{\mathsf{work}}.\\ \quad\quad {\color{roleColor}{\mathsf{Cart}}}?\mathit{ready}.\motion{\dtsess}{\mathsf{pick}}.{\color{roleColor}{\mathsf{Cart}}}!\mathit{ok}) \\ \quad\quad\& \; ({\color{roleColor}{\mathsf{Cart}}}?\mathit{free}.\motion{\dtsess}{\mathsf{work}}) \ ).\mathbf{t} \end{array} \end{array} \end{align*} We can show that all the processes type check. From the soundness theorems, we conclude that the example satisfies communication safety, motion compatibility, and collision freedom. \section{Related Work} \label{sec:related} The field of concurrent robotics has made enormous progress---from robot soccer to self-driving systems and to industrial manufacturing. However, to the best of our knowledge, none of these impressive systems come with formal guarantees of correctness. Our motivation, like many other similar projects in the area of high-confidence robotics and cyber-physical systems design, is to be able to reason formally about such systems. A spectrum of computer-assisted formal methods techniques can be, and have been, applied to reasoning about concurrent robotics, ranging from interactive theorem proving to automated analysis via model checking. As is well known, these techniques provide a tradeoff between manual effort and the expressiveness of specifications and the strength of guarantees. Our choice using manually specified choreographies and motion primitive specifications and automatically checked type correctness attempts to explore a point in the design space that requires manual abstraction of motion and geometry but provides automated checks for the interaction. We build on a type-based foundation rather than global model checking to again reflect the tradeoff: our use of choreographies and projections from global to local types restricts the structure of programs that can be type checked but enables a more scalable \emph{local} check for each process; in contrast, a model checking approach could lead to state-space explosion already at the level of concurrency. There are a vast number of extensions and applications of session types and choreographies~\cite{Huttel:2016:FST:2911992.2873052,ABBCCDGGGHJMMMNNPVY2016,BETTY2017}, but little work bringing types to practical programming in the domain of robotics or cyber-physical systems. We discuss the most related work. Our starting point was the theory of motion session types and PGCD \cite{PGCD,ECOOP19}, whose goals are similar to ours. We considerably extend the scope and expressiveness of motion session types: through \emph{continuous-time} motion primitives and through separating conjunction for modular synchronisation. Syntactic extensions of original global types \cite{HYC08} to represent more expressive communication structures have been studied, e.g.,~in \cite{DBLP:conf/popl/LangeTY15}, in the context of synthesis from communicating automata; in~\cite{DBLP:journals/corr/abs-1203-0780} to include parallel and choices; in \cite{DH2012} to represent nested global types. Our aim is to include the minimum syntax extension to \cite{HYC08} to represent separation and synchronisations best suited to implementing robotics applications. In turn, a combination of motion primitives and predicates required us to develop a novel and non-trivial data flow analysis of global choreographies for the well-formedness check. Hybrid extensions to process algebras \cite{RoundsS03,DBLP:journals/iandc/LynchSV03,BERGSTRA2005215,DBLP:conf/aplas/LiuLQZZZZ10} extend process algebras with hybrid behaviour and study classical concurrency issues such as process equivalences. Extensions to timed (but not hybrid) specifications in the $\pi$-calculus are studied in \citet{BYY2014,BMVY2019} to express properties on times on top of \emph{binary} session typed processes. The theory of hybrid automata \cite{ACHH,Henzinger96} provides a foundation for verifying models of hybrid systems. The main emphasis in hybrid automaton research has been in defining semantics and designing model checking algorithms---too many to enumerate, see \cite{Henzinger96,Platzer18}---and not on programmability. Assume guarantee reasoning for hybrid systems has been studied, e.g.~\cite{Nuzzo:EECS-2015-189,DBLP:journals/fteda/BenvenisteCNPRR18,DBLP:journals/pieee/NuzzoSBGV15,DBLP:journals/pieee/Tripakis16}. These works do not consider programmability or choreography aspects. Deductive verification for hybrid systems attempts to define logics and invariant-based reasoning to hybrid systems. Differential dynamic logic (dL) \cite{Platzer18,PlatzerT18} is a general logical framework to deductively reason about hybrid systems. It extends \emph{dynamic logic} with differential operators and shows sound and (relatively) complete axiomatisations for the logic. Keymaera \cite{DBLP:conf/cade/FultonMQVP15} and HHL Prover \cite{HHL} are interactive theorem provers based on hybrid progam logics. These tools can verify complex properties of systems at the cost of intensive manual effort. In contrast, we explore a point in the design space with more automation but less expressiveness. The ``trusted base'' in an interactive theorem prover is the core logic; optimizing the trusted base was not one of our goals. A well-studied workflow in high-confidence cyber-physical systems is model-based design (see, e.g., \cite{HenzingerSifakis07} for an overview), where a system is constructed by successive refinement of an abstract model down to an implementation. An important problem in model-based design is to ensure property-preserving refinement: one verifies properties of the system at higher levels of abstraction, and ensures that properties are preserved through refinement. In the presence of continuous dynamics, defining an appropriate notion of refinement and proving property-preserving compilation formally are hard problems \cite{DBLP:journals/tosem/YanJWWZ20,DBLP:conf/pldi/BohrerTMMP18}. In our implementation, we use \emph{automated} tools based on the dReal SMT solver \cite{dReal}. Our verification is \emph{semi-automatic}, as we require user annotations for footprints or for the motion primitive specifications, but discharge verification conditions through dReal. Of course, there are programs that go past the capability of the solver---this is already true for systems that \emph{only} have concurrency or only deal with dynamics. Our proof rules is to allow sound reasoning, potentially inside an interactive prover. Our implementation shows that---at least some---nontrivial examples do allow automation. Non-linear arithmetic is difficult to scale. Our observation is that a combination of manual specification of \emph{abstract} footprints that replace complex geometrical shapes with simpler over-approximations along with the power of state-of-the-art SMT solvers is reasonably effective even for complicated examples. Our choice of dReal (as opposed to a different SMT solver) is dReal's ``off the shelf'' support for non-linear arithmetic and trigonometric functions. Trigonometry shows up in our handling of frame shifts. Note that dReal only considers $\delta$-decidability and can be incomplete in theory. We expect that most implementations will be collision free in a ``robust'' way (that is, two robots will not just not collide, they would be separated by a minimum distance). Therefore we believe the potential incompleteness is less of a concern. Indeed, the main limiting factor in our experiments was scalability for larger verification conditions. Formal methods have been applied to multi-robot planning \cite{Drona,Antlab}. These systems ignore programming or geometry concerns and view robots as sequences of motion primitives. \begin{comment} Assume guarantee reasoning for hybrid systems has been studied, e.g.~\cite{Nuzzo:EECS-2015-189,DBLP:journals/fteda/BenvenisteCNPRR18,DBLP:journals/pieee/NuzzoSBGV15,DBLP:journals/pieee/Tripakis16}. However, much of this work is described at the level of abstract models and not at the level of programs. Moreover, usually assume guarantee reasoning and contracts do not, at the same time, consider the effects of message based synchronisation. Our work shows how assume guarantee contracts can be propagated through program syntax. Systems such as Drona \cite{Drona} or Antlab \cite{Antlab} model robots as discrete systems with motion primitives, and the main technical contribution is to perform temporal multi-agent non-modular planning for tasks. Instead, we provide a concurrency model, a modular typing discipline, and proof rules that model correct interaction between dynamics (time is ignored in other task management and synthesis systems beyond atomic discrete-time motion primitives) and concurrency, and geometry (also ignored in these systems---robots are ``point objects”). The theory of hybrid automata \cite{ACHH,Henzinger96} provides a foundation for verifying abstract models of hybrid systems. The main emphasis in hybrid automaton research has been in defining semantics and designing model checking algorithms---too many to enumerate, see \cite{Henzinger96,Platzer18}---and not on programmability or compositional reasoning. In particular, most analysis techniques for hybrid automata construct the product automaton to reason about concurrent subsystems. Hybrid extensions to process algebras \cite{RoundsS03,DBLP:journals/iandc/LynchSV03,BERGSTRA2005215} extend process algebras with hybrid behaviour; the emphasis is to define a formal model and study classical concurrency issues such as process equivalences. Programming languages incorporating hybrid behaviour have been studied in the synchronous programming literature \cite{Zelus,Averest}. Hybrid synchronous languages, such as Zelus, extend a synchronous model with differential equations to capture continuous-time evolution of state. While these languages come with simulation, verification, and compilation tools, they restrict concurrency and there is little work in compositional reasoning or geometric reasoning. The use of nonstandard models to provide semantics to hybrid systems goes back to Iwasaki et al.~\cite{DBLP:conf/ijcai/IwasakiFSBG95}. Our inspiration came from the use of nonstandard analysis to provide semantics for hybrid synchronous languages \cite{DBLP:journals/fuin/BliudzeK09,DBLP:journals/jcss/BenvenisteBCP12,DBLP:conf/hybrid/BenvenisteBCPP14}. \citet{DBLP:conf/icalp/SuenagaH11,DBLP:conf/cav/HasuoS12} give a nonstandard semantics for a hybrid ``while-language'' and use it as the basis for deductive program verification and static analysis \cite{DBLP:conf/vmcai/KidoCH16}. In all these approaches, the discrete steps appear because of evaluating predicates: the semantics provides a clear notion of when a signal crosses zero. The languages do not have additional concurrency features, such as synchronisation through messages. Moreover, none of the existing approaches consider compositional proof systems and, in particular, local reasoning based on physical-variables-as-resource. \citet{CardelliG12} define a process algebra for geometric interaction. Their formalism combines communication and frame shifting. However, they do not consider dynamics, which is crucial in a robotics context. We were inspired by concurrent separation logics, which combine reasoning about concurrency, state, and separation \cite{CSL,JungSSSTBD15,DBLP:conf/wollic/GardnerZ07,DBLP:conf/concur/VafeiadisP07}. These logics have mostly been studied for discrete systems, but our nonstandard view makes them applicable to continuous systems as well. Our reasoning about geometric separation and about passing permissions through predicate refinements is reminiscent of similar principles in concurrent separation logics. The main obstacle to using separation logics in our context is the use of frame shifts, which make the footprint of a process not a local property of a process but the property of its ancestors in the attached composition. It is an interesting open problem to model geometric space as a resource in an appropriate separation logic; we leave it for future work. \end{comment} \section{Discussion and Future Directions} \label{sec:discussion} In this paper, we have shown how choreographies can be extended with dynamic motion primitives to enable compositional reasoning in the presence of continuous-time dynamics. We have developed an automated verification tool and a compiler from type-correct programs to distributed robotics applications using ROS and commercial and custom-made robotics hardware. Our goal is to \emph{integrate} types and static analysis techniques into existing robotics frameworks, rather than provide fully verified stacks (see, e.g., \cite{DBLP:conf/pldi/BohrerTMMP18}). We explain our language features in terms of a calculus but session processes can be easily embedded into existing frameworks for robot programming. We have demonstrated that the language and type system are expressive enough to statically verify distributed manoeuvres on top of existing hardware and software. We view our paper as a first step in verifying robotics programs. There are many other important but yet unmodelled aspects. We outline several directions not addressed in our work. For example, we omit \emph{probabilistic robotics} aspects, including the perception stack (vision, LIDAR, etc.), and aspects such as filtering, localisation, and mapping \cite{ProbabilisticRobotics,LaValle2012}. These will require a probabilistic extension to our theory. Such a theory requires a nontrivial extension of program logics and analyses for probabilistic programs \cite{McIverMorgan} with the verification and synthesis for stochastic continuous-state systems \cite{ZamaniEMAL14}. We also omit any modeling of the perception stack or dynamic techniques, often based on machine learning, of learning the environment. Instead, our models \emph{assume} worst-case disturbance bounds on the sensing or dynamics. We believe an integration of learning techniques with formal methods is an interesting challenge but goes beyond the scope of this paper. Our framework statically verifies properties of a program. In practice, robots work in dynamic, often unknown, environments \cite{LaValle,LaValle2012,Siegwart,ProbabilisticRobotics}. When confronted with a formal method, domain experts often expect that a verification methodology should be able to verify correctness of behaviors in an \emph{arbitrary} dynamic environment and any failure to do so simply shows the inadequacy of verification techniques. Formal methods cannot prove correctness in an \emph{arbitrary} dynamic environment. When we verify a system, it is---as true in any formal methods---\emph{relative} to an environment assumption; such assumptions are usually implicit in robotics implementations. Thus, we can model moving obstacles, etc.\ in the environment through assumptions on the behaviour of such obstacles (e.g., limits on their speed or trajectories); these assumptions are propagated by our assume-guarantee proof system, and show up as a premise in the eventual correctness proof. We focus on communication safety and collision freedom as the basic correctness conditions any system has to satisfy. An interesting next step is to extend the reasoning to more expressive specifications. For safety specifications, such as invariants, one could reduce the problem to checking communication safety. For liveness specifications, the proof system would need to be extended with ranking arguments. While all the above problems are interesting in their own right, they are orthogonal to our main contribution that one can reason about concurrency and dynamics in continuous time in a type-based setting. Our future work will look at more expressive scenarios, but the setting in our paper already required complex proofs and it was important for us to get the core correct. We believe a verification system that can faithfully model and uniformly reason about more complex interactions and that scales to larger implementations remains a grand challenge in computer science (see, e.g., \cite{Lozano-Perez} for an articulation of these challenges).
{'timestamp': '2020-10-13T02:29:35', 'yymm': '2010', 'arxiv_id': '2010.05484', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05484'}
arxiv
\section{Introduction} Self-supervised approaches such as Momentum Contrast (MoCo) \citep{he2019moco, chen2020mocov2} can leverage unlabeled data to produce pretrained models for subsequent fine-tuning on labeled data. Contrastive learning of visual representations has emerged as the front-runner for self-supervision and has demonstrated superior performance on downstream tasks. In addition to MoCo, these include frameworks such as SimCLR \citep{chen2020simple, Chen2020Simclrv2} and PIRL \citep{misra2020self}. All contrastive learning frameworks involve maximizing agreement between positive image pairs relative to negative/different images via a contrastive loss function; this pretraining paradigm forces the model to learn good representations. These approaches typically differ in how they generate positive and negative image pairs from unlabeled data and how the data are sampled during pretraining. While MoCo and other contrastive learning methods have demonstrated promising results on natural image classification tasks, their application to medical imaging settings has been limited \citep{raghu2019transfusion, cheplygina2019not}. Chest X-ray is the most common imaging tool used in practice, and is critical for screening, diagnosis, and management of diseases. The recent introduction of large datasets (size 100k-500k) of chest X-rays \citep{irvin2019chexpert, mimic2019, Bustos2020PadChestAL} has driven the development of deep learning models that can detect diseases at a level comparable to radiologists \citep{rajpurkar2020chexaid,rajpurkar2021chexternal}. Because there is an abundance of unlabeled chest X-ray data \citep{raoof2012interpretation}, contrastive learning approaches represent a promising avenue for improving chest X-ray interpretation models. Chest X-ray interpretation is fundamentally different from natural image classification in that (1) disease classification may depend on abnormalities in a small number of pixels, (2) data attributes for chest X-rays differ from natural image classification because X-rays are larger, grayscale and have similar spatial structures across images (always either anterior-posterior, posterior-anterior, or lateral), (3) there are far fewer unlabeled chest X-ray images than natural images. These differences may limit the applicability of contrastive learning approaches, which were developed for natural image classification settings, to chest X-ray interpretation. For instance, MoCo uses a variety of data augmentations to generate positive image pairs from unlabeled data; however, random crops and blurring may eliminate disease-covering parts from an augmented image, while color jittering and random gray scale would not produce meaningful transformations for already grayscale images. Furthermore, given the availability of orders of magnitude fewer chest X-ray images than natural images, and larger image sizes, it remains to be understood whether retraining may improve on the traditional paradigm for automated chest X-ray interpretation, in which models are fine-tuned on labeled chest X-ray images from ImageNet-pretrained weights. In this work, we demonstrate that our proposed MoCo-CXR method leads to better representations and initializations than those acquired without MoCo-pretraining (solely from ImageNet) for chest X-ray interpretation. The MoCo-CXR pipeline involved first a modified MoCo-pretraining on CheXpert \citep{irvin2019chexpert}, where we adapted initialization, data augmentations, and learning rate scheduling of this pretraining step for successful application on chest X-rays. This was then followed by supervised fine-tuning experiments using different fractions of labeled data. We showed that MoCo-CXR-pretrained representations are of higher quality than ImageNet-pretrained representations by evaluating the performance of a linear classifier trained on pretrained representations on a chest X-ray interpretation task. We also demonstrated that a model trained end-to-end with MoCo-CXR-pretrained initialization had superior performance on the X-ray interpretation tasks, and the advantage was especially apparent at low labeled data regimes. Finally, we also showed that MoCo-CXR-pretrained representations from the source (CheXpert) dataset transferred to another small chest X-ray dataset (Shenzhen) with a different classification task \citep{jaeger2014two}. Our study demonstrates that MoCo-CXR provides high-quality representations and transferable initializations for chest X-ray interpretation. \section{Related Work} \paragraph{Self-supervised learning} Self-supervision is a form of unsupervised pretraining that uses a formulated pretext task on unlabeled data as the training goal. Handcrafted pretext tasks include solving jigsaw puzzles \citep{noroozi2016unsupervised}, relative patch prediction \citep{doersch2015unsupervised} and colorization \citep{zhang2016colorful}. However, many of these tasks rely on ad-hoc heuristics that could limit the generalization and transferability of learned representations for downstream tasks. Consequently, contrastive learning of visual representations has emerged as the front-runner for self-supervision and has demonstrated superior performance on downstream tasks \citep{chen2020mocov2, Chen2020Simclrv2}. \begin{wrapfigure}{r}{0.35\textwidth} \begin{center} \includegraphics[width=0.95\linewidth]{images/contrastive_learning.PNG} \end{center} \caption{Contrastive learning maximizes agreement of embeddings generated by different augmentations of the same chest X-ray image.} \label{fig:contrastive_learing} \end{wrapfigure} \paragraph{Contrastive learning for chest X-rays} Prior work using contrastive learning on chest X-rays is limited in its applicability to unlabeled data and evidence of transferability. A controlled approach is to explicitly contrast X-rays with pathologies against healthy ones using attention network \citep{liu2019align}; however, this approach is supervised. There has also been a proposed domain-specific strategy of extracting contrastive pairs from MRI and CT datasets using a combination of localized contrastive loss function and global loss function during pretraining \citep{chaitanya2020contrastive}. However, the method is highly dependent on the volumetric nature of MRI and CT scans, as the extraction of similar image pairs is based on taking 2D image slices of a single volumetric image. Thus, the technique would have limited applicability to chest X-rays. Work applying broader self-supervised techniques to medical imaging is more extensive. For example, encoding shared information between different imaging modalities for ophthalmology was shown to be an effective pretext task for pretraining diabetic retinopathy classification models \citep{Holmberg861757}. Other proposed pretext tasks in medical imaging include solving a Rubik’s cube \citep{medicalrubiks, ZHU2020101746}, predicting the position of anatomical patches \citep{bai2019cardiac}, anatomical reconstruction \citep{zhou2019models}, and image patch distance estimation \citep{spitzer2019cytoarch}. \paragraph{ImageNet transfer for chest X-ray interpretation} The dominant computer vision approach of starting with an ImageNet-pretrained model has been proven to be highly effective at improving model performance in diverse settings such as object detection and image segmentation \citep{Holmberg861757}. Although high performance deep learning models for chest X-ray interpretation use ImageNet-pretrained weights, \citet{sun2019unsupervised} found that common regularization techniques limit ImageNet transfer learning benefits and that ImageNet features are less general than previously believed. Moreover, \citet{medicalrubiks} showed that randomly-initialized models are competitive with their ImageNet-initialized counterparts on a vast array of tasks with sufficient labeled data, and that pretraining merely speeds up convergence. \citet{raghu2019transfusion} further investigated the efficacy of ImageNet pretraining, observing that simple convolutional architectures are able to achieve comparable performance as larger ImageNet model architectures. \section{Methods} \subsection{Chest X-ray datasets and diagnostic tasks} \label{sec:dataset} We used a large source chest X-ray dataset for pretraining and a smaller external chest X-ray dataset for the evaluation of model transferability. The source chest X-ray dataset we select is CheXpert, a large collection of chest X-ray images labeled for the presence or absence of several diseases \citep{irvin2019chexpert}. CheXpert consists of 224k chest X-rays collected from 65k patients. Chest X-ray images included in the CheXpert dataset are of size 320 $\times$ 320. We focused on identifying the presence of pleural effusion, a clinically important condition that has high prevalence in the dataset (with 45.63\% of all images labeled as positive or uncertain). We performed follow-up experiments with other CheXpert competition tasks (cardiomegaly, consolidation, edema and atelectasis) from \citet{irvin2019chexpert} to verify that our method worked on different pathologies. In addition, we use the Shenzhen Hospital X-ray set \citep{jaeger2014two} for evaluation of model transferability to an external target dataset. Chest X-ray images included in the Shenzhen dataset are of size 4020 $\times$ 4892 and 4892 $\times$ 4020. The Shenzhen dataset contains 662 X-ray images, of which 336 (50.8\%) are abnormal X-rays that have manifestations of tuberculosis. All images in both datasets are resized to 224 $\times$ 224 for MoCo-CXR. \subsection{MoCo-CXR Pretraining for Chest X-ray Interpretation} \label{sec:self_sup} We adapt the MoCo-pretraining procedure to chest X-rays. MoCo is a form of self-supervision that utilizes contrastive learning, where the pretext task is to maximize agreement between different views of the same image (positive pairs) and to minimize agreement between different images (negative pairs). Figure~\ref{fig:contrastive_learing} illustrates how data augmentations are used to generate views of a particular image and are subsequently contrasted to learn embeddings in an unsupervised fashion. Our choice to use MoCo is driven by two constraints in medical imaging AI: (1) large image sizes, and (2) the cost of large computational resources. Compared to other self-supervised frameworks such as SimCLR \citep{chen2020simple}, MoCo requires far smaller batch sizes during pretraining \citep{chen2020mocov2}. The MoCo implementation used a batch size of 256 and achieved comparable performance on ImageNet as the SimCLR implementation, which used a batch size of 4096; in contrast, SimCLR experienced lower performance at a batch size of 256 \citep{chen2020mocov2}. MoCo's reduced dependency on mini-batch size is achieved by using a momentum updated queue of previously seen samples to generate contrastive pair encodings. An illustration of MoCo's momentum encoding framework has been added as Appendix Figure~\ref{fig:momemtum}. Using MoCo, we were able to conduct experiments on a single NVIDIA GTX 1070 with a batch size of 16. We performed MoCo-pretraining on the entire CheXpert training dataset. We chose to apply MoCo-pretraining on ImageNet-initialized models to leverage possible convergence benefits \citep{raghu2019transfusion}. Due to the widespread availability of ImageNet-pretrained weights, there is no extra cost to initialize models with ImageNet weights before MoCo-pretraining. \begin{figure}[t] \centering \includegraphics[width=0.75\linewidth]{images/Moco_flowchart_horizontal_20210313.png} \caption{MoCo-CXR training pipeline. MoCo acts as self-supervised training agent. The model is subsequently tuned using chest X-ray images.} \label{fig:workflow} \end{figure} We modified the data augmentation strategy used to generate views suitable for the chest X-ray interpretation task. Data augmentations used in self-supervised approaches for natural images may not be appropriate for chest X-rays. For example, random crop and Gaussian blur could change the disease label for an X-ray image or make it impossible to distinguish between diseases. Furthermore, color jittering and random grayscale do not represent meaningful augmentations for grayscale X-rays. Instead, we use random rotation (10 degrees) and horizontal flipping (Appendix Figure~\ref{fig:augs}), a set of augmentations commonly used in training chest X-ray models \citep{irvin2019chexpert, rajpurkar2017chexnet} driven by experimental findings in the supervised setting and clinical domain knowledge. Future work should investigate the impact of various additional augmentations and their combinations. The overall training pipeline with MoCo-CXR-pretraining and the subsequent fine-tuning with CheXpert and Shenzhen datasets is illustrated in Figure~\ref{fig:workflow}. We maintained hyperparameters related to momentum, weight decay, and feature dimension from MoCo \citep{chen2020mocov2}. Checkpoints from top performing epochs were saved for subsequent checkpoint selection and model evaluation. In the subsequent fine-tuning step, we selected hyperparameters based on performance of linear evaluations. We used two backbones, ResNet18 and DenseNet121, to evaluate the consistency of our findings across model architectures. We experimented with initial learning rates of $10^{-2}$, $10^{-3}$, $10^{-4}$ and $10^{-5}$, and investigated their effect on performance. We also experimented with milestone and cosine learning rate schedulers. \subsection{MoCo-CXR Model Fine-tuning} We fine-tuned models on different fractions of labeled training data. We also conducted baseline fine-tuning experiments with ImageNet-pretrained models that were not subjected to MoCo-CXR-pretraining. We use label fraction to represent the ratio of data with its labels retained during training. For a model trained with 1\% label fraction, the model will only have access to 1\% of the all labels, while the remaining 99\% of labels are hidden from the model. The use of label fraction is a proxy for the real world, where large amounts of data remain unlabelled and only a small portion of well-labelled data can be used toward supervised training. As presented in Figure~\ref{fig:workflow}, the label fractions of training sets are 0.1\%, 1\%, 10\% and 100\% for the CheXpert dataset and 6.25\%, 25\%, 100\% for the external Shenzhen dataset. Fine-tuning experiments on small label fractions are repeated multiple times with different random samples and averaged to guard against anomalous, unrepresentative training splits. To evaluate the transfer of representations, we froze the backbone model and trained a linear classifier on top using the labeled data (MoCo-CXR/ImageNet-pretrained Linear Models). In addition, we unfreeze all layers and fine-tune the entire model end-to-end using the labeled data to assess transferability on the overall performance (MoCo-CXR/ImageNet-pretrained end-to-end Models). Our models were fine-tuned using the same configurations as fully-supervised models designed for CheXpert \citep{irvin2019chexpert}, which has determined an optimal batch size, learning rate and other hyper-parameters. To be specific, we use a learning rate of $3\times 10^{-5}$, batch size of 16 and number of epochs that scale with the size of labeled data. For the CheXpert dataset, these are 220, 95, 41, 18 epochs for the 4 label fractions respectively. \subsection{Statistical analysis} We compared the performance of the models trained with and without MoCo-CXR-pretraining using the area under the receiver operating characteristic curve (AUC). To assess whether MoCo-CXR-pretraining significantly changed the performance, we computed the difference in AUC on the test set with and without MoCo-CXR-pretraining. The non-parametric bootstrap was used to estimate the variability around model performance. A total of 500 bootstrap replicates from the test set were drawn, and the AUC and its corresponding differences were calculated for the MoCo-CXR-pretrained model and non-Moco-CXR pretrained model on these same 500 bootstrap replicates. This produced a distribution for each estimate, and the 95\% bootstrap percentile intervals were computed to assess significance at the $p = 0.05$ level. \section{Experiments} \begin{figure}[t] \centering \includegraphics[width=0.55\linewidth]{images/cx_all_last_ci.PNG} \caption{AUC on pleural effusion task for linear models with MoCo-CXR-pretraining is consistently higher than AUC of linear models with ImageNet-pretraining, showing that MoCo-CXR-pretraining produces higher quality representations than ImageNet-pretraining does.} \label{fig:cx_all_last} \end{figure} \subsection{Transfer performance of MoCo-CXR-pretrained representations on CheXpert}\label{sec:cx_last} We investigated whether representations acquired from MoCo-CXR-pretraining are of higher quality than those transferred from ImageNet. To evaluate the representations, we used the linear evaluation protocol \citep{oord2018representation, zhang2016colorful, Kornblith_2019_CVPR, bachman2019learning}, where a linear classifier is trained on a frozen base model, and test performance is used as a proxy for representation quality. We visualize the performance of MoCo-CXR-pretrained and ImageNet-pretrained linear models at various label fractions in Figure~\ref{fig:cx_all_last} and tabulate the corresponding AUC improvements in Table~\ref{tbl:cx_comp}. Trained on small label fractions, the ResNet18 MoCo-CXR-pretrained linear model demonstrated statistically significant performance gains over its ImageNet counterpart. With 0.1\% label fraction, the improvement in performance is 0.096 (95\% CI 0.061, 0.130) AUC; the MoCo-CXR-pretrained and ImageNet-pretrained linear models achieved performances of 0.776 and 0.683 AUC respectively. These findings support the hypothesis that MoCo-representations are of superior quality, and are most apparent when labeled data is scarce. With larger label fractions, the MoCo-CXR-pretrained linear models demonstrated clear yet diminishing improvements over the ImageNet-pretrained linear models. Training with 100\% of the labeled data, the ResNet18 MoCo-CXR-pretrained linear model yielded a performance gain of 0.034 (95\% CI -0.009, 0.080). Both backbones were observed to have monotonically decreasing performance gains with MoCo as we increase the amount of labeled training data. These results provide evidence that MoCo-CXR-pretrained representations retain their quality at all label fractions, but less significantly at larger label fractions. We generally observe similar performance gains with MoCo-CXR on the CheXpert competition pathologies, as seen in Appendix Table~\ref{tbl:all_chexpert_last}. \subsection{Transfer performance of end-to-end MoCo-CXR-pretrained models on CheXpert}\label{sec:cx_full} We investigated whether MoCo-CXR-pretraining translates to higher performance for models fine-tuned end-to-end. We visualize the performance of the MoCo and ImageNet-pretrained end-to-end models at different label fractions in Figure~\ref{fig:cx_all_full}. AUC improvements of using a MoCo-CXR-pretrained linear model over an ImageNet-pretrained linear is tabulated in Table~\ref{tbl:cx_comp} We found that MoCo-CXR-pretrained end-to-end models outperform their ImageNet-pretrained counterparts more at small label fractions than at larger label fractions. With the 0.1\% label fraction, the ResNet18 MoCo-CXR-pretrained end-to-end model achieved an AUC of 0.813 while the ImageNet-pretrained end-to-end model achieves an AUC of 0.775, yielding a statistically significant AUC improvement of 0.037 (95\% CI 0.015, 0.062). The AUC improvement with the 1.0\% label fraction was also statistically significant at 0.027 (95\% CI 0.006, 0.047). Both pretraining approaches converge to an AUC of 0.942 with the 100\% label fraction. These results demonstrate that MoCo-CXR-pretraining yields performance boosts for end-to-end training, and further substantiate the quality of the pretrained initialization, especially for smaller label fractions. This finding is consistent with behavior of SimCLR \citep{chen2020simple}, which also saw larger performance gains for self-supervised models trained end-to-end on smaller label fractions of ImageNet. We generally observe similar performance gains with MoCo-CXR end-to-end on the CheXpert competition pathologies, as seen in Appendix Table~\ref{tbl:all_chexpert_full}. \begin{figure}[t] \centering \includegraphics[width=0.55\linewidth]{images/cx_all_full_ci.PNG} \caption{AUC on pleural effusion task for models fine-tuned end-to-end with MoCo-CXR-pretraining is consistently higher than those without MoCo-CXR-pretraining, showing that MoCo-CXR-pretraining representations are more transferable than those produced by ImageNet-pretraining only.} \label{fig:cx_all_full} \end{figure} \begin{table}[t] \centering \scalebox{0.6}{ \begin{tabular}{lllcccc} \toprule \textbf{Architecture} & \textbf{MoCo-CXR-pretrained} & \textbf{ImageNet-pretrained} & \textbf{0.1\%} & \textbf{1.0\%} & \textbf{10.0\%} & \textbf{100\%} \\ \midrule ResNet18 & End-to-End & End-to-End & \text{0.037(\ 0.015, 0.062)} & \text{\ 0.027(\ 0.006, \ 0.047)} & \text{\ 0.017(\ 0.003, \ 0.031)} & \text{\ 0.000(-0.009, \ 0.009)} \\ ResNet18 & Linear Model & Linear Model & \text{0.096(\ 0.061, 0.130)} & \text{\ 0.070(\ 0.029, \ 0.112)} & \text{\ 0.049(\ 0.005, \ 0.094)} & \text{\ 0.034(-0.009, \ 0.080)} \\ ResNet18 & Linear Model & End-to-End & \text{0.001(-0.024, 0.025)} & \text{-0.022(-0.051, \ 0.009)} & \text{-0.050(-0.083, -0.018)} & \text{-0.094(-0.127, -0.062)} \\ \midrule DenseNet121 & End-to-End & End-to-End & \text{0.048(\ 0.023, 0.074)} & \text{\ 0.019(\ 0.001, \ 0.037)} & \text{\ 0.012(\ 0.000, \ 0.023)} & \text{\ 0.003(-0.006, \ 0.013)} \\ DenseNet121 & Linear Model & Linear Model & \text{0.107(\ 0.075, 0.142)} & \text{\ 0.078(\ 0.035, \ 0.121)} & \text{\ 0.067(\ 0.023, \ 0.111)} & \text{\ 0.055(\ 0.008, \ 0.102)} \\ DenseNet121 & Linear Model & End-to-End & \text{0.029(\ 0.002, 0.055)} & \text{-0.024(-0.050, -0.003)} & \text{-0.070(-0.109, -0.036)} & \text{-0.107(-0.141, -0.073)} \\ \bottomrule \end{tabular} } \caption{AUC improvements on pleural effusion task achieved by MoCo-CXR-pretrained models against models without MoCo-CXR-pretraining on the CheXpert dataset.} \label{tbl:cx_comp} \end{table} \begin{figure}[t] \centering \begin{minipage}[t]{1.0\textwidth} \begin{minipage}[b]{0.62\textwidth} \centering \includegraphics[width=0.75\linewidth]{images/sz_compare_all_ci.PNG} \captionof{figure}{AUC on the Shenzhen tuberculosis task for models with and without MoCo-CXR-pretraining shows that MoCo pretraining still introduces significant improvement despite being fine-tuned on an external dataset.}\label{fig:sz_comapre_all} \end{minipage} \hfill \begin{minipage}[b]{0.35\textwidth} \centering \scalebox{0.7}{ \begin{tabular}{c l} \toprule \multicolumn{1}{c}{\textbf{Learning Rate}} & \multicolumn{1}{c}{\textbf{AUC}} \\ \midrule $10^{-2}$ & 0.786 (0.699, 0.861) \\ \hline $10^{-3}$ & 0.908 (0.853, 0.955) \\ \hline $10^{-4}$ & 0.944 (0.907, 0.972) \\ \hline $10^{-5}$ & 0.939 (0.891, 0.975) \\ \bottomrule \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \end{tabular} } \captionof{table}{AUC of MoCo pretrained ResNet18 on Shenzhen dataset at different pretraining learning rates with $100\%$ label fraction.}\label{tab:sz_lr} \end{minipage} \end{minipage} \end{figure} \subsection{Transfer benefit of MoCo-CXR-pretraining on an external dataset} \label{sec:sz} We conducted experiments to test whether MoCo-CXR-pretrained chest X-ray representations acquired from a source dataset (CheXpert) transfer to a small target dataset (Shenzhen Dataset for Tuberculosis, with 662 X-rays). Results of these experiments are presented in Figure~\ref{fig:sz_comapre_all}. We first examined whether MoCo-CXR-pretrained linear models improve AUC on the external Shenzhen dataset. With 6.25\% label fraction, which is approximately 25 images, the ResNet18 MoCo-CXR-pretrained model outperformed the ImageNet-pretrained one by 0.054 (95\%, CI 0.024, 0.086). AUC improvement with the 100\% label fraction was 0.018 (95\% CI -0.011, 0.053). This is similar to the trend observed on the CheXpert dataset discussed previously. These observations suggest that representations learned from MoCo-CXR-pretraining are better suited for an external target chest X-ray dataset with a different task than representations learned from ImageNet-pretraining. Next, we tested whether MoCo-CXR-pretrained models with end-to-end training also perform well on the external Shenzhen dataset. With the 100\% label fraction, the ResNet18 MoCo-CXR-pretrained model was able to achieve an AUC of 0.974. However, the corresponding AUC improvement of only 0.003 (95\% CI -0.014, 0.020) is much less than the improvement observed for linear models. Since the Shenzhen dataset is limited in size, it is possible that training end-to-end quickly saturates learning potential at low label fractions. Regardless, the non-zero improvement still suggests that MoCo-CXR-pretrained initializations can transfer to an external dataset. This echoes previous investigations of self-supervised and unsupervised learnings, which found that unsupervised pretraining pushes the model towards solutions with better generalization to tasks that are in the same domain \citep{sun2019unsupervised, erhan2010unsupervised}. \section{Conclusion}\label{sec:disc_moco} We found that our MoCo-CXR method provides high-quality representations and transferable initializations for chest X-ray interpretation. Despite many differences in the data and task properties between natural image classification and chest X-ray interpretation, MoCo-CXR was a successful adaptation of MoCo pretraining to chest X-rays. These suggest the possibility for broad application of self-supervised approaches beyond natural image classification settings. To the best of our knowledge, this work is the first to show the benefit of MoCo-pretraining across label fractions for chest X-ray interpretation, and also investigate representation transfer to a target dataset. All of our experiments are run on a single NVIDIA GTX 1070, demonstrating accessibility of this method. Our success in demonstrating improvements in model performance over the traditional supervised learning approach, especially on low label fractions, may be broadly extensible to other medical imaging tasks and modalities, where high-quality labeled data is expensive, but unlabeled data is increasingly easier to access.
{'timestamp': '2021-05-19T02:04:02', 'yymm': '2010', 'arxiv_id': '2010.05352', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05352'}
arxiv
\section{#1}\vspace{-4pt}} \newcommand{\msubsection}[1]{\vspace*{-5pt}\subsection{#1}\vspace{-4pt}} \definecolor{light-gray}{gray}{0.80} \newcommand{\mcol}[2]{\multicolumn{#1}{r}{#2}} \newcommand{\mrow}[2]{\multirow{#1}{*}{#2}} \newcommand{\mrowrot}[2]{ \parbox[t]{2mm}{\multirow{#1}{*}{\rotatebox[origin=c]{90}{#2}}} } \newcommand{\algcolor}[2]{\colorbox{#1}{\parbox{\linewidth}{#2}}} \newcommand{\algemph}[1]{\algcolor{light-gray}{#1}} \newcommand{\algcmt}[1]{\hfill {\footnotesize\ttfamily\textcolor{blue}{/* {#1} */}}} \newcommand{\algcc}[1]{\hfill {\footnotesize\ttfamily\textcolor{blue}{//{#1}}}} \newcommand{\bfeval}[1]{ \textcolor{black}{\textbf{\eval{#1}}} } \newcommand\aref{Algorithm~\ref} \newcommand\appref{Appendix~\ref} \newcommand\eref{Eq.~\ref} \newcommand\fref{Figure~\ref} \newcommand\tref{Table~\ref} \newcommand\sref{Section~\ref} \newcommand\cmt[1]{\tcp*[r]{\scriptsize \color{gray!80!black}#1}} \newcommand{\red}[1]{{\color{red} #1}} \newcommand{\blue}[1]{{\color{blue} #1}} \newcommand{\bluem}[1]{{\bf\color{blue} #1}} \newcommand\ha{ \rowcolor{orange!0}} \newcommand\hb{ \rowcolor{orange!15}} \newcommand\hc{ \rowcolor{orange!40}} \newcommand\hd{ \rowcolor{orange!45}} \newcommand\he{ \rowcolor{orange!60}} \newcommand\hf{ \rowcolor{orange!75}} \newcommand\hg{ \rowcolor{orange!90}} \newcommand\ga{ \rowcolor{gray!0}} \newcommand\gb{ \rowcolor{gray!15}} \newcommand\gc{ \rowcolor{gray!40}} \newcommand\gd{ \rowcolor{gray!45}} \newcommand\MS{{\mathcal{M}}} \def{\bf x}{{\bf x}} \def{\bf H}{{\bf H}} \def{\bf g}{{\bf g}} \def{\bf Hg}{{\bf Hg}} \def{\bf 0}{{\bf 0}} \def{\bf s}{{\bf s}} \def{\bf t}{{\bf t}} \def{\bf p}{{\bf p}} \def{\bm{v}}{{\bf v}} \def\mathbb{R}{{\mathbb R}} \def{\mathcal{A}}{{\mathcal{A}}} \def{\mathbb{V}}{{\mathbb{V}}} \let\proof\relax \let\endproof\relax \usepackage{amsthm} \let\lemma\relax \let\assumption\relax \let\remk\relax \let\theorem\relax \usepackage{amsthm} \newtheorem{mytheorem}{Theorem} \newtheorem{assumption}[mytheorem]{Assumption} \newtheorem{lemma}[mytheorem]{Lemma} \newtheorem{remk}[mytheorem]{Remark} \newcommand{\es}[1]{{\color{red} #1}} \newcommand{\xspace\tiny{MP}}{\xspace\tiny{MP}} \newcommand{\xspace{MixSolver}}{\xspace{MixSolver}} \section*{Acknowledgments} We thank reviewers and the area chair for their helpful suggestions. We are grateful for a gracious fund from the Amazon AWS. MWM would also like to acknowledge DARPA, NSF, and ONR for providing partial support of this work. HT is supported by Bloomberg Data Science Ph.D. Fellowship. The views, opinions, and/or findings contained in this article are those of the authors and should not be interpreted as representing the official views or policies, either expressed or implied, of the funding agency. \bibliographystyle{acl_natbib} \section{Introduction} \label{sec:intro} Language grounding involves mapping language to real objects or data. Among language grounding tasks, phrase localization---which maps phrases to regions of an image---is a fundamental building block for other tasks. In the \emph{phrase localization task}, each data point consists of one image and its corresponding caption, i.e., $d = \left\langle I,S\right \rangle$, where $I$ denotes an image and $S$ denotes a caption. Typically, the caption $S$ contains several query phrases $\mathcal{P}= \left\{p_n \right\}^{N}_{n=1}$, where each phrase is grounded to a particular object in the image. The goal is to find the correct relationship between (query) phrases in the caption and particular objects in the image. Existing work~\cite{DBLP:journals/corr/RohrbachRHDS15, Kim2018BilinearAN, li2019visualbert, yu2018rethining, liu2019learning} mainly focuses on the supervised phrase localization setting. This requires a large-scale annotated dataset of phrase-object pairs for model training. However, given difficulties associated with manual annotation of objects, the size of grounding datasets is often limited. For example, the widely-adopted Flickr30k~\cite{10.1007/s11263-016-0965-7} dataset has 31k images, while the caption dataset MS COCO~\cite{lin2014microsoft} contains 330k images. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{paper_fig_sup_baby.png} \caption{Comparison of phrase localization task under supervision (left) and weak supervision (right). } \label{fig:sup_task} \vspace{-10pt} \end{figure} To address this limited data challenge, two different approaches have been proposed. First, a weakly-supervised setting---which requires only \emph{caption-image annotations}, i.e., no \emph{phrase-object annotations}---was proposed by~\citet{DBLP:journals/corr/RohrbachRHDS15}. This is illustrated in Figure~\ref{fig:sup_task}. Second, an unsupervised setting---which does not need any training data, i.e., neither caption-image and phrase-object annotation---was proposed by~\citet{wang2019phrase}. To bring more semantic information in such a setting, previous work~\cite{yeh2018unsupervised, wang2019phrase} used the detected object labels from an off-the-shelf object detector (which we will generically denote by PreDet) and achieved promising results. In more detail, for a given image $I$, the PreDet first generates a set of objects $\mathcal{O} = \left\{ o_m \right\}^{M}_{m=1}$. Afterward, all the query phrases $\mathcal{P}$ and the detected objects $\mathcal{O}$ are fed into an alignment model to predict the final phrase-object pairs. However, purely relying on the object labels causes ambiguity. For example, in Figure~\ref{feature}, the grounded objects of phrases ``an older man'' and ``the man with a red accordion'' are both labeled as ``man,'' and thus they are hard to differentiate. \begin{figure}[t] \centering \includegraphics[width=.96\linewidth]{man_fig_2-compressed_large.pdf} \caption{ Example of the ambiguity caused by label-based localization (top); and our fine-grained visual representation disambiguate labels (bottom).} \label{feature} \vspace{-10pt} \end{figure} \begin{figure*}[!htb] \centering \includegraphics[width=.96\linewidth]{paper_fig_model_fig_new.png} \caption{ Overview of our proposed Multimodal Alignment Framework (MAF). A dataset of images and their captions is the input to our model. PreDet predicts bounding boxes for objects in the image and their labels, attributes, and features, which are then integrated into visual feature representations. Attention is applied between word embedding and visual representations to compute the visually-aware language representations for phrases. Finally, a multi-modal similarity function is used to measure the caption-image relevance based on the phrase-object similarity~matrix. } \label{model} \vspace{-5pt} \end{figure*} Given these observations, we propose a Multimodal Alignment Framework (MAF), which is illustrated in Figure~\ref{model}. Instead of using only the label features from the PreDet (in our case, a Faster R-CNN~\cite{ren2015faster,anderson2018bottom}), we also enhance the visual representations by integrating visual features from the Faster R-CNN into object labels. (This is shown in Figure~\ref{feature}.) Next, we build visually-aware language representations for phrases, which thus could be better aligned with the visual representations. Based on these representations, we develop a multimodal similarity function to measure the caption-image relevance with phrase-object matching scores. Furthermore, we use a training objective to score relevant caption-image pairs higher than irrelevant caption-image pairs, which guides the alignment between visual and textual representations. We evaluate MAF on the public phrase localization dataset, Flickr30k Entities~\cite{10.1007/s11263-016-0965-7}. Under the weakly-supervised setting (i.e., using only caption-image annotations without the more detailed phrase-object annotations), our method achieves an accuracy of 61.43\%, outperforming the previous weakly-supervised results by 22.72\%. In addition, in the unsupervised setting, our visually-aware phrase representation improves the performance from the previous 50.49\% by 5.56\% up to 56.05\%. Finally, we validate the effectiveness of model components, learning methods, and training techniques by showing their contributions to our final results. \section{Related Work} With the recent advancement in research in computer vision and computational linguistics, multimodal learning, which aims to explore the explicit relationship across vision and language, has drawn significant attention. Multimodal learning involves diverse tasks such as Captioning~\cite{vinyals2015show,xu2015show, karpathy2015deep, venugopalan2015sequence}, Visual Question Answering~\cite{anderson2018bottom, Kim2018BilinearAN, tan2019lxmert}, and Vision-and-Language Navigation~\cite{anderson2018vision, chen2019touchdown, thomason2020vision}. Most of these tasks would benefit from better phrase-to-object localization, a task which attempts to learn a mapping between phrases in the caption and objects in the image by measuring their similarity. Existing works consider the phrase-to-object localization problem under various training scenarios, including supervised learning~\cite{DBLP:journals/corr/RohrbachRHDS15, yu2018rethining, liu2019learning, 10.1007/s11263-016-0965-7, li2019visualbert} and weakly-supervised learning~\cite{DBLP:journals/corr/RohrbachRHDS15, yeh2018unsupervised, chen2018knowledge}. Besides the standard phrase-object matching setup, previous works~\cite{DBLP:journals/corr/XiaoSL17, akbari2019multi, datta2019align2ground} have also explored a pixel-level ``pointing-game'' setting, which is easier to model and evaluate but less realistic. Unsupervised learning was studied by~\citet{wang2019phrase}, who directly use word similarities between object labels and query phrases to tackle phrase localization without paired examples. Similar to the phrase-localization task, \citet{hessel2019unsupervised} leverages document-level supervision to discover image-sentence relationships over the~web. \section{Methodology} \subsection{Fine-grained Visual/Textual Features} \paragraph{Visual Feature Representations.} Previous works usually use only one specific output of the PreDet as the \emph{visual feature representation} (VFR). For example, \citet{Kim2018BilinearAN} uses the final output feature of PreDet (denoted as $\boldsymbol{f_m}$) as the VFR, and \citet{wang2019phrase} uses the label embedding (denoted as $\boldsymbol{l_m}$) of the predicted label from PreDet as the VFR. This unitary VFR usually lacks the counter-side information. Hence, we exploit different aspects of features extracted from PreDet for each object $o_m$ in the image. In particular, we consider the output feature $\boldsymbol{f_m}$, the label embedding $\boldsymbol{l_m}$, and the attribute embedding $\boldsymbol{t_m}$ of the object $o_m$ as the VFR, \begin{equation} \boldsymbol{v_m} = \boldsymbol{l_m} + W_t \boldsymbol{t_m} + W_f \boldsymbol{f_m}, \\ \end{equation} where $W_t$ and $W_f$ are two projection matrices. Naively initializing $W_t$ and $W_f$ will lead the model to a sub-optimal solution. In Section~\ref{sec:empirical_results}, we discuss the effectiveness of different initializations. \paragraph{Textual Feature Representations.} \label{paragraph:tfr} Existing works for \emph{textual feature representation} (TFR)~\cite{Kim2018BilinearAN, yu2018rethining, wang2019phrase} commonly treat it independently of the VFR. From a different angle, we use the attention between the textual feature and the VFR $\boldsymbol{v}_m$ to integrate the visual information from the object into TFR. In more detail, we first use the GloVe embedding~\cite{pennington2014glove} to encode the $K_n$ words in the phrase $p_n$ to $\left\{\boldsymbol{h}_{n,k}\right\}^{K_n}_{k=1}$, where$~\boldsymbol{h}_{n,k}\in \mathbb{R}^d$. Here, the dimension of $\boldsymbol{h}_{n,k}$ is the same as $\boldsymbol{v_m}$. We then define a word-object matching score $a_{n,k}^m$ for each $\boldsymbol{h_{n,k}}$ in the phrase to all object features $\boldsymbol{v_m}$. In particular, for each word $\boldsymbol{h}_{n,k}$ in the phrase, we select the object with the highest matching score, \begin{equation} \begin{aligned} &\boldsymbol{a}_{n,k}^m = \mathrm{soft}\max_m \left\{\frac{\boldsymbol{h}_{n,k}^T\boldsymbol{v}_m}{{\sqrt{d}}}\right\},\\ &\alpha_{n,k} = \max_{m} \{\boldsymbol{a}_{n,k}^m\}. \end{aligned} \end{equation} Finally, we normalize the attention weights for each word in the phrase $p_n$ to obtain the final TFR, $\boldsymbol{e_n}$: \begin{equation} \begin{aligned} \beta_{n,k} &= \mathrm{soft}\max_k \left\{\alpha_{n,k}\right\},\\ \boldsymbol{e_n} &= W_p\left(\sum_k\beta_{n,k}\boldsymbol{h}_{n,k}\right). \end{aligned} \end{equation} where $W_p$ is a projection matrix. In Section~\ref{sec:empirical_results}, we study the (superb) performance of the weight $\beta_{n,k}$ over simply the average $\boldsymbol{h}_{n,k}$ as well as the importance of the initialization of $W_p$. \subsection{Training Objective and Learning Settings} \label{sec:loss_setting} \paragraph{Contrastive loss.} For the weakly-supervised setting, we use a contrastive loss to train our model, due to the lack of phrase-object annotations. The contrastive objective $\mathcal{L}$ aims to learn the visual and textual features by maximizing the similarity score between paired image-caption elements and minimizing the score between the negative samples (i.e., other irrelevant images). Inspired by the previous work in caption ranking~\cite{fang2015captions}, we use the following loss, \begin{equation} \mathcal{L} = -\log \frac{e^{\text{sim}(I, S)}}{\sum_{I^{'} \in \mathit{batch}}{e^{\text{sim}(I^{'}, S)}}} . \end{equation} Here, $\text{sim}(I, S)$ is the similarity function defined below. Particularly, for each caption sentence, we use all the images $I^{'}$ in the current batch as candidate examples. \paragraph{Multimodal Similarity Functions.} Following the document-level dense correspondence function in~\citet{hessel2019unsupervised}, our multimodal similarity function is defined as: \begin{equation} \begin{aligned} \mathrm{sim}(I,S) = \frac{1}{N}\sum_{n}{\max_{m}{A_{n,m}}}. \end{aligned} \end{equation} Here, $A \in \mathbb{R}^{N\times M}$ is the phrase-object similarity matrix, and its component is computed as \begin{equation} A_{n,m} = \boldsymbol{e}_n^T \boldsymbol{v}_m, \end{equation} and $\mathrm{sim}(I,S)$ measures the image-caption similarity. It is calculated based on the similarity score between each phrase in the caption and each object in the image. Note that the maximum function $\max_{m}{A_{n,m}}$ directly connects our training objective and inference target, which alleviates the discrepancy between training and inference. \paragraph{Weakly-supervised setting.} During training, our PreDet model is frozen. The word embeddings, $W_t$, $W_f$, and $W_p$ are trainable parameters. Here, the word embedding is initialized with GloVe~\cite{pennington2014glove}. We study the different initialization methods for the rest in Section~\ref{sec:empirical_results}. During inference, for the $n$-th phrase $p_n$ in an image-caption pair, we choose the localized object by \begin{equation} m_{n}^\text{pred} = \arg\max_{m}{A_{n,m}} = \arg\max_{m}{\boldsymbol{e}_n^T\boldsymbol{v}_{m}}. \end{equation} \paragraph{Unsupervised setting.} \label{sec:unsup_setting} In the unsupervised setting, the localized object is determined by \begin{equation} m_{n}^\text{pred} = \arg\max_m {\left(\sum_k\beta_{n,k}\boldsymbol{h}_{n,k}^{T}\right)\boldsymbol{l}_m}. \end{equation} We drop the parameters $W_t$, $W_f$, and $W_p$ here, because there is no training in the unsupervised setting. $\beta_{n,k}$ is only calculated based on $\boldsymbol{l}_m$ (instead of $\boldsymbol{v}_m$). \section{Empirical Results } \label{sec:empirical_results} \paragraph{Dataset details.} \label{sec:dataset_details} The Flickr30k Entities dataset contains 224k phrases and 31k images in total, where each image will be associated with 5 captions and multiple localized bounding boxes. We use 30k images from the training set for training and 1k images for validation. The test set consists of 1k images with 14,481 phrases. Our evaluation metric is the same as~\citet{10.1007/s11263-016-0965-7}.\footnote{To be specific, we use the evaluation code provided by~\newcite{wang2019phrase} at \url{https://github.com/josiahwang/phraseloceval}.} We consider a prediction to be correct if the IoU (Intersection of Union) score between our predicted bounding box and the ground-truth box is larger than 0.5. Following~\citet{DBLP:journals/corr/RohrbachRHDS15}, if there are multiple ground-truth boxes, we use their union regions as a single ground-truth bounding box for~evaluation. \paragraph{Weakly-supervised Results.} We report our weakly-supervised results on the test split in Table~\ref{tab:result_weaklysuper}. We include here upper bounds (UB), which are determined by the correct objects detected by the object detectors (if available). Our MAF with ResNet-101-based Faster R-CNN detector pretrained on Visual Genome (VG)~\cite{krishnavisualgenome} can achieve an accuracy of 61.43\%. This outperforms previous weakly-supervised methods by 22.71\%, and it narrows the gap between weakly-supervised and supervised methods to 15\%. We also implement MAF with a VGG-based Faster R-CNN feature extractor pretrained on PASCAL VOC 2007~\cite{everingham2010pascal}, following the setting in KAC~\cite{chen2018knowledge}, and we use the same bounding box proposals as our ResNet-based detector. We achieve an accuracy of 44.39\%, which is 5.68\% higher than existing methods, showing a solid improvement under the same backbone~model. { \begin{table}[!htb] \caption{ Weakly-supervised experiment results on Flick30k Entities. (We abbreviate backbone visual feature model as ``Vis. Feature,'' and upper bound as~``UB.'') } \label{tab:result_weaklysuper} \begin{adjustbox}{width=.5\textwidth,center} \centering \begin{tabular}{lccc} \toprule Method & Vis. Features& Acc. (\%) & UB\\ \midrule \multicolumn{3}{l}{\textbf{Supervised}} \\ GroundeR \cite{DBLP:journals/corr/RohrbachRHDS15} & VGG$_\text{det}$ & 47.81& 77.90\\ CCA~\cite{10.1007/s11263-016-0965-7} & VGG$_\text{det}$ & 50.89 & 85.12\\ BAN \cite{Kim2018BilinearAN} & ResNet-101 & 69.69 & 87.45\\ visualBERT \cite{li2019visualbert} & ResNet-101 &71.33& 87.45\\ DDPN~\cite{yu2018rethining} & ResNet-101&73.30& - \\ CGN~\cite{liu2019learning} &ResNet-101&76.74& - \\ \midrule \multicolumn{3}{l}{\textbf{Weakly-Supervised}}\\ GroundeR \cite{DBLP:journals/corr/RohrbachRHDS15} & VGG$_\text{det}$&28.93&77.90\\ Link~\cite{yeh2018unsupervised} & YOLO$_\text{det}$ & 36.93& - \\ KAC \cite{chen2018knowledge} & VGG$_\text{det}$ &38.71& - \\ \midrule \hb MAF (Ours) & VGG$_\text{det}$ & 44.39 & 86.29 \\ \hc MAF (Ours) & ResNet-101 & \textbf{61.43} & 86.29\\ \bottomrule \end{tabular} \end{adjustbox} \vspace{-10pt} \end{table} } \paragraph{Unsupervised Results.\footnote{More unsupervised results are available in Appendix~\ref{appendix:baseline}.}} We report our unsupervised results for the phrase localization method (described in Section~\ref{sec:unsup_setting}) in Table~\ref{tab:result_unsupervised}. For a fair comparison, we re-implemented~\citet{wang2019phrase} with a Faster R-CNN model trained on Visual Genome~\cite{krishnavisualgenome}. This achieves 49.72\% accuracy (similar to 50.49\% as reported in their paper). Overall, our result (with VG detector) significantly outperforms the previous best result by 5.56\%, which demonstrates the effectiveness of our visually-aware language representations. { \begin{table}[!htb] \large \caption{ Unsupervised experiment results on Flick30k Entities. w2v-max refers to the similarity algorithm proposed in~\cite{wang2019phrase}; Glove-att refers to our unsupervised inference strategy in Section~\ref{sec:loss_setting}; CC, OI, and PL stand for detectors trained on MS COCO~\cite{lin2014microsoft}, Open Image~\cite{krasin2017openimages}, and Places~\cite{zhou2017places}. } \label{tab:result_unsupervised} \begin{adjustbox}{width=.5\textwidth,center} \begin{tabular}{lccc} \toprule Method& TFR &Detector & Acc. (UB) (\%)\\ \midrule Whole Image & None & None & 21.99 \\ \cite{wang2019phrase} & w2v-max & Faster R-CNN & 49.72 (86.29)\\ \cite{wang2019phrase} & w2v-max & CC+OI+PL & 50.49 (57.81)\\ \midrule \hc MAF (Ours) & Glove-att & Faster R-CNN & 56.05 (86.29)\\ \bottomrule \end{tabular} \end{adjustbox} \vspace{-10pt} \end{table} } \paragraph{Ablation Experiments.} In this section, we study the effectiveness of each component and learning strategy in MAF. The comparison of different feature representations is shown in Table~\ref{tab:ablation_representation}. Replacing the visual attention based TFR with an average pooling based one decreases the result from 61.43\% to lower than 60\%. For the VFR, using only object label $\boldsymbol{l}_m$ or visual feature $\boldsymbol{f}_m$ decreases the accuracy by 4.20\% and 2.94\%% , respectively. One interesting finding here is that the performance with all visual features (last row) is worse than the model with only $\boldsymbol{l}_m$ and $\boldsymbol{f}_m$. Actually, we can infer that attributes cannot provide much information in localization (24.08\% accuracy if used alone), partly because attributes are not frequently used to differentiate objects in Flickr30k captions. \begin{table}[!htb] \small \caption{ Ablation experiment results of different visual and textual features. TFR and VFR denotes textual and visual feature representation respectively. } \label{tab:ablation_representation} \centering \begin{adjustbox}{width=0.44\textwidth} \begin{tabular}[t]{lcccccccccccccccccc} \toprule \multirow{2}{*}{TFR} & \multicolumn{3}{c}{VFR} & \multirow{2}{*}{Accuracy(\%)}\\ \cmidrule{2-4} & $l_m$ & $f_m$ & $t_m$ & \\ \midrule Average & \xm & & & 55.73 \\ Average & & \xm & & 56.18\\ Average & \xm &\xm & & 59.51 \\ \midrule Attention & \xm & & &57.23 \\ Attention & &\xm & & 58.49 \\ Attention & & &\xm & 24.08 \\ Attention & \xm & &\xm & 53.20 \\ Attention & & \xm & \xm & 57.98 \\ \hc Attention & \xm &\xm & & 61.43 \\ Attention & \xm &\xm &\xm & 60.86 \\ \bottomrule \end{tabular} \end{adjustbox} \vspace{-5pt} \end{table} \begin{table}[!htb] \caption{ Ablation results of different initialization. (ZR: zero initialization; RD: random initialization; ID+RD: noisy identity initialization.) } \small \label{tab:ablation_init} \centering \begin{adjustbox}{width=0.44\textwidth} \begin{tabular}[t]{cc|ccccccccccccccccccccccccccc} \toprule \multicolumn{2}{c}{$W_f$} & \multicolumn{2}{c}{$W_p$} &\multirow{2}{*}{Accuracy $\pm$ Var.(\%)}\\ \cmidrule{1-4} ZR & RD & ID+RD & RD & \\ \midrule & \xm & & \xm & 58.54 $\pm$ 0.26\\ \midrule \xm & && \xm& 60.05 $\pm$ 0.31\\ &\xm &\xm& & 59.68 $\pm$ 0.35\\ \midrule \hc \xm& &\xm& & 61.28 $\pm$ 0.32\\ \bottomrule \end{tabular} \end{adjustbox} \vspace{-5pt} \end{table} We then investigate the effects of different initialization methods for the two weight matrices, $W_f$ and $W_p$. The results are presented in Table~\ref{tab:ablation_init}. Here ZR means zero initialization, RD means random initialization with Xavier~\cite{glorot2010understanding}, and ID+RD means identity with small random noise initialization. We run each experiment for five times with different random seeds and compute the variance. According to Table~\ref{tab:ablation_init}, the best combination is zero initialization for $W_f$ and identity+random initialization for $W_p$. The intuitions here are: (i) For $W_f$, the original label feature $\boldsymbol{l}_m$ can have a non-trivial accuracy 57.23\% (see Table~\ref{tab:ablation_representation}), thus using RD on initializing $W_f$ will disturb the feature from $\boldsymbol{l}_m$; (ii) For $W_p$, an RD initialization will disrupt the information from the attention mechanism, while ID+RD can both ensure basic text/visual feature matching and introduce a small random noise for training. \section{Qualitative Analysis} \section{Conclusions} \label{sec:conclusions} We present a Multimodal Alignment Framework, a novel method with fine-grained visual and textual representations for phrase localization, and we train it under a weakly-supervised setting, using a contrastive objective to guide the alignment between visual and textual representations. We evaluate our model on Flickr30k Entities and achieve substantial improvements over the previous state-of-the-art methods with both weakly-supervised and unsupervised training strategies. Detailed analysis is also provided to help future works investigate other critical feature enrichment and alignment methods for this task. \section{Implementation Details} \label{appendix:Impl} For GloVE word embeddings, we use the one with the hidden dimension 300. Phrases are split into words by space. We replace all out-of-vocabulary words with the introduced $\left\langle \text{UNK} \right\rangle$ token. For object proposals, we apply an off-the-shelf Faster R-CNN model~\cite{ren2015faster} as the object detector\footnote{\small https://github.com/jwyang/faster-rcnn.pytorch} for object pseudo-labels. The backbone of the detector is ResNet-101~\cite{he2016deep}, and it is pre-trained on Visual Genome with mAP=10.1. We keep all bounding boxes with a confidence score larger than 0.1. For ResNet-based visual features, we use the 2048-dimensional feature from Bottom-up attention \cite{anderson2018bottom}, which is pre-trained with 1600 object labels and 400 attributes. The extracted visual features are frozen during training, and we use a batch size of 64 during training. Our optimizer is Adam with learning rate $lr = 1e^{-5}$. Except for word embeddings, trainable parameters include $W_t \in \mathbb{R}^{d_T \times d_T}$, $W_f \in \mathbb{R}^{d_V \times d_T}$, and $W_p \in \mathbb{R}^{d_T \times d_T}$, where $d_T=300$, $d_V=2048$ for ResNet-101 backbone and $d_V=4096$ for VGG backbone. During training, it takes around 350 seconds to train an epoch using a single Tesla K80. We train our model for 25 epochs and report the results at the last epoch. \section{Baselines} \label{appendix:baseline} In Table~\ref{tab:result_baselines}, we report the results of different unsupervised methods: \begin{itemize} \item Random: Randomly localize to a detected object. \item Center-obj: Localize to the object which is closest to the center of image, where we use an $L_1$ distance $D = |x-x_{\text{center}}| + |y-y_{\text{center}}|$. \item Max-obj: Localize to the object with the maximal area. \item Whole Image: Always localize to the whole image. \item Direct Match: Localize with the direct match between object labels and words in the phrase, e.g., localize ``a red apple'' to the object with the label ``apple.'' If multiple labels are matched, we choose the one with the largest bounding~box. \item Glove-max: Consider every word-label similarity independently and select the object label with the highest semantic similarity with any~word. \item Glove-avg: Represent a phrase using an average pooling over Glove word embeddings and select the object label with highest the semantic similarity with the phrase representation. \item Glove-att: Use our visual attention based phrase representation, as is described in the Methodology~\ref{paragraph:tfr}. \end{itemize} Note that in all label-based methods (Direct Match \cite{wang2019phrase}, and our unsupervised method), if multiple bounding boxes share the same label, we choose the largest one as the predicted box. { \begin{table}[!htb] \caption{ Baseline results of unsupervised methods on Flick30k Entities. Abbreviations are explained above. } \small \label{tab:result_baselines} \begin{adjustbox}{width=.45\textwidth,center} \begin{tabular}{lccc} \toprule Method & Detector & Acc. (\%)\\ \midrule Random & Faster R-CNN & 7.19\\ Center-obj &Faster R-CNN& 18.24\\ Whole Image &None & 21.99 \\ Max-obj &Faster R-CNN& 24.51\\ Direct match &Faster R-CNN & 26.42\\ \midrule Glove-max & Faster R-CNN & 26.28\\ Glove-avg & Faster R-CNN& 54.51\\ Glove-att & Faster R-CNN & 56.05 \\ \bottomrule \end{tabular} \end{adjustbox} \end{table} } \section{Qualitative Analysis} \label{appendix:analysis} \begin{figure}[!bth] \centering \includegraphics[scale = 0.32]{pic_example-02.png} \caption{Example of predictions on Flickr30k. (Red box: ground truth, blue box: our prediction).} \label{fig:example1} \end{figure} \begin{figure}[!bth] \centering \hspace{5pt} \includegraphics[scale = 0.34]{pic_example-03.png} \caption{Example of predictions on Flickr30k. (Red box: ground truth, blue box: supervised prediction, yellow box: unsupervised prediction)} \label{fig:example2} \vspace{-5pt} \end{figure} To analyze our model qualitatively, we show some visualization results in Figure~\ref{fig:example1} and Figure~\ref{fig:example2}. Figure~\ref{fig:example1} shows examples with consistent predictions between supervised and unsupervised models. In these cases, both methods can successfully learn to localize various objects, including persons (``mother''), clothes (``shirt''), landscapes (``wave''), and numbers (``56''). Figure~\ref{fig:example2} shows examples where supervised and unsupervised methods localize to different objects. In the first image, they both localize the phrase ``entrance'' incorrectly. In the remaining three images, the supervised method learns to predict a tight bounding box on the correct object, while the unsupervised method localizes to other irrelevant objects. For example (bottom left figure for Figure~\ref{fig:example2}), if the object detector fails to detect the ``blanket,'' then the unsupervised method can never localize ``green blanket'' to the right object. Still, the supervised method can learn from negative examples and obtain more information.
{'timestamp': '2020-10-13T02:26:32', 'yymm': '2010', 'arxiv_id': '2010.05379', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05379'}
arxiv
\section{Background} \subsection{Graph Neural Networks} \label{sec:gnn} GNNs emerge as a family of neural networks capable of learning a joint representation from both the graph structure and vertex/edge features. Recent studies~\cite{gnn-chemistry, graphnets} formulate GNN models with \emph{message passing}, in which vertices broadcast messages to their neighbors and compute their own representation by aggregating received messages. More formally, given a graph $\mathcal{G(\mathcal{V},\mathcal{E})}$, we denote the input feature of vertex $v$ as $\mathbf{h}_v^{(0)}$, and the feature of the edge between vertex $u$ and $v$ as $\mathbf{e}_{uv}$. To get the representation of a vertex at layer $l$, a GNN model performs the computations below: \begin{equation}\label{eq:mp-vertex} \mathbf{h}_v^{(l+1)} = g(\mathbf{h}_v^{(l)},\bigoplus_{u\in\mathcal{N}(v)} f(\mathbf{h}_u^{(l)}, \mathbf{h}_v^{(l)}, \mathbf{e}_{uv})) \end{equation} \noindent Here $f$, $\bigoplus$ and $g$ are customizable or parameterized functions (e.g., neural network modules) for calculating messages, aggregating messages, and updating vertex representations, respectively. Similar to convolutional neural networks (CNNs), a GNN model iteratively applies Equations~\eqref{eq:mp-vertex} to generate vertex representations for multiple layers. There are potentially two types of model parameters in graph neural networks. $f$, $\bigoplus$ and $g$ can contain model parameters, which are shared among all vertices. These model parameters are updated in every mini-batch and we refer to these parameters as \textit{dense} parameters. Some GNN models may additionally learn an \textit{embedding} for each vertex. Embeddings are part of the model parameters and only a subset of vertex embeddings are updated in a mini-batch. We refer to these model parameters as \textit{sparse} parameters. \subsection{Mini-batch training} \label{sec:minibatch} GNN models on a large dataset can be trained in a mini-batch fashion just like deep neural networks in other domains like computer vision and natural language processing. However, GNN mini-batch training is different from other neural networks due to the data dependency between vertices. Therefore, we need to carefully sample subgraphs that capture the data dependencies in the original graph to train GNN models. A typical strategy of training a GNN model \cite{graphsage} follows three steps: (i) sample a set of $N$ vertices, called \textit{target vertices}, uniformly at random from the training set; (ii) randomly pick at most $K$ (called \textit{fan-out}) neighbor vertices for each target vertex; (iii) compute the target vertex representations by gathering messages from the sampled neighbors. When the GNN has multiple layers, the sampling is repeated recursively. That is, from a sampled neighbor vertex, it continues sampling its neighbors. The number of recursions is determined by the number of layers in a GNN model. This sampling strategy forms a computation graph for passing messages on. Figure \ref{fig:mini_batch} depicts such a graph for computing representation of one target vertex when the GNN has two layers. The sampled graph and together with the extracted features are called a mini-batch in GNN training. \begin{figure} \centering \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.5\linewidth]{figures/full_graph.png} \caption{An input graph.} \label{fig:full_graph} \end{subfigure}% \hfill \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.3\linewidth]{figures/mini-batch.png} \caption{A sampled graph for computing one target vertex representation with a two-layer GNN model. Messages flow from leaves to root.} \label{fig:mini_batch} \end{subfigure} \caption{One sampled mini-batch in GNN training.} \label{fig:test} \end{figure} There have been many works regarding to the different strategies to sample graphs for mini-batch training \cite{chen2017stochastic, fastgcn, ladies, huang2018adaptive, clustergcn}. Therefore, a GNN framework needs to be flexible as well as scalable to giant graphs. \section{Conclusion} We develop DistDGL\xspace for distributed GNN training. We adopt Metis partitioning to generate graph partitions with minimum edge cuts and co-locate data and computation to reduce the network communication. We deploy multiple strategies to balance the graph partitions and mini-batches generated from each partition. We demonstrate that achieving high training speed requires both network communication reduction and load balancing. Our experiments show DistDGL\xspace has linear speedup of training GNN models on a cluster of CPU machines without compromising model accuracy. \section{DistDGL\xspace System Design} \subsection{Distributed Training Architecture} DistDGL\xspace distributes the mini-batch training process of GNN models to a cluster of machines. It follows the synchronous stochastic gradient descent (SGD) training; each machine computes model gradients with respect to its own mini-batch, synchronizes gradients with others and updates the local model replica. At a high level, DistDGL\xspace consists of the following logical components (Figure~\ref{fig:dist}): \begin{itemize} \item A number of \textit{samplers} in charge of sampling the mini-batch graph structures from the input graph. Users invoke DistDGL\xspace samplers in the trainer process via the same interface in DGL for neighbor sampling, which internally becomes a remote process call (RPC). After mini-batch graphs are generated, they are sent back to the trainers. \item A \textit{KVStore} that stores all vertex data and edge data distributedly. It provides two convenient interfaces for pulling the data from or pushing the data to the distributed store. It also manages the vertex embeddings if specified by the user-defined GNN model. \item A number of \textit{trainers} that compute the gradients of the model parameters over a mini-batch. At each iteration, they first fetch the mini-batch graphs from the samplers and the corresponding vertex/edge features from the KVStore. They then run the forward and backward computation on their own mini-batches in parallel to compute the gradients. The gradients of dense parameters are dispatched to the \textit{dense model update component} for synchronization, while the gradients of sparse embeddings are sent back to the KVStore for update. \item A \textit{dense model update component} for aggregating dense GNN parameters to perform synchronous SGD. DistDGL\xspace reuses the existing components depending on DGL's backend deep learning frameworks (e.g., PyTorch, MXNet and TensorFlow). For example, DistDGL\xspace calls the all-reduce primitive when the backend framework is PyTorch~\cite{li2020pytorch}, or resorts to parameter servers~\cite{ps} for MXNet and TensorFlow backends. \end{itemize} \begin{figure} \centering \includegraphics[width=0.95\linewidth]{figures/dist-2.png} \caption{DistDGL\xspace's logical components.} \label{fig:dist} \vspace{-1em} \end{figure} When deploying these logical components to actual hardware, the first consideration is to reduce the network traffic among machines because graph computation is data intensive~\cite{Eyerman2018}. DistDGL\xspace adopts the owner-compute rule (Figure~\ref{fig:arch}). The general principle is to dispatch computation to the data owner to reduce network communication. DistDGL\xspace first partitions the input graph with a light-weight min-cut graph partitioning algorithm. It then partitions the vertex/edge features and co-locates them with graph partitions. DistDGL\xspace launches the sampler and KVStore servers on each machine to serve the local partition data. Trainers also run on the same cluster of machines and each trainer is responsible for the training samples from the local partition. This design leverages data locality to its maximum. Each trainer works on samples from the local partition so the mini-batch graphs will contain mostly local vertices and edges. Most of the mini-batch features are locally available too via shared memory, reducing the network traffic significantly. In the following sections, we will elaborate more on the design of each components. \begin{figure} \centering \includegraphics[width=0.95\linewidth]{figures/arch.png} \caption{The deployment of DistDGL\xspace's logical components on a cluster of two machines.} \label{fig:arch} \vspace{-1em} \end{figure} \subsection{Graph Partitioning} \label{sec:partition} The goal of graph partitioning is to split the input graph to multiple partitions with a minimal number of edges across partitions. Graph partitioning is a preprocessing step before distributed training. A graph is partitioned once and used for many distributed training runs, so its overhead is amortized. DistDGL\xspace adopts METIS \cite{metis} to partition a graph. This algorithm assigns densely connected vertices to the same partition to reduce the number of edge cuts between partitions (Figure \ref{fig:assign_vertices}). After assigning some vertices to a partition, DistDGL\xspace assigns all incident edges of these vertices to the same partition. This ensures that all the neighbors of the local vertices are accessible on the partition so that samplers can compute locally without communicating to each other. With this partitioning strategy, each edge has a unique assignment while some vertices may be duplicated (Figure \ref{fig:graph_part}). We refer to the vertices assigned by METIS to a partition as \textit{core vertices} and the vertices duplicated by our edge assignment strategy as \textit{HALO vertices}. All the core vertices also have unique partition assignments. \begin{figure} \centering \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.5\linewidth]{figures/input_graph.png} \caption{Assign vertices to graph partitions} \label{fig:assign_vertices} \end{subfigure}% \hfill \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth]{figures/graph_partitions.png} \caption{Generate graph partitions with HALO vertices (the vertices with different colors from majority of the vertices in the partition).} \label{fig:graph_part} \end{subfigure} \caption{Graph partitioning with METIS in DistDGL\xspace.} \label{fig:test} \end{figure} While minimizing edge cut, DistDGL\xspace deploys multiple strategies to balance the partitions so that mini-batches of different trainers are roughly balanced. By default, METIS only balances the number of vertices in a graph. This is insufficient to generate balanced partitions for synchronous mini-batch training, which requires the same number of batches from each partition per epoch and all batches to have roughly the same size. We formulate this load balancing problem as a multi-constraint partitioning problem, which balances the partitions based on user-defined constraints~\cite{multiconstraint}. DistDGL\xspace takes advantage of the multi-constraint mechanism in METIS to balance training/validation/test vertices/edges in each partition as well as balancing the vertices of different types and the edges incident to the vertices of different types. METIS' partitioning algorithms are based on the multilevel paradigm, which has been shown to produce high-quality partitions. However, for many types of graphs involved in learning on graphs tasks (e.g., graphs with power-law degree distribution), the successively coarser graphs become progressively denser, which considerably increases the memory and computational complexity of multilevel algorithms. To address this problem, we extended METIS to only retain a subset of the edges in each successive graph so that the degree of each coarse vertex is the average degree of its constituent vertices. This ensures that as the number of vertices in the graph reduces by approximately a factor of two, so do the edges. To ensure that the partitioning solutions obtained in the coarser graphs represent high-quality solutions in the finer graphs, we only retain the edges with the highest weights in the coarser graph. In addition, to further reduce the memory requirements, we use an out-of-core strategy for the coarser/finer graphs that are not being processed currently. Finally, we run METIS by performing a single initial partitioning (default is 5) and a single refinement iteration (default is 10) during each level. For power-law degree graphs, this optimization leads to a small increase in the edge-cut (2\%-10\%) but considerably reduces its runtime. Overall, the set of optimizations above compute high-quality partitionings requiring ~5$\times$ less memory and ~8$\times$ less time than METIS' default algorithms. After partitioning the graph structure, we also partition vertex features and edge features based on the graph partitions. We only assign the features of the \textit{core vertices} and edges of a partition to the partition. Therefore, the vertex features and edge features are not duplicated. After graph partitioning, DistDGL\xspace manages two sets of vertex IDs and edge IDs. DistDGL\xspace exposes global vertex IDs and edge IDs for model developers to identify vertices and edges. Internally, DistDGL\xspace uses local vertex IDs and edge IDs to locate vertices and edges in a partition efficiently, which is essential to achieve high system speed as demonstrated by previous works \cite{gemini}. To save memory for maintaining the mapping between global IDs and local IDs, DistDGL\xspace relabels vertex IDs and edge IDs of the input graph during graph partitioning to ensure that all IDs of core vertices and edges in a partition fall into a contiguous ID range. In this way, mapping a global ID to a partition is binary lookup in a very small array and mapping a global ID to a local ID is a simple subtraction operation. \subsection{Distributed Key-Value Store} The features of vertices and edges are partitioned and stored in multiple machines. Even though DistDGL\xspace partitions a graph to assign densely connected vertices to a partition, we still need to read data from remote partitions. To simplify the data access on other machines, DistDGL\xspace develops a distributed in-memory key-value store (KVStore) to manage the vertex and edge features as well as vertex embeddings, instead of using an existing distributed in-memory KVStore, such as Reddis, for \textit{(i)} better co-location of node/edge features in KVStore and graph partitions, \textit{(ii)} faster network access for high-speed network, \textit{(iii)} efficient updates on sparse embeddings. DistDGL\xspace's KVStore supports flexible partition policies to map data to different machines. For example, vertex data and edge data are usually partitioned and mapped to machines differently as shown in Section \ref{sec:partition}. DistDGL\xspace defines separate partition policies for vertex data and edge data, which aligns with the graph partitions in each machine. Because accessing vertex and edge features usually accounts for the majority of communication in GNN distributed training, it is essential to support efficient data access in KVStore. A key optimization for fast data access is to use shared memory. Due to the co-location of data and computation, most of data access to KVStore results in the KVStore server on the local machine. Instead of going through Inter-Process Communication (IPC), the KVStore server shares all data with the trainer process via shared memory. Thus, trainers can access most of the data directly without paying any overhead of communication and process/thread scheduling. We also optimize network transmission of DistDGL\xspace's KVStore for fast networks (e.g., 100Gbps network). We develop an optimized RPC framework for fast networking communication, which adopts zero-copy mechanism for data serialization and multi-thread send/receive interface. In addition to storing the feature data, we design DistDGL\xspace's KVStore to support sparse embedding for training transductive models with learnable vertex embeddings. Examples are knowledge graph embedding models \cite{dglke}. In GNN mini-batch training, only a small subset of vertex embeddings are involved in the computation and updated during each iteration. Although almost all deep learning frameworks have off-the-shelf sparse embedding modules, most of them lack efficient support of distributed sparse update. DistDGL\xspace's KVStore shards the vertex embeddings in the same way as vertex features. Upon receiving the embedding gradients (via the PUSH interface), KVStore updates the embedding based on the optimizer the user registered. \subsection{Distributed Sampler} \label{sec:sampling} DGL has provided a set of flexible Python APIs to support a variety of sampling algorithms proposed in the literature. DistDGL\xspace keeps this API design but with a different internal implementation. At the beginning of each iteration, the trainer issues sampling requests using the target vertices in the current mini-batch. The requests are dispatched to the machines according to the core vertex assignment produced by the graph partitioning algorithm. Upon receiving the request, sampler servers call DGL's sampling operators on the local partition and transmit the result back to the trainer process. Finally, the trainer collects the results and stitches them together to generate a mini-batch. DistDGL\xspace deploys multiple optimizations to effectively accelerate mini-batch generation. DistDGL\xspace can create multiple sampling worker processes for each trainer to sample mini-batches in parallel. By issuing sampling requests to the sampling workers, trainers overlap the sampling cost with mini-batch training. When a sampling request goes to the local sampler server, the sampling workers to access the graph structure stored on the local sampler server directly via shared memory to avoid the cost of the RPC stack. The sampling workers also overlaps the remote RPCs with local sampling computation by first issuing remote requests asynchronously. This effectively hides the network latency because the local sampling usually accounts for most of the sampling time. When a sampler server receives sampling requests, it only needs to sample vertices and edges from the local partition because our graph partitioning strategy (Section~\ref{sec:partition}) guarantees that the core vertices in a partition have the access to the entire neighborhood. \subsection{Mini-batch Trainer} Mini-batch trainers run on each machine to jointly estimate gradients and update parameters of users' models. DistDGL\xspace provides utility functions to split the training set distributedly and generate balanced workloads between trainers. Each trainer samples data points uniformly at random to generate mini-batches independently. Because DistDGL generates balanced partitions (each partition has roughly the same number of nodes and edges) and uses synchronous SGD to train the model, the data points sampled collectively by all trainers in each iteration are still sampled uniformly at random across the entire dataset. As such, distributed training in DistDGL in theory does not affect the convergence rate or the model accuracy. To balance the computation in each trainer, DistDGL\xspace uses a two-level strategy to split the training set evenly across all trainers at the beginning of distributed training. We first ensure that each trainer has the same number of training samples. The multi-constraint algorithm in METIS (Section \ref{sec:partition}) can only assign roughly the same number of training samples (vertices or edges) to each partition (as shown by the rectangular boxes on the top in Figure \ref{fig:split}). We thus evenly split the training samples based on their IDs and assign the ID range to a machine whose graph partition has the largest overlap with the ID range. This is possible because we relabel vertex and edge IDs during graph partitioning and the vertices and edges in a partition have a contiguous ID range. There is a small misalignment between the training samples assigned to a trainer and the ones that reside in a partition. Essentially, we make a tradeoff between load balancing and data locality. In practice, as long as the graph partition algorithm balances the number of training samples between partitions, the tradeoff is negligible. If there are multiple trainers on one partition, we further split the local training vertices evenly and assign them to the trainers in the local machine. We find that random split in practice gives a fairly balanced workload assignment. In terms of parameter synchronization, we use synchronous SGD to update dense model parameters. Synchronous SGD is commonly used to train deep neural network models and usually leads to better model accuracy. We use asynchronous SGD to update the sparse vertex embeddings in the Hogwild fashion \cite{hogwild} to overlap communication and computation. In a large graph, there are many vertex embeddings. Asynchronous SGD updates some of the embeddings in a mini-batch. Concurrent updates from multiple trainers rarely result in conflicts because mini-batches from different trainers run on different embeddings. Previous study~\cite{dglke} has verified that asynchronous update of sparse embeddings can significantly speed up the training with nearly no accuracy loss. For distributed CPU training, DistDGL\xspace parallelizes the computation with both multiprocessing and multithreading. Inside a trainer process, we use OpenMP to parallelize the framework operator computation (e.g., sparse matrix multiplication and dense matrix multiplication). We run multiple trainer processes on each machine to parallelize the computation for non-uniform memory architecture (NUMA), which is a typical architecture for large CPU machines. This hybrid approach is potentially more advantageous than the multiprocessing approach for synchronous SGD because we need to aggregate gradients of model parameters from all trainer processes and broadcast new model parameters to all trainers. More trainer processes result in more communication overhead for model parameter updates. \begin{figure} \centering \includegraphics[width=0.5\linewidth]{figures/split.png} \caption{Split the workloads evenly to balance the computation among trainer processes.} \label{fig:split} \vspace{-1em} \end{figure} \section*{Acknowledgment} \bibliographystyle{IEEEtran} \section{Evaluation} \begin{comment} Dataset and model: GraphSage: Product graph Papers100M RGCN: MAG Hardware: 4x M5n.24xlarge 2 trainers per machine OMP thread: 20 #samplers: 4/8 per trainer #servers: 1 Compare with Euler Weak scaling batch size per machine is fixed, increase the number of machines. ** weak scalability on product graph Evaluate optimizations on 4 machines: optimizations: ** baseline ** with METIS default ** METIS with multi-constraints * reorder vertex to avoid memory copy * async pull DGL's Sparse embedding vs. Pytorch sparse embeddings on product graph \end{comment} In this section, we evaluate DistDGL\xspace to answer the following questions: \begin{itemize} \item \emph{Can DistDGL\xspace train GNNs on large-scale graphs and accelerate the training with more machines?} \item \emph{Can DistDGL\xspace's techniques effectively increase the data locality for GNN training?} \item \emph{Can our load balancing strategies effectively balance the workloads in the cluster of machines?} \end{itemize} \begin{table} \centering \caption{Dataset statistics from the Open Graph Benchmark~\cite{ogb}.}\label{tbl:dataset} \begin{tabular}{lrrr}\toprule Dataset & \# Nodes & \# Edges & Node Features \\\midrule \textsc{ogbn-product} & 2,449,029 & 61,859,140 & 100 \\ \textsc{ogbn-papers100M} & 111,059,956 & 3,231,371,744 & 128 \\ \bottomrule \end{tabular} \end{table} We focused on the node classification task using GNNs throughout the evaluation. The GNNs for other tasks such as link prediction mostly differ in the objective function while sharing most of the GNN architectures so we omit them in the experiments. We benchmark the state-of-the-art GraphSAGE~\cite{graphsage} model on two Open Graph Benchmark (OGB) datasets \cite{ogb} shown in Table \ref{tbl:dataset}. The GraphSAGE model has three layers of hidden size 256; the sampling fan-outs of each layer are 15, 10 and 5. We use a cluster of eight AWS EC2 m5n.24xlarge instances (96 VCPU, 384GB RAM each) connected by a 100Gbps network. In all experiments, we use DGL v0.5 and Pytorch 1.5. For Euler experiments, we use Euler v2.0 and TensorFlow 1.12. \subsection{DistDGL\xspace vs. other distributed GNN frameworks} We compare the training speed of DistDGL\xspace with Euler \cite{euler}, one of the state-of-the-art distributed GNN training frameworks, on four m5n.24xlarge instances. Euler is designed for distributed mini-batch training, but it adopts different parallelization strategy from DistDGL\xspace. It parallelizes computation completely with multiprocessing and uses one thread for both forward and backward computation as well as sampling inside a trainer. To have a fair comparison between the two frameworks, we run mini-batch training with the same global batch size (the total size of the batches of all trainers in an iteration) on both frameworks because we use synchronized SGD to train models. \begin{figure} \centering \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.9\linewidth]{figures/dgl-vs-euler.png} \caption{The overall runtime per epoch with different global batch sizes.} \label{fig:overall_runtime} \end{subfigure}% \hfill \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.95\linewidth]{figures/breakdown.png} \caption{The breakdown of epoch runtime for the batch size of 32K.} \label{fig:breakdown} \end{subfigure} \caption{DistDGL\xspace vs Euler on \textsc{ogbn-product} graph on four m5n.24xlarge instances.} \label{fig:dgl_vs_euler} \end{figure} DistDGL\xspace gets $2.2\times$ speedup over Euler in all different batch sizes (Figure \ref{fig:overall_runtime}). To have a better understanding of DistDGL\xspace's performance advantage, we break down the runtime of each component within an iteration shown in Figure \ref{fig:breakdown}. The main advantage of DistDGL\xspace is \textit{data copy}, in which DistDGL\xspace has more than $5\times$ speedup. This is expected because DistDGL\xspace uses METIS to generate partitions with minimal edge cuts and trainers are co-located with the partition data to reduce network communication. The speed of \textit{data copy} in DistDGL\xspace gets close to local memory copy while Euler has to copy data through TCP/IP from the network. DistDGL\xspace also has $2\times$ speedup in \textit{sampling} over Euler for the same reason: DistDGL\xspace samples majority of vertices and edges from the local partition to generate mini-batches. DistDGL\xspace relies on DGL and Pytorch to perform sparse and dense tensor computation in a mini-batch and uses Pytorch to synchronize gradients among trainers while Euler relies on TensorFlow for both mini-batch computation and gradient synchronization. DistDGL\xspace is slightly faster in mini-batch computation and gradient synchronization. Unfortunately, we cannot separate the batch computation and gradient synchronization in Pytorch. \subsection{DistDGL\xspace's sparse embedding vs. Pytorch's sparse embedding} Many graph datasets do not have vertex features. We typically use transductive GNN models with learnable vertex embeddings for these graphs. DistDGL\xspace provides distributed embeddings for such use case, with optimizations for sparse updates. Deep learning frameworks, such as Pytorch, also provide the sparse embedding layer for similar use cases and the embedding layer can be trained in a distributed fashion. To evaluate the efficiency of DistDGL\xspace's distributed embeddings, we adapt the GraphSage model by replacing vertex data of the input graph with DistDGL\xspace's or Pytorch's sparse embeddings. The GraphSage model with DistDGL\xspace's sparse embeddings on \textsc{ogbn-product} graph gets almsot $70\times$ speedup over the version with Pytorch sparse embeddings (Figure \ref{fig:dgl-vs-pytorch}). The main difference is that DistDGL\xspace's sparse embeddings are updated with DistDGL\xspace's efficient KVStore, which is natural for implementing sparse embedding updates. As such, it gets all benefits of DistDGL\xspace's optimizations, such as co-location of data and computation. In contrast, Pytorch's sparse embeddings are updated with its DistributedDataParallel module. Essentially, it is implemented with the AllReduce primitive, which requires the gradient tensor exchanged between trainers to have exactly the same shape. As such, Pytorch has to pad the gradient tensor of sparse embeddings to the same size. \begin{figure} \centering \includegraphics[width=0.95\linewidth]{figures/dgl-vs-pytorch.png} \caption{The GraphSage model with DistDGL\xspace's and Pyotch's sparse Embedding on the \textsc{ogbn-product} graph.} \label{fig:dgl-vs-pytorch} \end{figure} \subsection{Scalability} We further evaluate the scalability of DistDGL\xspace in the EC2 cluster. In this experiment, we fix the mini-batch size in each trainer and increase the number of trainers when the number of machines increases. We use the batch size of 2000 per trainer. DistDGL\xspace achieves a linear speedup as the number of machines increases in the cluster (Figure \ref{fig:scalability}) for both OGB datasets. When running on a larger cluster, DistDGL\xspace needs to perform more sampling on remote machines and fetch more data from remote machines. This linear speedup indicates that our optimizations prevent network communication from being the bottleneck. It also suggests that the system is well balanced when the number of machines increases. With all of our optimizations, DistDGL\xspace can easily scale to large graphs with hundreds of millions of nodes. It takes only 13 seconds to train the GraphSage model on the \textsc{ogbn-papers100M} graph in a cluster of 16 m5.24xlarge machines. We also compare DistDGL\xspace with DGL's multiprocessing training (two trainer processes). DistDGL\xspace running on a single machine with two trainers outperforms DGL. This may attribute to the different multiprocessing sampling used by the two frameworks. DGL relies on Pytroch dataloader's multiprocessing to sample mini-batches while DistDGL\xspace uses dedicated sampler processes to generate mini-batches. \begin{figure} \centering \includegraphics[width=0.95\linewidth]{figures/scalability.png} \caption{DistDGL\xspace achieves linear speedup w.r.t. the number of machines. } \label{fig:scalability} \end{figure} \begin{figure} \centering \includegraphics[width=0.95\linewidth]{figures/convergence.png} \caption{DistDGL\xspace convergence of distributed training. } \label{fig:convergence} \end{figure} In addition to the training speed, we also verify the training accuracy of DistDGL\xspace on different numbers of machines (Figure \ref{fig:convergence}). We can see that DistDGL\xspace quickly converges to almost the same peak accuracy achieved by the single-machine training, which takes a much longer time to converge. \subsection{Ablation Study} We further study the effectiveness of the main optimizations in DistDGL\xspace: 1) reducing network traffic by METIS graph partitioning and co-locating data and computation, 2) balance the graph partitions with multi-constraint partitioning. To evaluate their effectiveness, we compare DistDGL\xspace's graph partitioning algorithm with two alternatives: random graph partitioning and default METIS partitioning without multi-constraints. We use a cluster of four machines to run the experiments. \begin{figure} \centering \includegraphics[width=0.95\linewidth]{figures/metis-vs-random.png} \caption{METIS vs Random Partition on four machines} \label{fig:metis} \end{figure} METIS partitioning with multi-constraints to balance the partitions achieves good performance on both datasets (Figure \ref{fig:metis}). Default METIS partitioning performs well compared with random partitioning ($2.14\times$ speedup) on the \textsc{ogbn-product} graph due to its superior reduction of network communication; adding multiple constraints to balance partitions gives additional 4\% improvement over default METIS partitioning. However, default METIS partitioning achieves much worse performance than random partitioning on the \textsc{ogbn-papers100M} graph due to high imbalance between partitions created by METIS, even though METIS can effectively reduce the number of edge cuts between partitions. Adding multi-constraint optimizations to balance the partitions, we see the benefit of reducing network communication. This suggests that achieving load balancing is as important as reducing network communication for improving performance. \section{Introduction} Graph Neural Networks (GNNs) have shown success in learning from graph-structured data and have been applied to many graph applications in social networks, recommendation, knowledge graphs, etc. In these applications, graphs are usually huge, in the order of many millions of nodes or even billions of nodes. For instance, Facebook social network graph contains billions of nodes. Amazon is selling billions of items and has billions of users, which forms a giant bipartite graph for its recommendation task. Natural language processing tasks take advantage of knowledge graphs, such as Freebase \cite{freebase} with 1.9 billion triples. It is challenging to train a GNN model on a large graph. Unlike domains such as computer vision and natural language processing, where training samples are mutually independent, graph inherently represents the dependencies among training samples (i.e., vertices). Hence, mini-batch training on GNNs is different from the traditional deep neural networks; each mini-batch must incorporate those depending samples. The number of depending samples usually grows exponentially when exploring more hops of neighbors. This leads to many efforts in designing various sampling algorithms to scale GNNs to large graphs \cite{graphsage, chen2017stochastic, fastgcn, huang2018, pinsage}. The goal of these methods is to prune the vertex dependency to reduce the computation while still estimating the vertex representation computed by GNN models accurately. It gets even more challenging to train GNNs on giant graphs when scaling beyond a single machine. For instance, a graph with billions of nodes requires memory in the order of terabytes attributing to large vertex features and edge features. Due to the vertex dependency, distributed GNN training requires to read hundreds of neighbor vertex data to compute a single vertex representation, which accounts for majority of network traffic in distributed GNN training. This is different from traditional distributed neural network training, in which majority of network traffic comes from exchanging the gradients of model parameters. In addition, neural network models are typically trained with synchronized stochastic gradient descent (SGD) to achieve good model accuracy. This requires the distributed GNN framework to generate balanced mini-batches that contain roughly the same number of nodes and edges as well as reading the same account of data from the network. Due to the complex subgraph structures in natural graphs, it is difficult to generate such balanced mini-batches. Unfortunately, current systems cannot effectively address the challenges of distributed GNN training. Previous distributed graph analytical systems~\cite{pregel,powergraph,ligra} are designed for full graph computation expressed in the vertex-centric program paradigm, which is not suitable for GNN mini-batch training. Existing domain-specific frameworks for training GNNs, such as DGL~\cite{dgl} and PyTorch-Geometric~\cite{pyg}, cannot scale to giant graphs. They were mainly developed for training on a single machine. Although there have been some efforts in building systems for distributed GNN training, they either focus on full batch training by partitioning graphs to fit the aggregated memory of multiple devices~\cite{roc,neugraph,tripathy2020reducing} or suffer from the huge network traffic caused by fetching neighbor node data~\cite{aligraph,agl,euler}. System architectures~\cite{ps,project_adam,byteps} proposed for training neural networks for computer vision and natural language processing are not directly applicable because one critical bottleneck in GNN training is the network traffic of fetching neighbor node data due to the vertex dependencies, while previous systems majorly focuses on network traffic from exchanging the gradients of model parameters. In this work, we develop DistDGL\xspace on top of DGL to perform efficient and scalable mini-batch GNN training on a cluster of machines. It provides distributed components with APIs compatible to DGL's existing ones. As such, it requires trivial effort to port DGL's training code to DistDGL\xspace. Internally, it deploys multiple optimizations to speed up computation. It distributes graph data (both graph structure and the associated data, such as node and edge features) across all machines and run trainers, sampling servers (for sampling subgraphs to generate mini-batches) and in-memory KVStore servers (for serving node data and edge data) all on the same set of machines. To achieve good model accuracy, DistDGL\xspace follows a synchronous training approach and allows ego-networks forming the mini-batches to include non-local nodes. To reduce network communication, DistDGL\xspace adopts METIS \cite{metis} to partition a graph with minimum edge cut and co-locate data with training computation. In addition, DistDGL\xspace deploys multiple load balancing optimizations to tackle the imbalance issue, including multi-constraint partitioning and two-level workload splitting. DistDGL\xspace further reduces network communication in sampling by replicating halo nodes in the partitioned graph structure but does not replicate data in halo nodes to have a small memory footprint. DistDGL\xspace provides distributed embeddings with efficient sparse updates for transductive graph models. We conduct comprehensive experiments to evaluate the efficiency of DistDGL\xspace and effectiveness of the optimizations. Overall, DistDGL\xspace achieves $2.2\times$ speedup over Euler on a cluster of four CPU machines. The main performance advantage comes from the efficient feature copy with $5\times$ data copy throughput. DistDGL\xspace speeds up the training linearly without compromising model accuracy as the number of machines increases in a cluster of 16 machines and easily scales the GraphSage model to a graph with 100 million nodes and 3 billion edges. It takes 13 seconds per epoch to train on such a graph in a cluster of 16 machines. \section{Related Work} \subsection{Distributed DNN Training} There are many system-related works to optimize distributed deep neural network (DNN) training. The parameter server~\cite{li2014scaling} is designed to maintain and update the sparse model parameters. Horovod~\cite{horovod} and Pytorch distributed~\cite{li2020pytorch} uses allreduce to aggregate dense model parameters but does not work for sparse model parameters. BytePs~\cite{byteps} adopts more sophisticated techniques of overlapping model computation and gradient communication to accelerate dense model parameter updates. Many works reduces the amount of communication by using quantization~\cite{seide20141} or sketching~\cite{ivkin2019communicationefficient}. Several recent work focuses on relaxing the synchronization of weights ~\cite{ho2013more, luo2019hop} in case some workers run slower than others temporally due to some hardware issues. GNN models are composed of multiple operators organized into multiple graph convolution network layers shared among all nodes and edges. Thus, GNN training also has dense parameter updates. However, the network traffic generated by dense parameter updates is relatively small compared with node/edge features. Thus, reducing the network traffic of dense parameter updates is not our main focus for distributed GNN training. \subsection{Distributed GNN Training} A few works have been developed to scale GNN training on large graph data in the multi-GPU setting or distributed setting. Some of them~\cite{roc, neugraph, tripathy2020reducing} perform full graph training on multiple GPUs or distributed memory whose aggregated memory fit the graph data. However, we believe full graph training is an inefficient way to train a GNN model in a large graph data because one model update requires significant amount of computation. The mini-batch training has been widely adopted in training a neural network. Multiple GNN frameworks \cite{aligraph, agl, euler} built by industry adopt distributed mini-batch training. However, none of these frameworks adopt locality-aware graph partitioning and co-locate data and communication. As shown in our experiment, reducing communication is a key to achieve good performance. \subsection{Distributed graph processing} There are many works on distributed graph processing frameworks. Pregel \cite{pregel} is one of the first frameworks that adopt message passing and vertex-centric interface to perform basic graph analytics algorithms such as breadth-first search and triangle counting. PowerGraph \cite{powergraph} adopts vertex cut for graph partitioning and gather-and-scatter interface for computation. PowerGraph had significant performance improvement overhead Pregel. Gemini \cite{gemini} shows that previous distributed graph processing framework has significant overhead in a single machine. It adopts the approach to improve graph computation in a single machine first before optimizing for distributed computation. Even though the computation pattern of distributed mini-batch training of GNN is very different from traditional graph analytics algorithms, the evolution of graph processing frameworks provide valuable lessons for us and many of the general ideas, such as locality-aware graph partitioning and co-locating data and computation, are borrowed to optimize distributed GNN training.
{'timestamp': '2021-08-04T02:01:33', 'yymm': '2010', 'arxiv_id': '2010.05337', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05337'}
arxiv
\section{Introduction} \label{sec:introduction} Blockchain is a distributed ledger technology for recording transactions that underlies various services such as the digital currency Bitcoin~\cite{nakamoto}. Blockchain-based services use cryptography to record transactions as a chain of blocks. A block consists of a block header and transaction data. The block header contains a cryptographic hash of the previous block, making blockchain-based services resistant to tampering. In these services, users called \textit{miners} create blocks in a distributed manner, and the longest chain of blocks, called the \textit{main chain}, is considered to be legitimate. The process of creating blocks is called \textit{mining}. Blockchain-based services approve transactions through a consensus algorithm, typically proof-of-work (PoW). In this algorithm, the mining difficulty is set using a 4-byte value called a \textit{nonce} in the block header. To create a block, miners must find a nonce such that the cryptographic hash value for the previous block satisfies specific conditions, determined according to the mining difficulty. In general, a cryptographic hash value for a block is unique according to the nonce contained in the block. Moreover, a nonce that satisfies the specific conditions cannot be calculated directly. This is an exhaustive search that imposes a large computational cost on miners. Consequently, PoW also contributes to the resistance to tampering. Because transaction approvals depend on miner calculations, miner incentives are important to maintain blockchain-based services. When a miner successes in creating a block and the created block is contained in the main chain, he/she gets a reward. Game theory is used to analyze the interaction among rational decision-makers~\cite{game_t}. A Nash equilibrium is the most accepted solution concept for a non-cooperative game. Intuitively, it is the most rational solution for all decision-makers in the sense that no decision-maker has a reason for changing his/her decision if the others maintain their decisions. A non-cooperative game is applied in various fields, such as network security~\cite{network_security} and resource management~\cite{network_communication}. Because miners make decisions in a distributed and selfish manner, many studies have adopted game theory to analyze their behavior~\cite{survey_game}. In particular, mining involves significant energy consumption~\cite{bl_energy,mining_cost}, so it is important to analyze miner behavior considering both energy consumption and the expected reward. Dimitri~\cite{contest} discussed the computational resources needed for mining under a given computation cost and showed that the decision on investment for mining depends only on the average mining cost. Fiat et~al.~\cite{energy_eq} discussed computational resources spent for mining under an upper limit on time units for hash calculations, showing that all miners use all available resources. These previous studies implicitly assumed blocks will always be created within a given cost or number of hash calculations. However, these assumptions are not practical for actual blockchain-based services. In this paper, we formulate the energy consumption under the condition that miners keep calculating while paying the cost without the upper limit until the block is created. We adopt a deterministic game approach to analyze the relation between mining reward amount and the decision-making regarding participation in mining considering energy consumption and the expected reward. Specifically, we formulate a utility function according to energy consumption and the mean reward for mining, and model the decision-making problem of miners as a noncooperative game. Through theoretical and numerical analyses, we show a hysteresis phenomenon of Nash equilibria depending on the reward and a jump phenomenon of miner decisions by a slight change of the reward. The remainder of this paper is organized as follows. In Section~\ref{sec:pre}, we formulate the decision-making problem as a noncooperative game. In Section~\ref{sec:two_miners}, we analyze the Nash equilibrium of the game in the case of two miners. Section~\ref{sec:numerical_a} presents a numerical analysis. \section{Game Formulation}\label{sec:pre} \subsection{Miner decision-making as a game}\label{sec:min} It is an important decision-making problem for a miner in the blockchain networks if he/she participates in the mining so that he/she earns a reward by creating a new block earlier than other miners. We formulate this decision-making problem as a non-cooperative game because the probability of creating a block depends not only on one's own available computational resources, but also those of other miners. We denote $\mathcal{N} = \{1, 2, \ldots, n\}$ as a set of miners ($n \geq 2$) in a blockchain network. Each miner $k \in \mathcal{N}$ has a strategy set $S_k = \{0, 1\}$. The strategy $s_k = 1$ denotes that miner $k$ participates in the mining and $s_k = 0$ denotes that miner $k$ does not participate in the mining. Let $s = (s_1, \ldots, s_n)$ and $S = \times_{k \in \mathcal{N}} S_k$ be a strategy profile and the set of strategy profiles, respectively. We denote $U: S \to \mathbb{R}^n$ as a utility function for all miners and $U_k: S \to \mathbb{R}$ as a utility function for miner $k \in \mathcal{N}$, that is, $U(s) = (U_1(s), \ldots, U_n(s))$ for a given strategy profile $s$. Then, the game is described as the tuple \begin{equation} G_n = (\mathcal{N}, S, U). \label{eq:n_game_general} \end{equation} In Section~\ref{sec:util_def}, we will derive the utility function $U_k$. \subsection{Derivation of the utility function}\label{sec:util_def} To create a new block, a miner calculates a hash value $H(\mbox{tx}, \; \mbox{prev.hash}, \; \mbox{nc})$ using the data of the previous block, namely, the Merkle root of transactions $\mbox{tx}$, the hash of previous block header $\mbox{prev.hash}$, and the nonce $\mbox{nc}$. The hash function~$H$ outputs an $L$-bit hash value ($L \in \mathbb{N}$) according to inputs $\mbox{tx}$, $\mbox{prev.hash}$, and $\mbox{nc}$. In PoW~\cite{nakamoto,consensus}, the miner needs to find a nonce that satisfies \begin{equation} H(\mbox{tx}, \; \mbox{prev.hash}, \; \mbox{nc}) \leq 2^{L - h}. \label{eq:hash_satisfy} \end{equation} For a given target value $2^{L - h}$ in \eqref{eq:hash_satisfy}\footnote{ Note that $h \in \mathbb{N}$. In this context, $h$ corresponds to the difficulty of finding a nonce. The larger $h$ is, the more time is needed for miners to find a nonce. The selection of values $L$ and $h$ depends on the blockchain services. In Bitcoin~\cite{nakamoto}, $L = 256$ and difficulty $h$ is set so that the average number of generated blocks per hour is constant. }, the probability that a miner creates a block with one hash calculation is \begin{equation} \mathbb{P}\left[H(\mbox{tx}, \; \mbox{prev.hash}, \; \mbox{nc}) \leq 2^{L - h}\right] = \frac{1}{D}, \nonumber \end{equation} where $D = 2^h$~\cite{survey_consensus}. The relation between blocks and the times they are created is modeled by a Poisson process~\cite{bitcoin_game}. Let $w_k$ be the average number of queries to $H(\cdot)$ of miner $k \in \mathcal{N}$ calculated per unit operating time. The rate $\lambda_k$ of the Poisson process for miner $k$ is given by $\lambda_k = w_k / D$~\cite{dif}. When the miner $k$ participates in the mining, he/she needs a cost $c_k \geq 0$ per unit operating time and calculates queries whose average number per unit operating time depends on the cost, that is, we assume that $w_k = f_k(c_k)$, where $f_k: \mathbb{R}_{+} \to \mathbb{R}_{+}$ is a non-decreasing function. If miner $k$ chooses $s_k = 1$, then the rate of the Poisson process is \begin{equation} \lambda_k = \frac{s_k f_k(c_k)}{D}. \nonumber \end{equation} First, we calculate the expected reward for mining. Let $\mathcal{M} \subseteq \mathcal{N}$ be the set of miners who choose to participate in the mining. We assume that all miners in $\mathcal{M}$ start trying to create a new block at time $t = 0$ and that they create same-size blocks. The first miner to create a block that reaches consensus earns a reward $R \geq 0$ ($R \in \mathbb{R}_{+}$)\footnote{The reward includes a fixed reward and a variable one depending on the block size. From the assumption that all miners create same-size blocks, reward $R$ is independent of the miners.}. Let $B_k(t)$ be the probability of miner $k$ creating a block before other miners be between $t$ and $t + dt$. Then, using the properties of the Poisson process, we have \begin{align} &B_k(t) \nonumber \\ &=\exp(-\lambda_k t) \lambda_k dt \exp(-\lambda_k dt) \hspace{-2mm} \prod_{i \in \mathcal{M} \setminus \{k\}} \hspace{-2mm} \exp(-\lambda_i (t + dt)) \nonumber \\ &\approx \lambda_k \exp\left(-\sum_{i \in \mathcal{M}}\lambda_i t\right) dt = \lambda_k \exp\left(-\sum_{i \in \mathcal{N}}\lambda_i t\right) dt. \label{eq:k_t_dt} \end{align} From the assumption that all miners create same-size blocks, the probability of earning the reward equals the probability of creating the block~\cite{bitcoin_game}. Then, for any miner $k \in \mathcal{N}$, the probability $P_k(s)$ of earning the reward is given by the integration of \eqref{eq:k_t_dt} in the interval $[0, \infty)$: \begin{align} P_k(s) &= \int_{0}^{\infty} \lambda_k \exp \left(-\sum_{i \in \mathcal{N}} \lambda_i t\right) dt \nonumber \\ &= \frac{\lambda_k}{\sum_{i \in \mathcal{N}} \lambda_i} = \frac{s_k f_k(c_k)}{\sum_{i \in \mathcal{N}} s_i f_i(c_i)}. \nonumber \end{align} Note that the probability of miner $k$ earning the reward is $0$ when miner $k$ chooses $s_k = 0$. Therefore, for any miner $k \in \mathcal{N}$, the expected reward $R_k(s)$ is \begin{equation} R_k(s) = \frac{s_k f_k(c_k)}{\sum_{i \in \mathcal{N}} s_i f_i(c_i)}R. \label{eq:exp_reward} \end{equation} Next, we calculate the expected cost for creating a block in the same way as calculating the expected reward. Assume miner $k$ consumes cost $c_k$ per unit operating time until a nonce that satisfies \eqref{eq:hash_satisfy} is found. The expected cost for mining $CS_k(s)$ is \begin{align} CS_k(s) &= c_k \int_{0}^{\infty} t \lambda_k \exp\left(- \sum_{i \in \mathcal{N}} \lambda_it \right) dt \nonumber \\ &= \frac{c_k \lambda_k}{(\sum_{i \in \mathcal{N}}\lambda_i)^2} = \frac{s_k f_k(c_k)}{\sum_{i \in \mathcal{N}}s_i f_i(c_i)}\frac{Dc_k}{\sum_{i \in \mathcal{N}} s_i f_i(c_i)}. \label{eq:cst} \end{align} Finally, we define the utility function \begin{align} &U_k(s) \nonumber \\ &= \begin{cases} 0 & \mbox{if} \; \; s = (0, \ldots, 0), \\ \frac{s_k f_k(c_k)}{\sum_{i \in \mathcal{N}}s_i f_i(c_i)} \left(R - \frac{Dc_k}{\sum_{i \in \mathcal{N}}s_i f_i(c_i)}\right) &\mbox{otherwise} \end{cases}\label{eq:utility} \end{align} as the difference between \eqref{eq:exp_reward} and \eqref{eq:cst}. Note that when no miners decide to participate in the mining, $U_k(s)=0$ for all miners. \subsection{Extension to mixed strategies}\label{sec:mixed_str} We denote $X = \times_{k \in \mathcal{N}} X_k$ as a mixed strategy space where \begin{equation} X_k = \{x_k = (x_k^0, 1 - x_k^0)^{\mathrm{T}} \, | \, 0 \leq x_k^0 \leq 1 \}, \nonumber \end{equation} and $x_k^0$ represents the probability of miner $k$ choosing $s_k = 0$. Let $x = (x_1, \ldots, x_n)$ and $x_{-k}$ represent a mixed strategy profile for all miners and for all miners except $k$, respectively. We define $e_m^i$ as an $m$-dimensional unit vector in which only the $i$-th component is 1. Note that mixed strategy profiles $(e_2^1, \ldots, e_2^1)$ and $(e_2^2, \ldots, e_2^2)$ correspond to pure strategy profiles $s = (0, \ldots, 0)$ and $s = (1, \ldots, 1)$, respectively. Then, for any mixed strategy profile $x$, the expected utility function $u_k: X \to \mathbb{R}$ of miner $k \in \mathcal{N}$ is \begin{equation} u_k(x) = x_k^0 u_k(e_2^1, x_{-k}) + (1 - x_k^0) u_k(e_2^2, x_{-k}). \nonumber \end{equation} Note that $u_k(e_2^1, x_{-k})$ and $u_k(e_2^2, x_{-k})$ are the expected utility values when miner $k$ chooses strategy $s_k = 0$ and $s_k = 1$, respectively. Let $\tilde{\beta}_k : X \to 2^{X_k}$ represent the best response correspondence of miner $k$ for mixed strategy $x$ as \begin{align} &\tilde{\beta}_k(x) \nonumber \\ &=\{x_k^{*} \in X_k \, | \, \forall x_k^{\prime} \in X_k \; u_k(x_k^{*}, x_{-k}) \geq u_k(x_k^{\prime}, x_{-k})\}. \nonumber \end{align} A mixed strategy $x^{*}$ satisfying $x^{*} \in \tilde{\beta}(x^{*})$ is called a Nash equilibrium, where $\tilde{\beta}(x) = \times_{k \in \mathcal{N}} \tilde{\beta}_k(x) \subseteq X$. We denote $\mbox{NE}(G_n)$ as the set of Nash equilibria in game $G_n$. \section{The two-miners case}\label{sec:two_miners} In this section, we focus on the case of two miners, namely, where $\mathcal{N} = \{1, 2\}$ and $f_k(c_k)$ is a linear function $f_k(c_k) = v_k c_k, \, v_k \in \mathbb{R}_{+}$ for all $k \in \mathcal{N}$. We theoretically derive the Nash equilibria of game $G_2$, where the utility functions of two miners are written as \begin{align} &U_1(s) \nonumber \\ &= \begin{cases} 0 & \mbox{if} \; \; (s_1, s_2) = (0, 0), \\ \frac{s_1}{s_1 + s_2 p_v p_c}\left(R - \frac{d}{s_1 + s_2 p_v p_c}\right) & \mbox{otherwise}, \end{cases}\label{eq:util_m1} \\ &U_2(s) \nonumber \\ &= \begin{cases} 0 & \mbox{if} \; \; (s_1, s_2) = (0, 0), \\ \frac{s_2 p_v p_c}{s_1 + s_2 p_v p_c}\left(R - \frac{dp_c}{s_1 + s_2 p_v p_c}\right) & \mbox{otherwise}, \end{cases}\label{eq:util_m2} \end{align} where $p_v \coloneqq v_2 / v_1 > 0$, $p_c \coloneqq c_2 / c_1 > 0$, and $d \coloneqq D / v_1 > 0$. We can assume $p_v \geq 1 \; (0 < v_1 \leq v_2)$ without loss of generality\footnote{Intuitively, $v_k$ is the cost-effectiveness, and $p_v$ and $p_c$ are parameters that represent ratios of cost-effectiveness and cost, respectively. When $v_1$ is constant, the larger the difficulty $D$ (difficulty level $h$), the larger the value of $d$.}. Strategic forms for finite two-player games are depicted as matrices. Tables~\ref{tab:pr_1} and \ref{tab:pr_2} show payoffs for the corresponding strategy profiles of miners~1 and 2, respectively. \begin{table}[b] \centering \caption{Miner 1's payoff for the corresponding strategy profile.} \setlength{\extrarowheight}{2pt} \begin{tabular}{cc|c|c|} & \multicolumn{1}{c}{} & \multicolumn{2}{c}{$S_2$}\\ & \multicolumn{1}{c}{} & \multicolumn{1}{c}{$0$} & \multicolumn{1}{c}{$1$} \\\cline{3-4} \multirow{2}*{$S_1$} & $0$ & $0$ & $0$ \\\cline{3-4} & $1$ & $R - d$ & $\displaystyle \frac{1}{1 + p_v p_c}\left(R - \frac{d}{1 + p_v p_c}\right)$ \\\cline{3-4} \end{tabular} \label{tab:pr_1} \end{table} \begin{table}[b] \centering \caption{Miner 2's payoff for the corresponding strategy profile.} \setlength{\extrarowheight}{2pt} \begin{tabular}{cc|c|c|} & \multicolumn{1}{c}{} & \multicolumn{2}{c}{$S_2$}\\ & \multicolumn{1}{c}{} & \multicolumn{1}{c}{$0$} & \multicolumn{1}{c}{$1$} \\\cline{3-4} \multirow{2}*{$S_1$} & $0$ & $0$ & $\displaystyle R - \frac{d}{p_v}$ \\\cline{3-4} & $1$ & $0$ & $\displaystyle \frac{p_v p_c}{1 + p_v p_c}\left(R - \frac{dp_c}{1 + p_v p_c}\right)$ \\\cline{3-4} \end{tabular} \label{tab:pr_2} \end{table} We obtain the set of Nash equilibria for mixed strategies of game $G_2$ as in Proposition~\ref{prop:nash}. \begin{prop}\label{prop:nash} Assume $p_v \geq 1$. We define functions $g_1: \mathbb{R} \to \mathbb{R}$ and $g_2: \mathbb{R} \to \mathbb{R}$ as \begin{align} &g_1(z) = p_v p_c \left(z - \frac{p_c}{1 + p_v p_c}\right) \left(\frac{2p_v p_c + 1}{p_v(1 + p_v p_c)} - z\right)^{-1}, \label{eq:gz1} \\ &g_2(z) = \left(z - \frac{1}{1 + p_v p_c}\right)\left(p_v p_c \left(\frac{2 + p_v p_c}{1 + p_v p_c} - z\right)\right)^{-1}. \label{eq:gz2} \end{align} Respectively letting $\alpha_1$ and $\alpha_2$ be $\alpha_1 \coloneqq g_1(R/d)$ and $\alpha_2 \coloneqq g_2(R/d)$, the set $\mbox{NE}(G_2)$ is given as follows\footnote{ Intuitively, the value $R/d$ represents how much reward is given for the difficulty, increasing with reward $R$ and decreasing with difficulty level $h$.}: If $p_c \geq 1$, then \begin{align} &\mbox{NE}(G_2) = \nonumber \\ &\begin{cases} \{(e_2^1, e_2^1)\} \\ \hspace{15mm} \mbox{if} \; \; \frac{R}{d} < \frac{p_c}{1 + p_v p_c}, \\ \{(e_2^1, e_2^1), (e_2^2, (\gamma_2, 1 - \gamma_2)^{\mathrm{T}})\} \\ \hspace{15mm} \mbox{if} \; \; \frac{R}{d} = \frac{p_c}{1 + p_v p_c}, \\ \{(e_2^1, e_2^1), (e_2^2, e_2^2), ((\alpha_1, 1 - \alpha_1)^{\mathrm{T}}, (\alpha_2, 1 - \alpha_2)^{\mathrm{T}})\} \\ \hspace{15mm} \mbox{if} \; \; \frac{p_c}{1 + p_v p_c} < \frac{R}{d} < \frac{1}{p_v}, \\ \{(e_2^2, e_2^2), (e_2^1, (\delta_2, 1 - \delta_2)^{\mathrm{T}})\} \\ \hspace{15mm} \mbox{if} \; \; \frac{R}{d} = \frac{1}{p_v}, \\ \{(e_2^2, e_2^2)\} \\ \hspace{15mm} \mbox{if} \; \; \frac{R}{d} > \frac{1}{p_v}, \end{cases}\label{eq:NEG2_1} \end{align} where $\gamma_2 \in [0, g_2(p_c / (1 + p_v p_c))]$ and $\delta_2 \in [g_2(1 / p_v), 1]$. If instead $1 - 1 / p_v \leq p_c < 1$, then \begin{align} &\mbox{NE}(G_2) = \nonumber \\ &\begin{cases} \{(e_2^1, e_2^1)\} \\ \hspace{15mm} \mbox{if} \; \; \frac{R}{d} < \frac{1}{1 + p_v p_c}, \\ \{(e_2^1, e_2^1), ((\varepsilon_1, 1 - \varepsilon_1)^{\mathrm{T}}, e_2^2)\}, \\ \hspace{15mm} \mbox{if} \; \; \frac{R}{d} = \frac{1}{1 + p_v p_c}, \\ \{(e_2^1, e_2^1), (e_2^2, e_2^2), ((\alpha_1, 1 - \alpha_1)^{\mathrm{T}}, (\alpha_2, 1 - \alpha_2)^{\mathrm{T}})\} \\ \hspace{15mm} \mbox{if} \; \; \frac{1}{1 + p_v p_c} < \frac{R}{d} < \frac{1}{p_v}, \\ \{(e_2^2, e_2^2), (e_2^1, (\delta_2, 1 - \delta_2)^{\mathrm{T}})\} \\ \hspace{15mm} \mbox{if} \; \; \frac{R}{d} = \frac{1}{p_v}, \\ \{(e_2^2, e_2^2)\} \\ \hspace{15mm} \mbox{if} \; \; \frac{R}{d} > \frac{1}{p_v}, \end{cases}\label{eq:NEG2_2} \end{align} where $\varepsilon_1 \in [0, g_1(1 / (1 + p_v p_c))]$ and $\delta_2 \in [g_2(1 / p_v), 1]$. Finally, if $0 < p_c < 1 - 1 / p_v$, then \begin{align} \mbox{NE}(G_2) = \begin{cases} \{(e_2^1, e_2^1)\} & \mbox{if} \; \; \frac{R}{d} < \frac{1}{p_v}, \\ \{(e_2^1, (\zeta_2, 1 - \zeta_2)^{\mathrm{T}})\} & \mbox{if} \; \; \frac{R}{d} = \frac{1}{p_v}, \\ \{(e_2^1, e_2^2)\} & \mbox{if} \; \; \frac{1}{p_v} < \frac{R}{d} < \frac{1}{1 + p_v p_c}, \\ \{((\eta_1, 1 - \eta_1)^{\mathrm{T}}, e_2^2)\} & \mbox{if} \; \; \frac{R}{d} = \frac{1}{1 + p_c p_v}, \\ \{(e_2^2, e_2^2)\} & \mbox{if} \; \; \frac{R}{d} > \frac{1}{1 + p_v p_c}, \end{cases}\label{eq:NEG2_3} \end{align} where $\zeta_2 \in [0, 1]$ and $\eta_1 \in [0, 1]$. \end{prop} \begin{proof} Because the pure strategy sets $S_1$ and $S_2$ are finite, there exists at least one Nash equilibrium in game $G_2$ in the mixed strategies~\cite{game_t}. $x_1 = (x_1^0, 1 - x_1^0)^{\mathrm{T}}$, $0 \leq x_1^0 \leq 1$ and $x_2 = (x_2^0, 1 - x_2^0)^{\mathrm{T}}$, $0 \leq x_2^0 \leq 1$ represent mixed strategies of miners~1 and 2, respectively. We denote the expected payoffs of miners~1 and 2 as $u_1(x_1, x_2)$ and $u_2(x_1, x_2)$, respectively. The difference in expected payoffs between $s_k = 1$ and $s_k = 0$ for miner $k$ is \begin{align} &u_1(e_2^2, x_2) - u_1(e_2^1, x_2) \nonumber \\ &= \frac{d}{1 + p_v p_c}\left( \left(\frac{R}{d} - \frac{1}{1 + p_v p_c}\right)\right. \nonumber \\ &\hspace{25mm}+ \left. p_vp_c\left(\frac{R}{d} - \frac{2 + p_v p_c}{1 + p_v p_c}\right)x_2^0 \right) \label{eq:dif_u1} \end{align} and \begin{align} &u_2(x_1, e_2^2) - u_2(x_1, e_2^1) \nonumber \\ &= \frac{d}{1 + p_v p_c}\left( p_v p_c \left(\frac{R}{d} - \frac{p_c}{1 + p_v p_c}\right)\right. \nonumber \\ &\hspace{25mm}+ \left. \left(\frac{R}{d} - \frac{2p_v p_c + 1}{p_v (1 + p_v p_c)}\right)x_1^0 \right). \label{eq:dif_u2} \end{align} From \eqref{eq:dif_u1} and \eqref{eq:dif_u2}, for another miner $\ell \in \mathcal{N} \setminus \{k\}$, the best response $\tilde{\beta}_k(x)$ of miner $k$ changes depending on the value range for $g_{\ell}(R / d)$. We thus consider five cases: $g_{\ell}(R / d) < 0$, $g_{\ell}(R / d) = 0$, $0 < g_{\ell}(R / d) < 1$, $g_{\ell}(R / d) = 1$, and $g_{\ell}(R / d) > 1$. When $0 < g_{\ell}(R/d) < 1$, the sign of the difference between miner $k$'s expect payoff for $s_k = 1$ and $s_k = 0$ changes depending on the value of $x_{\ell}^0$ as follows\footnote{We present the case where $k = 1$ and $\ell = 2$, but the same applies when $k = 2$ and $\ell = 1$.}. \begin{equation} \begin{cases} u_k(e_2^2, x_{\ell}) - u_k(e_2^1, x_{\ell}) < 0 & \mbox{if} \; \; g_{\ell}(R/d) < x_{\ell}^0 \leq 1, \\ u_k(e_2^2, x_{\ell}) - u_k(e_2^1, x_{\ell}) = 0 & \mbox{if} \; \; x_{\ell}^0 = g_{\ell}(R/d), \\ u_k(e_2^2, x_{\ell}) - u_k(e_2^1, x_{\ell}) > 0 & \mbox{if} \; \; 0 \leq x_{\ell}^0 < g_{\ell}(R/d). \end{cases} \nonumber \end{equation} Therefore, the best response $\tilde{\beta}_{k}(x)$ is \begin{equation} \tilde{\beta}_k(x) = \begin{cases} \{e_2^1\} & \mbox{if} \; \; g_{\ell}(R / d) < x_{\ell}^0 \leq 1, \\ X_k & \mbox{if} \; \; x_{\ell}^0 = g_{\ell}(R/d), \\ \{e_2^2\} & \mbox{if} \; \; 0 \leq x_{\ell}^0 < g_{\ell}(R / d). \end{cases}\label{eq:bt_pat3} \end{equation} Similarly, we obtain the best response $\tilde{\beta}_{k}(x)$ depending on the value range for $g_{\ell}(R/d)$ as follows: \begin{itemize} \item When $g_{\ell}(R / d) < 0$, \begin{equation} \tilde{\beta}_k(x) = \{e_2^1\}. \label{eq:bt_pat1} \end{equation} \item When $g_{\ell}(R / d) = 0$, \begin{equation} \tilde{\beta}_k(x) = \begin{cases} X_k & \mbox{if} \; \; x_{\ell}^0 = 0, \\ \{e_2^1\} & \mbox{if} \; \; 0 < x_{\ell}^0 \leq 1. \end{cases}\label{eq:bt_pat2} \end{equation} \item When $g_{\ell}(R / d) = 1$, \begin{equation} \tilde{\beta}_k(x) = \begin{cases} X_k & \mbox{if} \; \; x_{\ell}^0 = 1, \\ \{e_2^2\} & \mbox{if} \; \; 0 \leq x_{\ell}^0 < 1. \end{cases}\label{eq:bt_pat4} \end{equation} \item When $g_{\ell}(R / d) > 1$, \begin{equation} \tilde{\beta}_k(x) = \{e_2^2\}. \label{eq:bt_pat5} \end{equation} \end{itemize} We next derive the range of $R/d$ satisfying $0 < g_k(R/d) < 1, \, k = 1, 2$. From \eqref{eq:gz1} and \eqref{eq:gz2}, it is easily shown that $g_1$ and $g_2$ are monotonically increasing functions. Therefore, we obtain \begin{align} &0 < g_1(R / d) < 1 \Rightarrow \frac{p_c}{1 + p_v p_c} < \frac{R}{d} < \frac{1}{p_v}, \label{eq:g1_range} \\ &0 < g_2(R/d) < 1 \Rightarrow \frac{1}{1 + p_v p_c} < \frac{R}{d} < 1. \label{eq:g2_range} \end{align} Assuming $p_v \geq 1$, the magnitude relationship among $p_c/(1 + p_v p_c)$, $1 / p_v$, $1 / (1 + p_v p_c)$, and $1$ depends on the value of $p_c$, as follows: \begin{enumerate} \item When $p_c \geq 1$, \label{enu:case1} \begin{equation} \frac{1}{1 + p_v p_c} \leq \frac{p_c}{1 + p_v p_c} < \frac{1}{p_v} \leq 1. \nonumber \end{equation} \item When $1 - 1/p_v \leq p_c < 1$, \label{enu:case2} \begin{equation} \frac{p_c}{1 + p_v p_c} < \frac{1}{1 + p_v p_c} \leq \frac{1}{p_v} \leq 1. \nonumber \end{equation} \item When $0 < p_c < 1 - 1/p_v$, \label{enu:case3} \begin{equation} \frac{p_c}{1 + p_v p_c} < \frac{1}{p_v} < \frac{1}{1 + p_v p_c} < 1. \nonumber \end{equation} \end{enumerate} We derive the set of Nash equilibria in the case of \ref{enu:case1}). Then, we have nine cases depending on the value range of $R/d$. Table~\ref{tab:rdnash} shows the relation between $R/d$ and the set of Nash equilibria. Therefore, \eqref{eq:NEG2_1} is the set of Nash equilibria. We can similarly prove \eqref{eq:NEG2_2} and \eqref{eq:NEG2_3}. \end{proof} \begin{table*}[t] \centering \caption{Relation between $R/d$ and the set of Nash equilibria.} \begin{tabular}{|c|c|c|c|}\hline $R/d$ value & $\alpha_1$ & $\alpha_2$ & Set of Nash equilibria \\ \hline $0 < R/d < 1 / (1 + p_v p_c)$ & $\alpha_1 < 0$ & $\alpha_2 < 0$ & $\{(e_2^1, e_2^1)\}$ \\ $R/d = 1 / (1 + p_v p_c)$ & $\alpha_1 < 0$ & $\alpha_2 = 0$ & $\{(e_2^1, e_2^1)\}$ \\ $1 / (1 + p_v p_c) < R / d < p_c / (1 + p_v p_c)$ & $\alpha_1 < 0$ & $0 < \alpha_2 < 1$ & $\{(e_2^1, e_2^1)\}$ \\ $R/d = p_c / (1 + p_v p_c)$ & $\alpha_1 = 0$ & $0 < \alpha_2 < 1$ & $\{(e_2^1, e_2^1), (e_2^2, (\gamma_2, 1 - \gamma_2)^{\mathrm{T}})\}, \; \; \gamma_2 \in [0, g_2(p_c/(1 + p_v p_c))]$ \\ $p_c / (1 + p_v p_c) < R / d < 1 / p_v$ & $0 < \alpha_1 < 1$ & $0 < \alpha_2 < 1$ & $\{(e_2^1, e_2^1), (e_2^2, e_2^2), ((\alpha_1, 1 - \alpha_1)^{\mathrm{T}}, (\alpha_2, 1 - \alpha_2)^{\mathrm{T}})\}$ \\ $R/d = 1 / p_v$ & $\alpha_1 = 1$ & $0 < \alpha_2 < 1$ & $\{(e_2^2, e_2^2), (e_2^1, (\delta_2, 1 - \delta_2)^{\mathrm{T}})\}, \; \; \delta_2 \in [g_2(1 / p_v), 1]$ \\ $1 / p_v < R / d < 1$ & $\alpha_1 > 1$ & $0 < \alpha_2 < 1$ & $\{(e_2^2, e_2^2)\}$ \\ $R/d = 1$ & $\alpha_1 > 1$ & $\alpha_2 = 1$ & $\{(e_2^2, e_2^2)\}$ \\ $R/d > 1$ & $\alpha_1 > 1$ & $\alpha_2 > 1$ & $\{(e_2^2, e_2^2)\}$ \\ \hline \end{tabular} \label{tab:rdnash} \end{table*} For a given $p_v$, $p_c$ affects change in the Nash equilibria depending on $R/d$. Fig.~\ref{fig:pcR} shows the $p_c-R/d$ parameter plane where $p_v \geq 1$ is fixed. If the pair $(p_c, R/d)$ is in region~(a), (b), (c), or (d), set $\mbox{NE}(G_2)$ satisfies $\mbox{NE}(G_2) = \{(e_2^2, e_2^2)\}$, $\mbox{NE}(G_2) = \{(e_2^1, e_2^1), (e_2^2, e_2^2), ((\alpha_1, 1 - \alpha_1)^{\mathrm{T}}, (\alpha_2, 1 - \alpha_2)^{\mathrm{T}})\}$, $\mbox{NE}(G_2) = \{(e_2^1, e_2^1)\}$, or $\mbox{NE}(G_2) = \{(e_2^1, e_2^2)\}$, respectively\footnote{$\mbox{NE}(G_2)$ for the boundary between regions~(a) and (b) is given by the fourth equation in \eqref{eq:NEG2_1} and the fourth equation in \eqref{eq:NEG2_2}. Similarly, $\mbox{NE}(G_2)$ for the boundaries of regions~(b) and (c), (c) and (d), and (d) and (a) are given by the second equation in \eqref{eq:NEG2_1} if $p_c \geq 1$ and the second equation in \eqref{eq:NEG2_2} if $1 - 1/p_v < p_c < 1$, the second equation in \eqref{eq:NEG2_3}, and the fourth equation in \eqref{eq:NEG2_3}, respectively. $\mbox{NE}(G_2)$ when the pair $(p_c, R/d) = (1 - 1/p_v, 1/p_v)$ is given by $\mbox{NE}(G_2) = \{((\varepsilon_1, 1 - \varepsilon_1)^{\mathrm{T}}, e_2^2), (e_2^1, (\delta_2, 1 - \delta_2)^{\mathrm{T}})\}$, where $\varepsilon_1 \in [0, 1]$ and $\delta_2 \in [0, 1]$.}. \begin{figure}[tb] \centering \includegraphics[clip, width = 7.5cm]{./fig/theo/pcR_1.eps} \caption{The $p_c-R/d$ parameter plane where $p_v \geq 1$ is fixed.} \label{fig:pcR} \end{figure} Figs.~\ref{fig:eq_1}--\ref{fig:eq_3} show the relation between $R/d$ and $x_k^0$ ($k = 1, 2$) in Nash equilibria. The blue (left) and red (right) lines represent values for $x_1^0$ and $x_2^0$, respectively. \begin{figure}[tb] \centering \includegraphics[clip, width = 7.5cm]{./fig/theo/theo_2_0.8.eps} \caption{The case when $(p_v, p_c) = (2, 0.8)$.} \label{fig:eq_1} \end{figure} Fig.~\ref{fig:eq_1} shows the case where $p_c > 1 - 1/p_v$ is fixed. Consider the case where $1 - 1/p_v < p_c < 1$. The pure strategy profile $s = (0, 0)$ is a Nash equilibrium if $R/d$ is smaller than $1/p_v$. If $R/d$ is larger than $1/p_v$, the pure Nash equilibrium $s = (0, 0)$ disappears and only the pure strategy profile $s = (1, 1)$ is a Nash equilibrium. The pure strategy profile $s = (1, 1)$ is a Nash equilibrium if $R/d$ is larger than $1/(1 + p_v p_c)$. If $R/d$ is smaller than $1/(1 + p_v p_c)$, the pure Nash equilibrium $s = (1, 1)$ disappears and only the pure strategy profile $s = (0, 0)$ is a Nash equilibrium. This change in Nash equilibria due to change in $R/d$ implies that when the mining reward exceeds some value, all miners will decide to participate in the mining, after which they continue for a while even if the reward decreases to the boundary of region~(b). Thus, a hysteresis phenomenon exists in the region. Moreover, a jump phenomenon regarding the strategy profiles miners choose occurs owing to the disappearance of Nash equilibria when the reward changes across the region boundary. \begin{figure}[tb] \centering \includegraphics[clip, width = 7.5cm]{./fig/theo/theo_2_0.5.eps} \caption{The case when $(p_v, p_c) = (2, 0.5)$.} \label{fig:eq_2} \end{figure} Fig.~\ref{fig:eq_2} shows the case where $p_c = 1 - 1/p_v$. A transition from region~(c) to (a), that is, a jump from one pure strategy profile to another, is observed when $R/d$ equals $1/p_v = 1/(1 + p_v p_c)$. This transition is only seen when $p_c = 1 - 1 / p_v$. \begin{figure}[tb] \centering \includegraphics[clip, width = 7.5cm]{./fig/theo/theo_2_0.2.eps} \caption{The case when $(p_v, p_c) = (2, 0.2)$.} \label{fig:eq_3} \end{figure} Fig.~\ref{fig:eq_3} shows the case where $p_c < 1 - 1/p_v$ is fixed. The pure strategy profile $s = (0, 1)$ is a Nash equilibrium if $1/p_v < R/d < 1/(1 + p_v p_c)$. Two pure Nash equilibria do not coexist in the interior of each region while mixed strategy profile $(e_2^1, (\zeta_2, 1 - \zeta_2)^{\mathrm{T}})$ and $((\eta_1, 1 - \eta_1)^{\mathrm{T}}, e_2^2)$ are Nash equilibria on the boundary $R/d = 1/p_v$ and $R/d = 1/(1 + p_v p_c)$. \section{Numerical Analysis}\label{sec:numerical_a} In this section, we use Gambit~\cite{gambit} to numerically calculate Nash equilibria for the game $G_n$ with $n > 2$. We estimate $c_k = c$ and $f_k(c) = vc, \, v > 0$ for all $k \in \mathcal{N}$\footnote{In this example, all miners calculate the same number of hash queries per unit operating time.}. From \eqref{eq:utility} and these assumptions, $U_k(s)$ can be rewritten as \begin{equation} U_k(s) = \begin{cases} 0 & \mbox{if} \; \; s = (0, \ldots, 0), \\ \frac{s_k}{\sum_{i \in \mathcal{N}} s_i} \left(R - \frac{d}{\sum_{i \in \mathcal{N}} s_i}\right) & \mbox{otherwise}, \end{cases}\nonumber \end{equation} where $d \coloneqq D/v$. Value $d$ is fixed to 100 and set $R \in \{0, 1, \ldots, 150\}$. We calculate Nash equilibria for each $R$ when the number of miners $n$ is 2, 3, 4, 5, and 6. \begin{figure}[tb] \centering \includegraphics[clip, width = 7.5cm]{./fig/num/alpha_agent_all.eps} \caption{Relation between $R/d$ and $x_k^0$ in Nash equilibria for each the number of miners $n$.} \label{fig:num_1} \end{figure} Fig.~\ref{fig:num_1} shows the relation between $R/d$ and $x_k^0$ in Nash equilibria for numbers of miners $n = 2, 3, 4, 5, 6$. This result shows that both the hysteresis phenomena and the jump phenomenon of the strategy profiles can be observed regardless of the number of miners when all miners pay the same cost and calculate the same number of hash queries per unit operating time. In addition, this implies that as the number of miners increases, $R/d$ for the appearance of a Nash equilibrium $s = (1, \ldots, 1)$ decreases. \begin{figure}[tb] \centering \includegraphics[clip, width = 7.5cm]{./fig/num/bif_10.eps} \caption{Relation between number of miners and $R/d$ when the Nash equilibrium $s = (1, \ldots, 1)$ appears.} \label{fig:num_2} \end{figure} Fig.~\ref{fig:num_2} shows the relation between the number of miners and $R/d$ when the Nash equilibrium $s = (1, \ldots, 1)$ appears. The figure shows that $R/d$ when the equilibrium $s = (1, \ldots, 1)$ appears is inversely proportional to the number of miners $n$. This result shows that once miners decide to participate in the mining, they continue to mine for smaller rewards as their number increases. Thus, it is very important when designing blockchain networks to set the largest possible initial reward as an incentive for mining in the network. The reward can later be decreased, after the number of participating miners increases, without decreasing their number. \section{Conclusion}\label{sec:conclusion} Modeling a decision-making problem for mining participation as a noncooperative game, we showed that hysteresis phenomena due to the coexistence of two pure Nash equilibria and jump phenomena in the choice of strategy profiles can be observed with changes in the mining reward. Moreover, numerical calculations showed that miners continue mining for smaller rewards as their number increases. In general, it is difficult to analyze the miner behavior as $n$ increases. In future work we will theoretically analyze Nash equilibria by deriving a macro model of the group of the miners.
{'timestamp': '2020-12-15T02:06:40', 'yymm': '2010', 'arxiv_id': '2010.05370', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05370'}
arxiv
\section{#1}} \newcommand{\Subsection}[1]{\subsection{#1}} \newcommand{\Subsubsection}[1]{\noindent \textbf{#1.}~~~~~~} \newcommand{\SUBsubsection}[1]{\vspace*{\medskipamount} \noindent $\bullet$ {\em #1}~~~~~~ \newcommand{\Subsubsubsection}[1]{\vspace*{\medskipamount} \noindent $\bullet$ \textbf{#1}~~~~~~} \newcommand{\cg}[1]{#1 \newcommand{\cgr}[1]{#1 \newcommand{\cgred}[1]{#1 \usepackage[utf8]{inputenc} \begin{document} % \title{Self-Stabilizing Indulgent Zero-degrading Binary Consensus} \author{Oskar Lundstr\"om~\thanks{Department of Computer Science and Engineering, Chalmers University of Technology, Gothenburg, SE-412 96, Sweden, E-mail: \texttt{[email protected]}.} \and Michel Raynal~\thanks{Institut Universitaire de France IRISA, ISTIC Universit\'{e} de Rennes, Rennes cedex, 35042, France, and Polytechnic University, Hong Kong. E-mail: \texttt{[email protected]}.} \and Elad M.\ Schiller~\thanks{Department of Computer Science and Engineering, Chalmers University of Technology, Gothenburg, SE-412 96, Sweden, E-mail: \texttt{[email protected]}.}} \maketitle \begin{abstract} Guerraoui proposed an indulgent solution \ems{for the binary consensus problem. Namely,} he showed that an arbitrary behavior of the failure detector never violates safety requirements even if it compromises liveness. Consensus implementations are often used in a repeated manner. Dutta and Guerraoui proposed a zero-degrading solution, \emph{i.e.,}\xspace during system runs in which the failure detector behaves perfectly, a node failure during one consensus instance has no impact on the performance of future instances. Our study, which focuses on indulgent zero-degrading binary consensus, aims at the design of an even more robust communication abstraction. We do so through the lenses of \emph{self-stabilization}---a very strong notion of fault-tolerance. In addition to node and communication failures, self-stabilizing algorithms can recover after the occurrence of \emph{arbitrary transient faults}; these faults represent any violation of the assumptions according to which the system was designed to operate (as long as the algorithm code stays intact). This work proposes the first, to the best of our knowledge, self-stabilizing algorithm for indulgent zero-degrading binary consensus for time-free message-passing systems prone to detectable process failures. The proposed algorithm has an $\mathcal{O}\xspace(1)$ stabilization time (in terms of asynchronous cycles) from arbitrary transient faults. \remove{Moreover, the communication costs of our algorithm are similar to the ones of the non-self-stabilizing solution by Guerraoui and Raynal. The main difference is that our proposal uses repeated communications until the consensus object is deactivated.} Since the proposed solution uses an $\Omega$ failure detector, we also present the first, to the best of our knowledge, self-stabilizing asynchronous $\Omega$ failure detector, which is a variation on the one by Most{\'{e}}faoui, Mourgaya, and Raynal. \end{abstract} \Section{Introduction} \label{sec:intro} We propose a self-stabilizing implementation of \emph{binary consensus} objects for time-free (aka asynchronous) message-passing systems whose nodes may fail-stop. We also show a self-stabilizing asynchronous construction of eventual leader failure detector, $\Omega$. \Subsection{Background and motivation} With the information revolution, everything became connected, \emph{e.g.,}\xspace banking services, online reservations, e-commerce, IoTs, automated driving systems, to name a few. All of these applications are distributed, use message-passing systems, and require fault-tolerant implementations. Designing and verifying these systems is notoriously difficult since the system designers have to cope with their asynchronous nature and the presence of failures. The combined presence of failures and asynchrony creates uncertainties (from the perspective of individual processes) with respect to the application state. Indeed, Fischer, Lynch, and Paterson~\cite{DBLP:journals/jacm/FischerLP85} showed that, in the presence of at least one (undetectable) process crash, there is no deterministic algorithm for determining the state of an asynchronous message-passing system in a way that can be validly agreed on by all non-faulty processes. This work is motivated by applications whose state is replicated over several processes in a way that emulates a finite-state machine. In order to maintain consistent replicas, each process has to apply the same sequence of state-transitions according to different sources of (user) input. To this end, one can divide the problem into two: (i) propagate the user input to all replicas, and (ii) let each replica perform the same sequence of state-transitions. The former challenge can be rather simply addressed via uniform reliable broadcast~\cite{DBLP:books/sp/Raynal18,hadzilacos1994modular}, whereas the latter one is often considered to be at the problem core since it requires all processes to agree on a common value, \emph{i.e.,}\xspace the order in which all replicas apply their state transitions. In other words, the input must be totally ordered before delivering it to the emulated automaton. It was observed that the agreement problem of item (ii) can be generalized. Namely, the consensus problem requires each process to propose a value, and all non-faulty processes to agree on a single decision, which must be one of the proposed values. The problem of fault-tolerant consensus was studied extensively in the context of time-free message passing-systems. The goal of our work is to broaden the set of failures that such solutions can tolerate. \Subsection{Problem definition and scope} Definition~\ref{def:consensus} states the consensus problem. When the set, $V$, of values that can be proposed, includes just two values, the problem is called binary consensus. Otherwise, it is called multivalued consensus. Existing solutions for multivalued consensus often use binary consensus algorithms. Figure~\ref{fig:suit} depicts the relation to other problems in the area, which were mentioned earlier. \begin{figure} \begin{center} }%{\vspace*{-\bigskipamount}\BBB \includegraphics[scale=0.4, clip]{arcCrop.pdf} \end{center} }%{\vspace*{-\bigskipamount}\ \caption{\label{fig:suit}{The studied problem \reduce{of binary consensus} (in bold) in the context of a relevant protocol suite}.} }%{\vspace*{-\bigskipamount}}%{\vspace*{-\medskipamount} \end{figure} \begin{definition}[The consensus problem] % \label{def:consensus} % Every process $p_i$ has to propose a value $v_i \in V$ via an invocation of the $\mathsf{propose}_i(v_i)$ operation, where $V$ is a finite set of values. Let $\mathit{Alg}$ be an algorithm that solves consensus. $\mathit{Alg}$ has to satisfy \emph{safety} (\emph{i.e.,}\xspace validity, integrity, and agreement) and \emph{liveness} (\emph{i.e.,}\xspace termination). \begin{itemize \item \textbf{Validity.} Suppose that $v$ is decided. Then, $\mathsf{propose}(v)$ was invoked by some process. \item \textbf{Integrity.} Suppose a process decides. It does so at most once. \item \textbf{Agreement.} No two processes decide different values. \item \textbf{Termination.} All non-faulty processes decide. \end{itemize} \end{definition} As mentioned earlier, consensus cannot be solved in asynchronous message-passing systems that are prone to failures, as weak as even the crash of a single process~\cite{DBLP:journals/jacm/FischerLP85}. Unreliable failure detectors~\cite{DBLP:journals/jacm/ChandraT96} are often used to circumvent such impossibilities. For a given failure detector class, Guerraoui~\cite{DBLP:conf/podc/Guerraoui00} proposed an indulgent solution, namely, he showed that an arbitrary behavior of the failure detector never violates safety requirements even if it compromises liveness. Consensus implementations are often used in a repeated manner. Dutta and Guerraoui~\cite{DBLP:conf/edcc/DuttaG02} proposed a zero-degrading solution, \emph{i.e.,}\xspace during system runs in which the failure detector behaves perfectly, a failure during one consensus instance has no impact on the performance of future instances. We study solutions for indulgent zero-degrading binary consensus. \Subsection{Fault Model} We study a time-free message-passing system that has no guarantees on the communication delay and the algorithm cannot explicitly access the local clock. Our fault model includes $(i)$ detectable fail-stop failures of processes, and $(ii)$ communication failures, such as packet omission, duplication, and reordering. In addition to the failures captured in our model, we also aim to recover from \emph{arbitrary transient faults}, \emph{i.e.,}\xspace any temporary violation of assumptions according to which the system and network were designed to operate, \emph{e.g.,}\xspace the corruption of control variables, such as the program counter, packet payload, and indices, \emph{e.g.,}\xspace sequence numbers, which are responsible for the correct operation of the studied system, as well as operational assumptions, such as that at least a majority of nodes never fail. Since the occurrence of these failures can be arbitrarily combined, we assume that these transient faults can alter the system state in unpredictable ways. In particular, when modeling the system, we assume that these violations bring the system to an arbitrary state from which a \emph{self-stabilizing algorithm} should recover the system. \Subsection{Related Work} The celebrated Paxos algorithm~\cite{DBLP:journals/tocs/Lamport98} circumvents the impossibility by Fischer, Lynch, and Paterson~\cite{DBLP:journals/jacm/FischerLP85} by assuming that failed computers can be detected by unreliable failure detectors~\cite{DBLP:journals/jacm/ChandraT96}. These detectors can eventually notify the algorithm about the set of computers that were recently up and connected. However, there is no bound on the time that it takes the algorithm to receive a correct version of this notification. It is worth mentioning that Paxos has inspired many veins of research, \emph{e.g.,}\xspace~\cite[and references therein]{DBLP:journals/csur/RenesseA15}. We, however, follow the family of abstractions by Raynal~\cite{DBLP:books/sp/Raynal18} due to its clear presentation that is easy to grasp as well as the fact that it can facilitate efficient implementations. \Subsubsection{Non-self-stabilizing solutions} The $\Omega$ class includes eventual leader failure detectors. Chandra, Hadzilacos, and Toueg~\cite{DBLP:journals/jacm/ChandraHT96} defined this class and showed that it is the weakest for solving consensus in asynchronous message-passing systems while assuming that at most a minority of the nodes may fail. In this work we study the $\Omega$ failure detector by Most{\'{e}}faoui, Mourgaya, and Raynal~\cite{DBLP:conf/dsn/MostefaouiMR03}. We note the existence of a computationally equivalent $\Omega$ failure detector by Aguilera \emph{et al.}\xspace~\cite{DBLP:conf/podc/AguileraDFT04}, which explicitly accesses timers. Our study focuses on~\cite{DBLP:conf/dsn/MostefaouiMR03} since it is asynchronous. Guerraoui~\cite{DBLP:conf/podc/Guerraoui00} presented the design criterion of indulgence. Guerraoui and Lynch~\cite{DBLP:conf/sss/GuerraouiL06} studied this criterion formally. Raynal~\cite{DBLP:journals/tc/GuerraouiR04,DBLP:journals/cj/GuerraouiR07} generalized it and designed indulgent $\Omega$-based consensus algorithms. Dutta and Guerraoui~\cite{DBLP:conf/edcc/DuttaG02} introduced the zero-degradation criterion. The studied algorithm is by Guerraoui and Raynal~\cite{DBLP:journals/tc/GuerraouiR04} who presented an indulgent zero-degrading consensus algorithm for message-passing systems in which the majority of the nodes never fail, and $\Omega$-failure detectors are available. We have selected this algorithm due to its clear presentation and the fact that it matches the ``two rounds'' lower bound by Keidar and Rajsbaum~\cite{DBLP:journals/ipl/KeidarR03}. Hurfin \emph{et al.}\xspace~\cite{DBLP:journals/tc/HurfinMR02} showed that zero-degradation can be combined with the versatile use of a family of failure detector for improving the efficiency of round-based consensus algorithms. Wu \emph{et al.}\xspace~\cite{DBLP:journals/jpdc/WuCYR08} presented the notion of round-zero-degradation, which extend zero-degradation, and the notation of look-head. They presented algorithms that extend the ones by Hurfin \emph{et al.}\xspace and can reduce the number of required rounds. We note that such extensions are also plausible for our solutions. \Subsubsection{Self-stabilizing solutions} We follow the design criteria of self-stabilization, which Dijkstra~\cite{DBLP:journals/cacm/Dijkstra74} proposed. A detailed pretension of self-stabilization was provided by Dolev~\cite{DBLP:books/mit/Dolev2000} and Altisen \emph{et al.}\xspace~\cite{DBLP:series/synthesis/2019Altisen}. Blanchard \emph{et al.}\xspace~\cite{DBLP:conf/netys/BlanchardDBD14} have a self-stabilizing failure detector for partially synchronous systems. They mention the class P of perfect failure detectors. Indeed, there is a self-stabilizing asynchronous failure detector for class P by Beauquier and Kekkonen{-}Moneta~\cite{DBLP:journals/ijsysc/BeauquierK97} and a self-stabilizing synchronous $\Omega$ failure detector by Delporte{-}Gallet, Devismes, and Fauconnier~\cite{DBLP:conf/sss/Delporte-GalletDF07}. We present the first, to the best of our knowledge, asynchronous $\Omega$ failure detector. Hutle and Widder~\cite{DBLP:conf/sss/HutleW05} present an impossibility result that connects fault detection, self-stabilization, and time-freedom as well as link capacity and local memory bounds. They explain how randomization can circumvent this impossibility for eventually perfect failure detector~\cite{DBLP:conf/pdcn/HutleW05}. Biely \emph{et al.}\xspace~\cite{DBLP:conf/sss/BielyHPW07} connect between classes of deterministic failure detectors, self-stabilization, and synchrony assumptions. We follow the assumption made by Most{\'{e}}faoui, Mourgaya, and Raynal~\cite{DBLP:conf/dsn/MostefaouiMR03} regarding communication patterns, which is another way to circumvent such impossibilities. The consensus problem was not extensively studied in the context of self-stabilization. The notable exceptions are by Dolev \emph{et al.}\xspace~\cite{DBLP:journals/jcss/DolevKS10} and Blanchard \emph{et al.}\xspace~\cite{DBLP:conf/netys/BlanchardDBD14}, which presented the first practically-self-stabilizing solutions for share-memory and message-passing systems, respectively. We note that practically-self-stabilizing systems, as defined by Alon \emph{et al.}\xspace~\cite{DBLP:journals/jcss/AlonADDPT15}\reduce{ and clarified by Salem and Schiller~\cite{DBLP:conf/netys/SalemS18}}, do not satisfy Dijkstra's requirements, \emph{i.e.,}\xspace practically-self-stabilizing systems do not guarantee recovery within a finite time after the occurrence of transient faults. Moreover, the message size of Blanchard \emph{et al.}\xspace is polynomial in the number of processes, whereas ours is a constant (that depends on the number of bits it takes to represent a process identifier). The origin of the design criteria of practically-self-stabilizing systems can be traced back to Dolev \emph{et al.}\xspace~\cite{DBLP:journals/jcss/DolevKS10}, who provided a practically-self-stabilizing solution for the consensus problem in shared memory systems, whereas we study message-passing systems. \reduce{It is worth mentioning that the work of Blanchard \emph{et al.}\xspace has lead to the work of Dolev \emph{et al.}\xspace~\cite{DBLP:journals/jcss/DolevGMS18}, which considers a practically-self-stabilizing emulation of state-machine replication, which has the same task of the state-machine replication in Figure~\ref{fig:suit}. However, Dolev \emph{et al.}\xspace's solution is based on virtual synchrony by Birman and Joseph~\cite{DBLP:journals/tocs/BirmanJ87}, where the one in Figure~\ref{fig:suit} consider censuses. We also note that earlier self-stabilizing algorithms for state-machine replications were based on group communication systems and assumed execution fairness~\cite{DBLP:journals/tpds/DolevS03,DBLP:journals/acta/DolevS04,DBLP:journals/tmc/DolevSW06}.} There are other self-stabilizing algorithms that are the result of transformations of non-self-stabilizing yet solutions, such as for atomic snapshots~\cite{DBLP:conf/netys/GeorgiouLS19}, uniform reliable broadcast~\cite{selfStabURB}, set-constraint delivery broadcast~\cite{DBLP:conf/icdcs/ICDCS2020} and coded atomic storage~\cite{DBLP:journals/corr/abs-1806-03498}. \Subsection{Our contribution} We present a fundamental module for dependable distributed systems: a self-stabilizing algorithm for indulgent zero-degrading binary consensus for time-free message-passing systems that are prone to detectable node fail-stop failures. The design criteria of indulgence and zero-degradation are essential for facilitating efficient distributed replication systems and self-stabilization is imperative for significantly advancing the fault-tolerance degree of future replication systems. \ems{Indulgence means that the safety properties, \emph{e.g.,}\xspace agreement, are never compromised even if the underlying model assumptions are never satisfied. Zero-degrading means that the process failures that occurred before the algorithm starts have no impact on its efficiency, which depends only on the failure pattern that occur during the system run.} To the best of our knowledge, we are the first to provide a solution for binary consensus that is indulgent, zero-degrading and can tolerate a fault model as broad as ours. Our model includes detectable fail-stop failures, communication failures, such as packet omission, duplication, and reordering as well as arbitrary transient faults. The latter can model any \ems{temporary} violation of the assumptions according to which the system was designed to operate (as long as the algorithm code stays intact). In the absence of transient faults, our solution achieves consensus within an optimal number of communication rounds (without assuming fair execution). After the occurrence of any finite number of arbitrary transient faults, the system recovers within an asymptotically optimal time (while assuming fair execution). Namely, the stabilization time is in $\mathcal{O}\xspace(1)$ (in terms of asynchronous cycles). As in Guerraoui and Raynal~\cite{DBLP:journals/tc/GuerraouiR04}, each node uses a bounded amount of memory. Moreover, the communication costs of our algorithm are similar to the non-self-stabilizing one by Guerraoui and Raynal~\cite{DBLP:journals/tc/GuerraouiR04}. The main difference is in the period after a node has decided. Then, it has to broadcast the decided value. At that time, the non-self-stabilizing solution in~\cite{DBLP:journals/tc/GuerraouiR04} terminates whereas our self-stabilizing solution repeats the broadcast until the consensus object is deactivated by the invoking algorithm. This is along the lines of a well-known impossibility~\cite[Chapter 2.3]{DBLP:books/mit/Dolev2000} \ems{stating} that self-stabilizing systems cannot terminate. Also, it is easy to trade the broadcast repetition rate with the speed of recovery from transient faults. We also propose the first, to the best of our knowledge, self-stabilizing asynchronous $\Omega$ failure detector, which is a variation on Most{\'{e}}faoui, Mourgaya, and Raynal~\cite{DBLP:conf/dsn/MostefaouiMR03}. We show transient fault recovery within the time it takes all non-crashed processes to exchange messages among themselves. The use of local memory and communication costs are asymptotically the same as the one of~\cite{DBLP:conf/dsn/MostefaouiMR03}. The key difference is that we deal with the ``counting to infinity'' scenario, which transient fault can introduce. The proposed self-stabilizing solution uses \ems{a} trade-off parameter, $\delta$, that can balance between the solution's vulnerability (to elect a crashed node as a leader even in the absence of transient faults) and the time it takes to elect a non-faulty leader (after the occurrence of the last transient fault). Note that $\delta \in \mathbb{Z}^+$ can be a predefined constant. As an extension, we also discuss how to transform the (non-self-stabilizing) randomized algorithm for binary consensus by Ben{-}Or~\cite{DBLP:conf/podc/Ben-Or83} to a self-stabilizing one (Section~\ref{sec:disc}). \reduce{ \Subsection{Organization} We state our system settings in Section~\ref{sec:sys}. Section~\ref{sec:omega} present our self-stabilizing asynchronous $\Omega$ failure detector. Section~\ref{sec:back} includes a brief overview of the earlier algorithm that has led to the proposed solution. Our self-stabilizing algorithm is proposed in Section~\ref{sec:binary}; it considers unbounded counters. \ems{The correctness proof appears in Section~\ref{sec:correctness}.} We sketch an extension and conclude in Section~\ref{sec:disc}. } \smallskip \Section{System settings} \label{sec:sys} We consider a time-free message-passing system that has no guarantees on the communication delay. Moreover, there is no notion of global (or universal) clocks and the algorithm cannot explicitly access the local clock (or timeout mechanisms). The system consists of a set, $\mathcal{P}\xspace$, of $n$ fail-prone nodes (or processors) with unique identifiers. Any pair of nodes $p_i,p_j \in \mathcal{P}\xspace$ have access to a bidirectional communication channel, $\mathit{channel}_{j,i}$, that, at any time, has at most $\mathsf{channelCapacity}\xspace \in \mathbb{N}\xspace$ packets on transit from $p_j$ to $p_i$ (this assumption is due to a well-known impossibility~\cite[Chapter 3.2]{DBLP:books/mit/Dolev2000}). In the \emph{interleaving model}~\cite{DBLP:books/mit/Dolev2000}, the node's program is a sequence of \emph{(atomic) steps}. Each step starts with an internal computation and finishes with a single communication operation, \emph{i.e.,}\xspace a message $send$ or $receive$. The \emph{state}, $s_i$, of node $p_i \in \mathcal{P}\xspace$ includes all of $p_i$'s variables and $\mathit{channel}_{j,i}$. The term \emph{system state} (or configuration) refers to the tuple $c = (s_1, s_2, \cdots, s_n)$. We define an \emph{execution (or run)} $R={c[0],a[0],c[1],a[1],\ldots}$ as an alternating sequence of system states $c[x]$ and steps $a[x]$, such that each $c[x+1]$, except for the starting one, $c[0]$, is obtained from $c[x]$ by $a[x]$'s execution. \Subsection{Task specification} \label{sec:spec} The set of \emph{legal executions} ($LE$) refers to all the executions in which the requirements of the task $T$ hold. In this work, $T_{\text{binCon}}$ denotes the task of binary consensus, which Definition~\ref{def:consensus} specifies, and $LE_{\text{binCon}}$ denotes the set of executions in which the system fulfills $T_{\text{binCon}}$'s requirements. Definition~\ref{def:consensus} considers the \ems{$\mathsf{propose}(s,k,v)$ operation. We refine the definition of $\mathsf{propose}(s,k,v)$ to include the value of $s$ and $k$ that we describe next.} Moreover, we specify how the decided value is retrieved. We clarify that it can be either via the returned value of the $\mathsf{propose}()$ operation (as in the studied algorithm~\cite{DBLP:journals/tc/GuerraouiR04}) or via the returned value of the $\mathsf{result}\xspace(s,k)$ operation (as in the proposed solution). The proposed solution is tailored for the protocol suite presented in Figure~\ref{fig:suit}. Thus, we consider multivalued consensus objects that use an array, $BC[]$, of $n$ binary consensus objects, such as the one by~\cite[Chapter 17]{DBLP:books/sp/Raynal18}, where $n=|\mathcal{P}\xspace|$ is the number of nodes in the system. Moreover, we organize these multivalued consensus objects in an array, $CS[]$, of $M$ elements, where $M \in \mathbb{Z}^+$ is a predefined constant. We note that in case the algorithm that uses $CS[]$ runs out of consensus objects, a global restart procedure can be invoked, such as the one in~\cite{DBLP:conf/netys/GeorgiouLS19}, Section~5. Thus, it is possible to have bounded sequence numbers for multivalued objects. \Subsection{The fault model and self-stabilization A failure occurrence is a step that the environment takes rather than the algorithm. \Subsubsection{Benign failures} \label{sec:benignFailures} When the occurrence of a failure cannot cause the system execution to lose legality, \emph{i.e.,}\xspace to leave $LE$, we refer to that failure as a benign one. The studied consensus algorithms are prone to \emph{fail-stop failures}, in which nodes stop taking steps. We assume that at most $t<|P|/2$ node may fail and that unreliable failure detectors~\cite{DBLP:journals/jacm/ChandraT96} can detect these failures. The studied failure detector constructions consider (undetectable) \emph{crash failures}. We consider solutions that are oriented towards time-free message-passing systems and thus they are oblivious to the time in which the packets arrive and depart. We assume that any message can reside in a communication channel only for a finite period. Also, the communication channels are prone to packet failures, such as omission, duplication, reordering. However, if $p_i$ sends a message infinitely often to $p_j$, node $p_j$ receives that message infinitely often. We refer to the latter as the \emph{fair communication} assumption. \Subsubsection{Arbitrary transient faults} \label{sec:arbitraryTransientFaults} We consider any temporary violation of the assumptions according to which the system was designed to operate. We refer to these violations and deviations as \emph{arbitrary transient faults} and assume that they can corrupt the system state arbitrarily (while keeping the program code intact). The occurrence of an arbitrary transient fault is rare. Thus, our model assumes that the last arbitrary transient fault occurs before the system execution starts~\cite{DBLP:books/mit/Dolev2000}. Also, it leaves the system to start in an arbitrary state. \Subsubsection{Dijkstra's self-stabilization criterion} \label{sec:Dijkstra} An algorithm is \textit{self-stabilizing} with respect to the task of $LE$, when every (unbounded) execution $R$ of the algorithm reaches within a finite period a suffix $R_{legal} \in LE$ that is legal. Namely, Dijkstra~\cite{DBLP:journals/cacm/Dijkstra74} requires $\forall R:\exists R': R=R' \circ R_{legal} \land R_{legal} \in LE \land |R'| \in \mathbb{Z}^+$, where the operator $\circ$ denotes that $R=R' \circ R''$ concatenates $R'$ with $R''$. \Subsubsection{Complexity Measures} \label{sec:timeComplexity} The complexity measure of self-stabilizing systems, called \emph{stabilization time}, is the time it takes the system to recover after the occurrence of the last transient fault. Next, we provide the assumptions needed for defining this period. We \emph{do not assume} execution fairness in the absence of transient faults. We say that a system execution is \emph{fair} when every step that is applicable infinitely often is executed infinitely often and fair communication is kept. After the occurrence of the last transient fault, we assume the system execution is \emph{temporarily} fair until the system reaches a legal execution, as in Georgiou \emph{et al.}\xspace~\cite{DBLP:conf/netys/GeorgiouLS19}. Since asynchronous systems do not consider the notion of time, we use the term (asynchronous) cycles as an alternative way to measure the period between two system states in a fair execution. The first (asynchronous) cycle (with round-trips) of a fair execution $R=R' \circ R''$ is the shortest prefix $R'$ of $R$, such that each non-failing node executes at least one complete iteration (of the do forever loop) in $R'$. The second cycle in $R$ is the first cycle in $R''$, and so on. We clarify the term complete iteration (of the do forever loop). It is well-known that self-stabilizing algorithms cannot terminate their execution and stop sending messages~\cite[Chapter 2.3]{DBLP:books/mit/Dolev2000}. Moreover, their code includes a do forever loop. Let $N_i$ be the set of nodes with whom $p_i$ completes a message round trip infinitely often in $R$. Suppose that immediately after the state $c_{begin}$, node $p_i$ takes a step that includes the execution of the first line of the do forever loop, and immediately after system state $c_{end}$, it holds that: (i) $p_i$ has completed the iteration of $c_{begin}$ and (ii) every request message $m$ (and its reply) that $p_i$ has sent to any non-failing node $p_j \in \mathcal{P}\xspace$ during the iteration (of the do forever loop) has completed its round trip. In this case, we say that $p_i$'s complete iteration starts at $c_{begin}$ and ends at $c_{end}$. \remove{ Let $N_i$ be the set of nodes with whom $p_i$ completes a message round trip infinitely often in execution $R$. % % Suppose that immediately after the state $c_{begin}$, node $p_i$ takes a step that includes the execution of the first line of the do forever loop, and immediately after system state $c_{end}$, it holds that: (i) $p_i$ has completed the iteration it has started immediately after $c_{begin}$ (regardless of whether it enters branches) and (ii) every request message $m$ (and its reply) that $p_i$ has sent to any non-failing node $p_j \in \mathcal{P}\xspace$ during the iteration has completed its round trip. % % In this case, we say that $p_i$'s complete iteration (with round-trips) starts at $c_{begin}$ and ends at $c_{end}$. \smallskip \noindent \textbf{Message round-trips and iterations of self-stabilizing algorithms.~~} \label{sec:messageRoundtrips} The correctness proof depends on the nodes' ability to exchange messages during the periods of recovery from transient faults. The proposed solution considers communications that follow the pattern of request-reply, \emph{i.e.,}\xspace $\mathsf{MSG}$ and $\mathsf{MSGack}$ messages, as well as $\mathsf{GOSSIP}$ messages for which the algorithm does not send replies. The definitions of our complexity measures use the notion of a message round-trip for the cases of request-reply messages and the term algorithm iteration. We give a detailed definition of \emph{round-trips} as follows. Let $p_i \in \mathcal{P}\xspace$ and $p_j \in \mathcal{P}\xspace \setminus \{p_i\}$. Suppose that immediately after system state $c$, node $p_i$ sends a message $m$ to $p_j$, for which $p_i$ awaits a reply. At system state $c'$, that follows $c$, node $p_j$ receives message $m$ and sends a reply message $r_m$ to $p_i$. Then, at system state $c''$, that follows $c'$, node $p_i$ receives $p_j$'s response, $r_m$. In this case, we say that $p_i$ has completed with $p_j$ a round-trip of message $m$. It is well-known that self-stabilizing algorithms cannot terminate their execution and stop sending messages~\cite[Chapter 2.3]{DBLP:books/mit/Dolev2000} that self-stabilizing systems cannot terminate. Moreover, their code includes a do forever loop. Thus, we define a \emph{complete iteration} of a self-stabilizing algorithm. Let $N_i$ be the set of nodes with whom $p_i$ completes a message round trip infinitely often in execution $R$. Moreover, assume that node $p_i$ sends a gossip message infinitely often to $p_j \in \mathcal{P}\xspace \setminus \{p_i\}$ (regardless of the message payload). Suppose that immediately after the state $c_{begin}$, node $p_i$ takes a step that includes the execution of the first line of the do forever loop, and immediately after system state $c_{end}$, it holds that: (i) $p_i$ has completed the iteration it has started immediately after $c_{begin}$ (regardless of whether it enters branches), (ii) every request-reply message $m$ that $p_i$ has sent to any node $p_j \in \mathcal{P}\xspace$ during the iteration (that has started immediately after $c_{begin}$) has completed its round trip, and (iii) it includes the arrival of at least one gossip message from $p_i$ to any non-failing $p_j \in \mathcal{P}\xspace \setminus \{p_i\}$. In this case, we say that $p_i$'s complete iteration (with round-trips) starts at $c_{begin}$ and ends at $c_{end}$. \smallskip \noindent \textbf{Cost measures: asynchronous cycles and the happened-before relation.~~} \label{ss:asynchronousCycles} We say that a system execution is \emph{fair} when every step that is applicable infinitely often is executed infinitely often and fair communication is kept. Since asynchronous systems do not consider the notion of time, we use the term (asynchronous) cycles as an alternative way to measure the period between two system states in a fair execution. The first (asynchronous) cycle (with round-trips) of a fair execution $R=R' \circ R''$ is the shortest prefix $R'$ of $R$, such that each non-failing node executes at least one complete iteration in $R'$. The second cycle in execution $R$ is the first cycle in execution $R''$, and so on. \begin{remark} % \label{ss:first asynchronous cycles} % For the sake of simple presentation of the correctness proof, when considering fair executions, we assume that any message that arrives in $R$ without being transmitted in $R$ does so within $\mathcal{O}\xspace(1)$ asynchronous cycles in $R$. \end{remark} \begin{remark}[Absence of transient faults implies no need for fairness assumptions] % \label{ss:noFairnessIsNEeeded} % In the absence of transient faults, no fairness assumptions are required in any practical settings. Also, the existing non-self-stabilizing solutions (Section~\ref{sec:back}) do not make any fairness assumption, but they do not consider recovery from arbitrary transient faults regardless of whether the execution eventually becomes fair or not. \end{remark} Lamport~\cite{DBLP:journals/cacm/Lamport78} defined the happened-before relation as the least strict partial order on events for which: (i) If steps $a, b \in R$ are taken by processor $p_i \in \mathcal{P}\xspace$, $a \rightarrow b$ if $a$ appears in $R$ before $b$. (ii) If step $a$ includes sending a message $m$ that step $b$ receives, then $a \rightarrow b$. Using the happened-before definition, one can create a directed acyclic (possibly infinite) graph $G_R:(V_R,E_R)$, where the set of nodes, $V_R$, represents the set of system states in $R$. Moreover, the set of edges, $E_R$, is given by the happened-before relation. In this paper, we assume that the weight of an edge that is due to cases (i) and (ii) are zero and one, respectively. When there is no guarantee that execution $R$ is fair, we consider the weight of the heaviest directed path between two system state $c,c' \in R$ as the cost measure between $c$ and $c'$. } \Subsection{Uniform reliable broadcast} We assume the availability of a self-stabilizing uniform reliable broadcast (URB)~\cite{selfStabURB}, which requires that if a node (faulty or not) delivers a message, then all non-failing nodes also deliver this message~\cite{hadzilacos1994modular}. The task specifications consider an operation for URB broadcasting of message $m$ and an event of URB delivery of message $m$. The requirements include URB-validity, \emph{i.e.,}\xspace there is no spontaneous creation or alteration of URB messages, URB-integrity, \emph{i.e.,}\xspace there is no duplication of URB messages, as well as URB-termination, \emph{i.e.,}\xspace if the broadcasting node is non-faulty, or if at least one receiver URB-delivers a message, then all non-failing nodes URB-deliver that message. Note that the URB-termination property considers both faulty and non-faulty receivers. This is the reason why this type of reliable broadcast is named \emph{uniform}. This work also assumes that the operation for URB broadcasting message $m$ returns a transmission descriptor, $\txD$, which is the unique message identifier. Moreover, the predicate $\mathsf{hasTerminated}\xspace(\txD)$ holds whenever the sender knows that all non-failing nodes in the system have delivered $m$. The implementation of $\mathsf{hasTerminated}\xspace(\txD)$ can just test that the local buffer does not include any record with the message identifier $\txD$. The solution in~\cite{selfStabURB} can facilitate the implementation of $\mathsf{hasTerminated}\xspace()$ since the self-stabilizing algorithm in~\cite{selfStabURB} removes obsolete records of messages that were delivered by all non-faulty receivers. \Subsection{Unreliable failure detectors} \label{sec:ext} Chandra and Toueg~\cite{DBLP:journals/jacm/ChandraT96} introduced the concepts of failure patterns and unreliable failure detectors. Chandra, Hadzilacos, and Toueg~\cite{DBLP:journals/jacm/ChandraHT96} proposed the class $\Omega$ of eventual leader failure detectors. It is known to be the weakest failure detector class to solve consensus. A pedagogical presentation of these failure detectors is given in Raynal~\cite{DBLP:books/sp/Raynal18}. \Subsubsection{Failure patterns} Any execution $R:=(c[0],a[0],c[1],a[1],\ldots)$ can have any number of failures during its run. $R$'s failure pattern is a function $F:\mathbb{Z}^+ \rightarrow 2^\mathcal{P}\xspace$, where $\mathbb{Z}^+$ refers to an index of a system state in $R$, which in some sense represents (progress over) time, and $2^\mathcal{P}\xspace$ is the power-set of $\mathcal{P}\xspace$, which represents the set of failing nodes in a given system state. $F(\tau)$ denotes the set of failing nodes in system state $c_{\tau}\in R$. Since we consider fail-stop failures, $F(\tau) \subseteq F(\tau + 1)$ holds for any $\tau \in \mathbb{Z}^+$. Denote by $\mathit{Faulty}(F)\subseteq \mathcal{P}\xspace$ the set of nodes that eventually fail-stop in the (unbounded) execution $R$, which has the failure pattern $F$. Moreover, $\mathit{Correct}(F)=\mathcal{P}\xspace \setminus \mathit{Faulty}(F)$. For brevity, we sometimes notate these sets as $\mathit{Correct}$ and $\mathit{Faulty}$. \Subsubsection{Eventual leader failure detectors} \label{sec:Omega} This class allows $p_i \in \mathcal{P}\xspace$ to access a read-only local variable $leader_i$, such that $\{leader_i\}_{1\leq i \leq n}$ satisfy the $\Omega$-validity and $\Omega$-eventual leadership requirements, where $leader^\tau_i$ denotes $leader_i$'s value in system state $c_\tau \in R$ of system execution $R$. $\Omega$-validity requires that $\forall i: \forall \tau : leader^\tau_i$ contains a node identity. $\Omega$-eventual leadership requires that $\exists \ell \in \mathit{Correct}(F), \exists c_\tau \in R: \forall \tau' \geq \tau : \forall i \in \mathit{Correct}(F): leader^{\tau'}_i= \ell$. These requirements imply that a unique and non-faulty leader is eventually elected, however, they do not specify when this occurs and how many leaders might co-exist during an arbitrarily long (yet finite) anarchy period. \ems{Moreover, no processor can detect the ending of this period of anarchy.} \remove{ Let $F$ denote a crash pattern $(F(\tau)$ is the set of processes crashed at time $\tau$), $\mathit{Faulty}(F)$ the set of processes that crash in the failure pattern $F$, and $\mathit{Correct}(F)$ the set of processes that are non-faulty in the failure pattern $F$. We assume the availability of self-stabilizing $\Theta$ failure detectors~\cite{DBLP:journals/siamcomp/AguileraCT00}, which offer local access to $\mathit{trusted}$, which is a set that satisfies the $\Theta$-accuracy and $\Theta$-liveness properties. Let $\mathit{trusted}^\tau_i$ denote $p_i$'s value of $\mathit{trusted}$ at time $\tau$. $\Theta$-accuracy is specified as $\forall p_i \in \mathcal{P}\xspace: \forall \tau \in \mathbb{Z}^+:(\mathit{trusted}^\tau_i\cap \mathit{Correct}(F))\neq \emptyset$, \emph{i.e.,}\xspace at any time, $\mathit{trusted}_i$ includes at least one non-faulty node, which may change over time. $\Theta$-liveness is specified as $\exists \tau \in \mathbb{N}: \forall \tau' \geq \tau : \forall p_i \in \mathit{Correct}(F):\mathit{trusted}^{\tau'}_i\subseteq \mathit{Correct}(F)$, \emph{i.e.,}\xspace eventually $\mathit{trusted}_i$ includes only non-faulty nodes. A self-stabilizing $\Theta$-failure detector appears in~\cite{DBLP:conf/netys/BlanchardDBD14}. We also assume the availability of a class $\mathit{HB}$ (heartbeat) self-stabilizing failure detectors~\cite{DBLP:journals/siamcomp/AguileraCT00}, which has the $\mathit{HB}$-completeness and $\mathit{HB}$-liveness properties. Let $\mathit{HB}_i^\tau[j]$ be $p_i$'s value of the $j$-th entry in the array $\mathit{HB}$ at time $\tau$. $\mathit{HB}$-completeness is specified as $\forall p_i \in \mathit{Correct}(F), \forall p_j \in \mathit{Faulty}(F): \exists K: \forall \tau \in \mathbb{N}: \mathit{HB}_i^\tau[j] < K$, \emph{i.e.,}\xspace any faulty node is eventually suspected by every non-failing node. $\mathit{HB}$-liveness is specified as (1) $\forall p_i, p_j \in \mathcal{P}\xspace: \forall \tau \in \mathbb{N}: \mathit{HB}_i^\tau[j] \leq \mathit{HB}_i^{\tau+1}[j]$, and (2) $\forall p_i,p_j \in \mathit{Correct}(F): \forall K: \exists \tau \in \mathbb{Z}^+:\mathit{HB}_i^\tau[j] > K$. In other words, there is a time after which only the faulty nodes are suspected. The implementation of the $\mathit{HB}$ failure detector that appears in~\cite{DBLP:conf/wdag/AguileraCT97} and~\cite[Chapter 3.5]{DBLP:books/sp/Raynal18} uses unbounded counters. A self-stabilizing variation of this mechanism can simply let $p_i \in \mathcal{P}\xspace$ to send $\mathsf{HEARTBEAT}(\mathit{HB}_i[i], \mathit{HB}_i[j])$ messages to all $p_j \in \mathcal{P}\xspace$ periodically while incrementing the value of $\mathit{HB}_i[i]$. Once $p_j$ receives a heartbeat message from $p_i$, it updates the $i$-th and the $j$-th entries in $\mathit{HB}_j$, \emph{i.e.,}\xspace it takes the maximum of the locally stored and received entries. Moreover, once any entry reaches the value of the maximum integer, $\mathit{MAXINT}$, a global reset procedure is used (see Section~\ref{sec:bounded}). \begin{remark} % \label{ss:FD asynchronous cycles} % For the sake of simple presentation of the correctness proof of the convergence property, during fair executions, we assume that \EMS{@@ Need to revise this part. @@ $c_{\tau}\in R$ is reached within $\mathcal{O}\xspace(1)$ asynchronous cycles, such that $\forall_{p_i \in \mathit{Correct}(F)}:\mathit{trusted}^{\tau}_i\subseteq \mathit{Correct}(F)$ and for a given $K$, $\forall p_i,p_j \in \mathit{Correct}(F): \mathit{HB}_i^\tau[j] > K$, where $\tau \in \mathbb{Z}^+$ is determined by the $\Theta$- and $\mathit{HB}$-liveness properties. (The proof of the closure property does not use this assumption.)} \end{remark} } \Section{Failure Detectors for the $\Omega$ Class} \label{sec:omega} We study a non-self-stabilizing construction of an $\Omega$ failure detector (Section~\ref{sec:Omega}) and propose its self-stabilizing variant. \Subsection{Non-self-stabilizing $\Omega$ failure detector} Algorithm~\ref{alg:somegaNon} presents the non-self-stabilizing $\Omega$ failure detector by Most{\'{e}}faoui, Mourgaya, and Raynal~\cite{DBLP:conf/dsn/MostefaouiMR03}; the boxed code lines are irrelevant to~\cite{DBLP:conf/dsn/MostefaouiMR03} since we use them to present our self-stabilizing solution. \ems{Note that, in addition to the assumptions described in Section~\ref{sec:spec}, Most{\'{e}}faoui, Mourgaya, and Raynal make the following operational assumptions (Section~\ref{sec:opetionalAssumptions}), which are asynchronous by nature.} \Subsection{Operational assumptions} \label{sec:opetionalAssumptions} Algorithm~\ref{alg:somegaNon} follows Assumption~\ref{def:EMP}. Let us observe Algorithm~\ref{alg:somegaNon}'s communication pattern of queries and responses. Node $p_i$ broadcasts $\mathsf{ALIVE()}$ queries repeatedly until the arrival of the corresponding $\mathsf{RESPONSE}()$ messages from $(n-t)$ receivers (the maximum number of messages from distinct nodes it can wait for without risking being blocked forever). For the sake of a simple presentation (and without loss of generality), it is assumed that nodes always receive their own responses. We refer to the first $(n-t)$ replies to a query that $p_i$ receives as the winning responses. The others are referred to as the losing since, after a crash, the failing nodes cannot reply. \begin{assumption}[Eventual Message Pattern] \label{def:EMP} In any execution $R$, there is a system state $c_{\tau} \in R$, a non-faulty $p_i \in \mathcal{P}\xspace$, and a set $Q$ of $(t+1)$ nodes, such that, after $c_{\tau}$, each node $p_j \in Q$ always receives a winning response from $p_i$ to each of its queries (until $p_j$ possibly crashes). (Note that the time until the system reaches $c_{\tau}$, the \ems{identity of} $p_i$ and the set $Q$ need not be explicitly known by the nodes.) \end{assumption} \Subsection{Variables} The local state includes $r_i$, which is initialized to $0$ and is used for indexing $p_i$'s current round of alive queries and responses. Moreover, the array $count[]$ counts the number of suspicions, \emph{e.g.,}\xspace $count_i[j]$ counts from zero the number of times $p_i$ suspected $p_j$. Also, the $recFrom$ set, which is initialized to $\mathcal{P}\xspace$, has the identities of the nodes which responded to the most recent alive query. When the application layer accesses the variable $leader$, Algorithm~\ref{alg:somegaNon} returns the identity of the least suspected node (line~\ref{ln:sleaderRead}). \Subsection{Algorithm description} Algorithm~\ref{alg:somegaNon} repeatedly executes a do forever loop (lines~\ref{ln:startLoop} to~\ref{ln:srecFromRESPONSE}), which broadcasts $\mathsf{ALIVE}(r,\bullet)$ messages (line~\ref{ln:ssendIAMALIVE}) and collects their replies, which are the $\mathsf{RESPONSE}(\mathit{rJ},\bullet)$ messages (lines~\ref{ln:sRESPONSErecived} and~\ref{ln:ssendRESPONSE}). In this message exchange, every $p_i \in \mathcal{P}\xspace$ uses a round number, $r_i$, to facilitate asynchronous rounds without any coordination linking the rounds of different nodes. Moreover, there is no limit on the number of steps any node takes to complete an asynchronous round. \Subsubsection{The do forever loop} Each iteration of the do forever loop includes actions (1) to (3). (1) Node $p_i$ broadcasts $\mathsf{ALIVE}(r_i,count_i)$ queries (line~\ref{ln:ssendIAMALIVE}), and waits for $(n-t)$ replies, \emph{i.e.,}\xspace $\mathsf{RESPONSE}(\mathit{rJ}, \mathit{recFromJ})$ messages from $p_j \in \mathcal{P}\xspace$ (line~\ref{ln:ssendRESPONSE}), where $r_i$ and $\mathit{rJ}$ are matching round numbers. Moreover, $count_i$ is an array in which, as said before, $count_i[k]$ stores the number of times $p_i$ suspected $p_k \in \mathcal{P}\xspace$. Also, $\mathit{recFromJ}$ is a set of the identities of the responders to $p_j$'s most recent query (lines~\ref{ln:srecFromRESPONSE} and~\ref{ln:ssendRESPONSE}). (2) By aggregating into $prevRecFrom_i$ all the arriving $\mathit{recFromJ}$ sets (line~\ref{ln:sRESPONSErecived}), $p_i$ can estimate that any $p_j: j\notin prevRecFrom_i$ that does not appear in any of these sets is faulty. Thus, $p_i$ increment $count_i[j]$ (line~\ref{ln:scountPlusOne}). (3) The iteration of the do forever loop ends with a local update to $p_i$'s $recFrom_i$ (line~\ref{ln:srecFromRESPONSE}). \Subsubsection{Processing of arriving queries} Upon $\mathsf{ALIVE}(\mathit{rJ}, \mathit{countJ})$ arrival from $p_j$, node $p_i$ merges the arriving data with its own (line~\ref{ln:smaxCountK}), and replies with $\mathsf{RESPONSE}(\mathit{rJ}, recFrom_i)$ (line~\ref{ln:ssendRESPONSE}). This reply includes $p_j$'s round number, $\mathit{rJ}$, which is not linked to $p_i$'s round number, $r_i$. \remove{ \begin{algorithm*}[t!] \begin{\algSize} \smallskip \noindent \textbf{local variables and their initialization:}\\ $r:=0$ \tcc*{current round number} $recFrom:= \mathcal{P}\xspace$ \tcc*{the set of identities of the processors who responded to the most recent alive query} $count[0..n\text{-}1]:=[0,\ldots,0]$ \tcc*{the number of times each processors was suspected} \smallskip \textbf{operation} $\mathsf{leader}()$ \label{ln:leader} \{\textbf{let} $(\bull,x) := \min\{(count[k], k)\}_{p_k \in \mathcal{P}\xspace}$; \Return($x$)\} \label{ln:leaderRead} \smallskip \textbf{do forever} \label{ln:tartLoop} \Begin{ $r \gets r + 1$\; \lForEach{$j \neq i$}{\textbf{send} $\mathsf{ALIVE}(r, count)$ \textbf{to} $p_j$\label{ln:sendIAMALIVE}} \textbf{wait}($\mathsf{RESPONSE}(\mathit{rJ}, \mathit{recFromJ})$ \textbf{received from} $(n-t)$ {processors})\label{ln:RESPONSErecived}\; \textbf{let} $prevRecFrom := \cup$ sets of $\mathit{recFromJ}$ received in line~\ref{ln:RESPONSErecived}\; \lForEach{$j \notin prevRecFrom$}{$count[j] \gets count[j]+1$\label{ln:countPlusOne}} $recFrom \gets \{$processors from which $p_i$ has received $\mathsf{RESPONSE}(\mathit{rJ},\bullet)$ in line~\ref{ln:RESPONSErecived}$\}$\label{ln:recFromRESPONSE} } \smallskip \textbf{upon} $\mathsf{ALIVE}(\mathit{rJ}, \mathit{countJ})$ \textbf{arrival from} $p_j$ \label{ln:uponIAMALIVE}\Begin{ \lForEach{$k \in \{1, \ldots, n\}$}{$count[k] \gets \max(count[k], \mathit{countJ}[k])$\label{ln:maxCountK}} \textbf{send} $\mathsf{RESPONSE}(\mathit{rJ}, \mathit{recFrom})$ to $p_j$\label{ln:sendRESPONSE} } \smallskip \caption{\label{alg:omegaNon}A non-self-stabilizing $\Omega$ construction; code for $p_i$} \end{\algSize} \end{algorithm*} } \begin{algorithm*}[t!] \begin{\algSize} \smallskip \noindent \textbf{local constant, variables and their initialization:} (Initialization is optional in the context of self-stabilization.)\\ \fbox{\textbf{const} $\delta$} \tcc*{max gap between the extrema of count values} $r:=0$ \tcc*{current round number} $recFrom:= \mathcal{P}\xspace$ \tcc*{set of identities of the processors that replied to the most recent query} $count[0..n\text{-}1]:=[0,\ldots,0]$ \tcc*{the number of times each processor was suspected} \smallskip \textbf{operation} $\mathsf{leader}()$ \label{ln:sleader} \{\textbf{let} $(\bull,x) := \min\{(count[k], k)\}_{p_k \in \mathcal{P}\xspace}$; \Return($x$)\}\label{ln:sleaderRead} \smallskip \fbox{\textbf{macro} $\mathsf{counts}\xspace():=\{count[k]:p_k \in \mathcal{P}\xspace\}$}\; \smallskip \fbox{\textbf{macro} $\mathsf{check}\xspace():=$\textbf{ if }{$\max \mathsf{counts}\xspace() - \min \mathsf{counts}\xspace()\ems{>} \delta$\label{ln:consistencyAssertion}}\textbf{ then foreach } {$p_k \in \mathcal{P}\xspace$} \textbf{do}} \fbox{$count[k]\gets \max \{count[k], (\max \mathsf{counts}\xspace() -\delta)\}$;} \smallskip \textbf{do forever} \label{ln:startLoop}\Begin{ \Repeat{$\mathsf{RESPONSE}(\mathit{rJ},$ \fbox{$\bull,$} $\mathit{recFromJ})$ \textbf{\emph{received from}} $(n-t)$ {\emph{processors}}\label{ln:sRESPONSErecived}}{\lForEach{$j \neq i$}{\textbf{send} $\mathsf{ALIVE}(r, count)$ \textbf{to} $p_j$\label{ln:ssendIAMALIVE}}} \textbf{let} $prevRecFrom := \cup$ sets of $\mathit{recFromJ}$ received in line~\ref{ln:sRESPONSErecived}\; \lForEach{$j \notin prevRecFrom$\fbox{$: count[j] < \delta+\min \mathsf{counts}\xspace()$}}{$count[j] \gets count[j]+1$\label{ln:scountPlusOne}} $recFrom \gets \{$processors from which $p_i$ has received $\mathsf{RESPONSE}(\mathit{rJ},\bullet)$ in line~\ref{ln:sRESPONSErecived}$\}$\label{ln:srecFromRESPONSE}\; \fbox{$\mathsf{check}\xspace()$}\label{ln:checkLoop}\; } \smallskip \textbf{upon} $\mathsf{ALIVE}(\mathit{rJ}, \mathit{countJ})$ \textbf{arrival from} $p_j$ \label{ln:suponIAMALIVE}\Begin{ \lForEach{$p_k \in \mathcal{P}\xspace$}{$count[k] \gets \max(count[k], \mathit{countJ}[k])$\label{ln:smaxCountK}} \fbox{$\mathsf{check}\xspace()$}\label{ln:checkAlive}\; \textbf{send} $\mathsf{RESPONSE}(\mathit{rJ}, \fbox{count,} \mathit{recFrom})$ to $p_j$\label{ln:ssendRESPONSE} } \smallskip \fbox{\textbf{upon} $\mathsf{RESPONSE}(\mathit{rJ}, \mathit{countJ}, \mathit{recFromJ})$ \textbf{arrival from} $p_j$} \label{ln:suponRESPONSE}\Begin{ \fbox{\lForEach{$p_k \in \mathcal{P}\xspace$}{$count[k] \gets \max(count[k], \mathit{countJ}[k])$\label{ln:smaxCountK2}}} \fbox{$\mathsf{check}\xspace()$}\label{ln:checkResponse}\; } \smallskip \caption{\label{alg:somegaNon}An $\Omega$ construction; code for $p_i$. (Only the self-stabilizing version includes the boxed code lines.)} \end{\algSize} \end{algorithm*} \Subsection{Self-stabilizing $\Omega$ failure detector} When including the boxed code lines, Algorithm~\ref{alg:somegaNon} presents an unbounded self-stabilizing variation of the $\Omega$ failure detector in~\cite{DBLP:conf/dsn/MostefaouiMR03}. (As mentioned before, Section~5 in~\cite{DBLP:conf/netys/GeorgiouLS19} \ems{explains} how to convert such unbounded self-stabilizing algorithms to bounded ones.) Note that in~\cite{DBLP:conf/dsn/MostefaouiMR03}, all non-crashed nodes converge to a constant value that is known to all correct nodes whereas the counters of crashed nodes increase forever, see claim C2 and C3 of Theorem~97 in~\cite{DBLP:books/sp/Raynal18}. Thus, the proposed algorithm includes \ems{the following} differences from~\cite{DBLP:conf/dsn/MostefaouiMR03}. Algorithm~\ref{alg:somegaNon} makes sure that any non-failing node does not ``hide'' a value that is too high in $count_i[x]$ without sharing it with all correct nodes. In the context of self-stabilization, such a value can appear due to a transient fault. To that end, Algorithm~\ref{alg:somegaNon} includes the field $count$ in the $\mathsf{RESPONSE}()$ message (line~\ref{ln:ssendRESPONSE}) so that the receiver can merge the arriving data with the local one (line~\ref{ln:smaxCountK2}). Algorithm~\ref{alg:somegaNon} also avoids ``counting to infinity'' since, in the context of self-stabilization, a transient fault can set the counters \ems{to arbitrary values. For example, suppose that the counter values that non-faulty nodes associates with all crashed nodes is zero. Also suppose that the counters associated with any non-faulty node is extremely high, say, $M=2^{62}$. We must not require the system to count from zero to $M$ before it is guaranteed that a non-crashed leader is elected, because it would take more than 146 years to do (of we assume the speed of one nanosecond per communication round).} Thus, the proposed solution limits the difference between the extrema counter values in any local array to be \ems{less} than $\delta$, where $\delta$ is a predefined constant. One can view $\delta$ as a trade-off parameter between the solution vulnerability (to elect a crashed node as a leader even in the absence of transient faults) and the time it takes to elect a non-faulty leader (after the occurrence of the last transient fault and after the system has reached $c_\tau$ that satisfies the eventual message pattern assumption, cf. Assumption~\ref{def:EMP}). \ems{\emph{I.e.,}\xspace on the one hand, if the value of $\delta$ is set too low, processors that sporadically slow down might be elected, while on the other hand, for very large values of $\delta$, say, $M$, the time it takes to recover after the occurrence of the last transient faults can be extremely long.} \Subsubsection{Correctness} Definitions~\ref{def:safeConfig} and~\ref{def:complete} are needed for showing that Algorithm~\ref{alg:somegaNon} brings the system to a legal execution (Theorem~\ref{thm:consistencyAssertion}). \begin{definition}[Algorithm~\ref{alg:somegaNon}'s consistent system state] % \label{def:safeConfig} % Suppose that $\max \mathsf{counts}\xspace_i() - \min \mathsf{counts}\xspace_i()\leq \delta$ holds in $c \in R$ for any non-faulty $p_i \in\mathcal{P}\xspace$. % In this case, we say $c$ is consistent. \end{definition} \begin{definition}[Complete execution of Algorithm~\ref{alg:somegaNon}] % \label{def:complete} % Let $R$ be an execution of Algorithm~\ref{alg:somegaNon}. Let $c, c'' \in R$ denote the starting system states of $R$, and respectively, $R''$, for some suffix $R''$ of $R$. We say that message $m$ is \emph{completely delivered} in $c$ if the communication channels do not include $\mathsf{ALIVE}(r,\bullet)$ nor $\mathsf{RESPONSE}(r,\bullet)$ messages. % Suppose that $R=R' \circ R''$ has a suffix $R''$, such that for any $\mathsf{ALIVE}(r,\bullet)$ or $\mathsf{RESPONSE}(r,\bullet)$ message $m$ that is not completely delivered in $c''$, it holds that $m$ does not appear in $c$. In this case, we say that $R''$ is complete with respect to $R$. \end{definition} }%{\vspace*{-\medskipamount} \begin{theorem}[Convergence] % \label{thm:consistencyAssertion} % (i) Once every non-failing processor completes at least one iteration of the do forever loop (lines~\ref{ln:startLoop} to~\ref{ln:checkLoop}) or receive at least one message (lines~\ref{ln:suponIAMALIVE} or~\ref{ln:suponRESPONSE}), the system reaches a consistent state. (ii) Every infinite execution $R=R' \circ R''$ of Algorithm~\ref{alg:somegaNon} reaches within a finite number of steps suffix $R''$, such that $R''$ is complete with respect to $R$ (Definition~\ref{def:complete}). \end{theorem} }%{\vspace*{-\bigskipamount} \begin{proof} Lines~\ref{ln:checkLoop},~\ref{ln:checkAlive}, and~\ref{ln:checkResponse} imply invariant (i). Invariant (ii) is implied by the assumption that any message can reside in a communication channel only for a finite time (Section~\ref{sec:benignFailures}). \end{proof} }%{\vspace*{-\medskipamount} \begin{theorem}[Closure] \label{thm:fdClosed} Let $R$ be an execution of Algorithm~\ref{alg:somegaNon} that starts in a consistent system state. Suppose that $R$ has an eventual message pattern \ems{(Assumption~\ref{def:EMP}).} Algorithm~\ref{alg:somegaNon} demonstrates in $R$ a construction of the eventual leader failure detector, $\Omega$. \end{theorem} \remove{\ BB \begin{proofsketch} In the context of Algorithm~\ref{alg:somegaNon}, we say that $p_i \in \mathcal{P}\xspace$ inhibits the increment of $count_i[x]$ in line~\ref{ln:scountPlusOne} when $x \notin prevRecFrom$ holds but $count_i[x] < \delta+\min \mathsf{counts}\xspace_i()$ does not. Suppose that, for a given $p_x \in \mathcal{P}\xspace$, there is $p_k \in \mathcal{P}\xspace$ that, during $R$, either increments $count_k[x]$ in line~\ref{ln:scountPlusOne} or inhibits such increments for a bounded number of times. In this case, we say that $count_k[x]$ is bounded. % % The proof shows that all non-crashed nodes converge to a bounded value that becomes known to all correct nodes whereas the counters of crashed nodes increase forever. One can obtain the proof by taking Theorem~97 in~\cite{DBLP:books/sp/Raynal18} and substantiating `increasing $count_i[x]$' in Claim 2 with `the increment of $count_i[x]$ or its inhibition'. \end{proofsketch} } }%{\vspace*{-\bigskipamount} \begin{proof} In the context of Algorithm~\ref{alg:somegaNon}, we say that $p_i \in \mathcal{P}\xspace$ inhibits the increment of $count_i[x]$ in line~\ref{ln:scountPlusOne} when $x \notin prevRecFrom$ holds but $count_i[x] < \delta+\min \mathsf{counts}\xspace_i()$ does not. Suppose that, for a given $p_x \in \mathcal{P}\xspace$, there is $p_k \in \mathcal{P}\xspace$ that, during $R$, either increments $count_k[x]$ in line~\ref{ln:scountPlusOne} or in inhibits such increments for a bounded number of times. In this case, we say that $count_k[x]$ is bounded. In all other cases, we say that $count_k[x]$ is unbounded. Given a failure pattern $F()$, we define: $PL = \{x : \exists i \in \mathit{Correct}(F) : count_i[x]$ is bounded$\}$, and $\forall i \in \mathit{Correct}(F) : PL_i = \{x : count_i[x]$ is bounded$\}$, where the set of processor identities, $PL$, stands for ``potential leaders''. These definitions imply $\forall i \in \mathit{Correct}(F) : PL_i \subseteq PL$. The rest of the proof shows that correct processors share identical sets of potential leaders ($PL$), which non-empty (Lemmas~\ref{thm:PLemptyset}), and include only correct processors (Lemmas~\ref{thm:PLsubseteqCorrectF} and~\ref{thm:iCorrectFplIpl}). The proof ends by showing that the processors in $PL$ can only be suspected, \emph{i.e.,}\xspace their counters are incremented (or inhibited from being incremented), a bounded number of times, and this number is eventually the same at each non-faulty processor (Lemma~\ref{thm:twoNonFaultyCountIK}). Thus, all correct processors eventually elect the processor that was suspected for the smallest number of times. \begin{lemma} \label{thm:PLemptyset} $PL\neq \emptyset$ \end{lemma} }%{\vspace*{-\bigskipamount} \begin{proof} Since Assumption~\ref{def:EMP} holds, there mus be a system state $c_{\tau_0} \in R$, a processor $p_i$ and a set $Q$ of $(t+1)$ processors for which at any state after $c_{\tau_0}$, any non-failing processor $p_j \in Q$ receives winning responses from $p_i$ for any of $p_i$'s queries. Due to the assumptions that $|Q|>t$ and that there are at most $t$ faulty processors, $Q$ includes at least one non-faulty processor. Let $\tau\geq\tau_0$ be a time after which no more processors fail. Processor $p_k \in \mathcal{P}\xspace: k \in \mathit{Correct}(F)$ does not stop sending its query (line~\ref{ln:ssendIAMALIVE}) until it receives $\mathsf{RESPONSE}()$ messages from $(n-t)$ processors. Moreover, after $c_\tau$, at least $(t+1)$ processors get winning responses from $p_i$. Therefore, the system eventually reaches a state $c_{\tau_k} \in R: \tau \leq \tau_k$ after which $i \in prevRecFrom_k$ holds (line~\ref{ln:ssendRESPONSE}. Thus, $p_k$ stops incrementing (or inhibiting the increment) of $count_k[i]$ at line~\ref{ln:scountPlusOne}. Since $p_k$ is any correct processors, the system eventually reaches the state $c_{\max \{\tau_x\}_{x\in \mathit{Correct}(F)}} \in R$, it holds that $\forall x,y \in \mathit{Correct}(F):count_x[i] = count_y[i] = M_i \in \mathbb{Z}^+$. In other words, due to the repeated exchange of messages between any pair of non-faulty processors, these processors has a constant value for $count[i]$. \end{proof} \begin{lemma} \label{thm:PLsubseteqCorrectF} $PL \subseteq \mathit{Correct}(F)$. \end{lemma} }%{\vspace*{-\bigskipamount} \begin{proof} We show that for every $x \notin \mathit{Correct}(F)$, it holds that $p_i:i\in \mathit{Correct}(F)$ increments (or inhibits the increment) of $count_i[x]$ for an unbounded number of times during $R$. The rest of the proof is implied by the fact that non-faulty processors never stop exchanging messages among themselves and merge the arriving information upon message arrival (lines~\ref{ln:smaxCountK} and~\ref{ln:smaxCountK2}). Suppose that all the faulty processors have crashed (and their messages $\mathsf{RESPONSE}()$ have been received) before $c_\tau \in R$. Let $p_i$ and $p_j$ be non-faulty processors, and $p_x$ a faulty one. We observe invariants (i) to (iv), which imply the proof. % (i) Since $p_x$ cannot respond to any of $p_j$'s queries, it holds that $x \notin \mathit{rF}_j$, where $x \notin \mathit{rF}_j$ is the value of $recFrom_j$ (which is assigned in line~\ref{ln:srecFromRESPONSE}) in any system state, $c'_\tau$, that appears in $R$ after $c_\tau$. % (ii) Due to invariant (i), it holds that $x \notin \mathit{pRF}_j$, where $x \notin \mathit{pRF}_j$ is the value of $prevRecFrom_i$ (which is assigned in line~\ref{ln:sRESPONSErecived}) in any system state, $c''_\tau$, that appears in $R$ after $c'_\tau$. % (iii) Due to invariant (ii), after $c''_\tau$, every execution of line~\ref{ln:countPlusOne} implies an increment of $count_i[x]$ (or the inhibition of an increment). % (iv) Since $p_i$ sends an unbounded number of queries, invariant (iii) implies that $count_i[x]$ is incremented (or the inhibited from incrementing) for an unbounded number of times during $R$. \end{proof} \begin{lemma} \label{thm:iCorrectFplIpl} $(i \in \mathit{Correct}(F)) \Rightarrow (PL_i = PL)$ \end{lemma} }%{\vspace*{-\bigskipamount} \begin{proof} Recall that $PL_i \subseteq PL$ (by the definitions of $PL$ and $PL_i$). Therefore, $PL \subseteq PL_i$ implies the proof and $PL_i \subseteq Correct(F)$ (due to Lemma~\ref{thm:PLsubseteqCorrectF}). % Let assume that $k \in PL$ and show that $k \in PL_i$. That is, we assume that there are $k, j\in \mathit{Correct}(F)$ for which the constant $M_k$ is the highest value stored in $count_j[k]$ throughout $R$. In order to prove that $k \in PL_i$, we show that $count_i[k]$ is also bounded. Since $count_j[k] \leq M_k$ throughout $R$, the repeated exchange of $\mathsf{ALIVE}()$ and $\mathsf{RESPONSE}()$ messages between the correct processors $p_i$ and $p_j$ (line~\ref{ln:ssendIAMALIVE}, lines~\ref{ln:suponIAMALIVE} to~\ref{ln:smaxCountK} and lines~\ref{ln:suponRESPONSE} to~\ref{ln:smaxCountK2}), implies that $count_i[k]\leq M_k$ throughout $R$ (due to the fact that $M_k$ is a constant). \end{proof} \begin{lemma} \label{thm:twoNonFaultyCountIK} Let $i, j\in \mathit{Correct}(F)$. Suppose that $R$ has a suffix $R''$ during which $count_i[k]=M_k$ always hold, where $M_k$ is a constant. Then, $count_j[k]=M_k$ also holds throughout $R''$. \end{lemma} }%{\vspace*{-\bigskipamount} \begin{proof} This is due to the repeated exchange of $\mathsf{ALIVE}()$ and $\mathsf{RESPONSE}()$ messages between $p_i$ and $p_j$ (line~\ref{ln:ssendIAMALIVE}, lines~\ref{ln:suponIAMALIVE} to~\ref{ln:smaxCountK} and lines~\ref{ln:suponRESPONSE} to~\ref{ln:smaxCountK2}). \end{proof} \end{proof} This ends the proof of Theorem~\ref{thm:fdClosed}. \Section{Background: Non-self-stabilizing Zero-degrading Binary Consensus} \label{sec:back} \begin{algorithm*}[t!] \begin{\algSize} \smallskip \noindent \textbf{local variables and their initialization:}\\ $r:=0$ \tcc*{current round number} $est[0..1]:=[\bot,\bot]$ \tcc*{local decision estimates at the beginning of phases 0 and 1} \smallskip \textbf{operation} $\mathsf{propose}(v)$ \label{ln:scdBroadcast} \Begin{ $(est[], r) \gets ([v,\bot],0)$ \tcc*{$\bot$ denotes a default value that cannot be proposed} \While{$\mathsf{True}\xspace$}{{ $r \gets r +1$\; \tcc{Phase 0: select a value with the help of $\Omega$} \textbf{let} $myLeader := \mathsf{leader}$\label{ln:letMyLeaderNon} \tcc*{read $\Omega$ \Repeat{$[\mathrm{PHASE}(0,r ,\bullet)$ \emph{received from} $n-t$ \emph{nodes}$] \land [\mathrm{PHASE}(0,r,\bullet)$ \emph{received from} $p_{myLeader} \lor myLeader \neq \mathsf{leader}]$\label{ln:until0Non}}{\textbf{broadcast} $\mathrm{PHASE}(0,r, est[0],myLeader)$\label{ln:broadcast0Non}} \If{$[\mathrm{PHASE}(0,r,\bullet,\ell)$ \emph{received from more than} $n/2$ \emph{nodes}$] \land [\mathrm{PHASE}(0,r, v,\bullet)$ \emph{received from} $p_{\ell}]$\label{ln:result0Non}}{$est[1] \gets v$ \textbf{else} $est[1] \gets \bot$} \tcc{Here, we have $((est_i[1] \neq \bot) \land (est_j[1] \neq \bot)) \implies (est_i[1] = est_j[1] = v)$} \tcc{Phase 1: try to decide on an $est[1]$ value} \lRepeat{$[\mathrm{PHASE}(1,r ,\bullet)$ \emph{received from} $n-t$ \emph{nodes}$]$}{\textbf{broadcast} $\mathrm{PHASE}(1,r, est[1])$} \Switch{$\{rec: \mathrm{PHASE}(1,r, rec)$ {has been received}$\}$\label{ln:letREcEst2Non}}{ \lCase{$\{v\}$}{\{\textbf{broadcast} $\mathrm{DECIDE}(v)$; $\Return(v)$\}\label{ln:vBroadcastNon}} \lCase{$\{v,\bot\}$}{$est[0] \gets v$\label{ln:vBotEstNon}} \lCase{$\{\bot\}$}{\textbf{continue}\label{ln:continueNon}} } }} } \smallskip \textbf{upon} $\mathsf{DECIDE}(v)$ arrival from $p_j$ \textbf{do} \{\textbf{broadcast} $\mathrm{DECIDE}(v)$; $\Return(v)$;\label{ln:finalDeci}\} \smallskip \caption{\label{alg:consensusBinaryNon}Guerraoui-Raynal~\cite{DBLP:journals/tc/GuerraouiR04}'s non-self-stabilizing indulgent zero-degrading binary consensus; code for $p_i$} \end{\algSize} \end{algorithm*} Algorithm~\ref{alg:consensusBinaryNon} is a non-self-stabilizing $\Omega$-based binary consensus algorithm that is indulging and zero-degrading. \ems{For the sake of a simpler presentation of the correctness proofs, Algorithm~\ref{alg:consensusBinaryNon}'s line enumeration continues the one of Algorithm~\ref{alg:somegaNon}.} \Subsection{Algorithm structure} Algorithm~\ref{alg:consensusBinaryNon} proceeds in asynchronous rounds that combine, each, two phases. The algorithm aims to have, by the end of phase zero, the same value, which is named the estimated value. This selection is done by a leader, \ems{whose} election is facilitated by the $\Omega$ failure detector. Next, during phase one, the algorithm tests the success of phase zero. The challenge here is that, due to the asynchronous nature of the system, not all nodes run the same round simultaneously. Therefore, the test considers the agreement on the round number, the leader identity, and the proposed value. Moreover, just before deciding on any value, say $v$, the deciding node broadcasts a $\mathrm{DECIDE}(v)$ message. Upon $\mathrm{DECIDE}(v)$ arrival, the receiver repeats the broadcast of the arriving \ems{message} before deciding. Algorithm~\ref{alg:consensusBinaryNon} executes the ``decide'' action by returning with $v$ from $\mathsf{propose}(v)$'s invocation. \ems{This technique of `broadcast repetition' basically lets Algorithm~\ref{alg:consensusBinaryNon} to invoke a reliable broadcast of the decided value. } \Subsubsection{The system behavior during phase zero} The objective of phase zero of round $r$ is to let all nodes to store in $est[1]$ the same value. Once that happens, a decision can be taken during phase one of round $r$. As we are about to explain, that objective is guaranteed to be achieved once a single leader is elected. The main challenge that phase zero addresses is the provision of the safety property, \emph{i.e.,}\xspace no two different decisions are made, during $\Omega$'s anarchy period in which there is no single non-faulty elected leader. To that end, phase zero makes sure that the \emph{quasi-agreement} property always holds before anyone enters phase one of round $r$, where $((est_i[1] \neq \bot) \land (est_j[1] \neq \bot)) \implies (est_i[1] = est_j[1] = v)$ is the property definition. This means that, if $est_i[1] = v \neq \bot$ holds, from the perspective of $p_i$, it can decide $v$. Moreover, if $est_i[1] = \bot$ holds, then from the perspective of $p_i$, it is not ready to decide any value. Therefore, a system state that satisfies the quasi-agreement property allows the individual nodes to decide during phase one on the same value (when $est_i[1] = est_j[1] = v$), or defer the decision to the next round (when $est_i[1] = \bot$). In order to satisfy the quasi-agreement property by the end of phase zero, each $p_i \in \mathcal{P}\xspace$ performs actions (1) and (2), which imply Corollary~\ref{thm:quasiAgreement}. \begin{corollary} % \label{thm:quasiAgreement} % The \emph{quasi-agreement} property holds immediately before $p_i \in \mathcal{P}\xspace$ enters phase one of any round. \end{corollary} Action (1): \reduce{Processor} $p_i$ stores in $myLeader_i$ the value of $leader_i$ \ems{(line~\ref{ln:letMyLeaderNon}),} which is the interface to the $\Omega$ failure detector, before broadcasting the message $\mathrm{PHASE}(0,r, est_i[0],myLeader_i)$ (line~\ref{ln:broadcast0Non}). It then waits until it hears from $n-t$ nodes on the same round (line~\ref{ln:until0Non}). Since there are at most $t$ crashed nodes, waiting for more than $n-t$ nodes jeopardizes the system liveness. Moreover, $t < n/2$ and thus any set of $n-t$ nodes is a majority set, which contains at least one correct node. Processor $p_i$ may stop broadcasting also when it receives a $\mathrm{PHASE}(0,r,\bullet)$ message from its leader, \emph{i.e.,}\xspace $p_{\mathit{myLeader}_i}$, or when a new leader is elected, \emph{i.e.,}\xspace $\mathit{myLeader}_i \neq leader_i$. Action (2): after the above broadcast, $p_i$'s assignment to $est_i[1]$ (line~\ref{ln:result0Non}) satisfies the quasi-agreement property by making sure that (i) a majority of nodes consider $p_\ell$ as their leader when they broadcast the $\mathrm{PHASE}(0,r,\bullet, \ell)$, and (ii) $p_i$ received $\mathrm{PHASE}(1,r,v,\bullet)$ from $p_\ell$. In other words, if (i) and (ii) hold, $p_i$ can assign $v$ to $est_i[1]$, which is $p_\ell$'s value in $est_\ell[0]$ at the start of round $r$. Otherwise, $est_i[1]$ gets $\bot$. Due to the majority intersection property, no two majority sets can have two different unique leaders. Therefore, it cannot be that \ems{$est1_i[r] = v \neq \bot$ and $est1_j[r] = v' \neq \bot$} with $v \neq v'$. \reduce{Corollary~\ref{thm:quasiAgreement} is implied by the above.} \Subsubsection{The system behavior during phase one} During this phase, $p_i$ broadcasts $\mathrm{PHASE}(1,r, est_i[1])$ until it hears from $n-t$ nodes. By the quasi-agreement property, $\exists v \in V: \forall p_j \in \mathcal{P}\xspace : est_j[1] = \bot \lor est_j[1] = v \neq \bot$ holds during round $r$. Thus, for the set of all received estimated values, $rec_i\in \{ \{v\}, \{v, \bot\}, \{\bot\} \}$ (line~\ref{ln:letREcEst2Non}) holds. For the $rec_i = {v}$ case, $p_i$ can broadcast $\mathrm{DECIDE}(v)$ before deciding $v$ (line~\ref{ln:vBroadcastNon}). For the $rec_i = \{v, \bot\}$ case, $p_i$ uses $v$ during round $r+1$ as the new estimated value $est_i[0]$ since some other node might have decided $v$ (line~\ref{ln:vBotEstNon}). For the $rec_i=\{\bot\}$ case, $p_i$ continues to round $r+1$ without modifying $est_i[0]$ (line~\ref{ln:continueNon}). Note that, at any round $r$, it cannot be the case that both $rec_i = \{v\}$ and $rec_j = \{\bot\}$ hold, since \ems{$p_i$'s} broadcast of $\mathrm{DECIDE}(v)$ implies that it had received $\mathrm{PHASE}(1,r_i,v)$ from a majority of nodes. Due to the majority intersection property, there is at least one $\mathrm{PHASE}(1,r_i,v)$ arrival to any $p_j \in \mathcal{P}\xspace$ that executes line~\ref{ln:letREcEst2Non} since it also received $\mathrm{PHASE}(1,r_i,\bullet)$ \reduce{messages} from a majority. Thus, $rec_j = \{\bot\}$ cannot hold. \Subsubsection{The necessity of broadcasting $v$ before deciding on it} Algorithm~\ref{alg:consensusBinaryNon} has to take into consideration the case in which not all nodes decide during round $r$. \emph{E.g.,}\xspace a majority of nodes might decide on round $r$, while a minority of them continues to round $r+1$ during which it must not wait in vain to hear from a majority. By broadcasting $\mathrm{DECIDE}(v)$ before deciding $v$, Algorithm~\ref{alg:consensusBinaryNon} allows the system to avoid such bad situations since once $p_i$ decides, it is guaranteed that eventually, all correct nodes decide. \begin{algorithm*}[t!] \begin{\algSizeSmall} \noindent \textbf{variables:} % $\mathit{seq}$ {is the sequence number of the multivalued consensus object}; $k$ {is the node index, $p_k \in \mathcal{P}\xspace$}; $r:=0$ {is the current round number}; $est[0..2]:=[\bot,\bot,\bot]$ {are the local decision estimates at the beginning of phases 0 and 1 as well as the decided value at entry 2}; $\mathit{myLeader}$ {is the current identity of the leader}; $\mathit{newR}$ {is the round number aggregated from all received values}; and $\txD$ {is the URB transmission descriptor for sharing the decision}; \smallskip \textbf{operation} $\mathsf{propose}(s,k,v)$ \label{ln:scdBroadcastM} \{\textbf{if} {$\reduce{\mathsf{test}\xspace} %{\mathsf{consistencyTest}\xspace(s) \land }CS[\ell] \neq \bot} %{\mathrm{defaultCS}\xspace \land CS[\ell].BC[\ell']=\bot} %{\mathrm{defaultBS}\xspace$}\label{ln:binProposeInvoke} \textbf{where $(\ell,\ell'):=(s \bmod M,k $ $\bmod n)$ then} {$CS[\ell].BC[\ell'].(\mathit{seq},k,r,est$, $\mathit{myLeader},\mathit{newR},\txD) \gets (s,k,0,[v,\bot,\bot],\mathsf{leader},0,\bot)$\}} \textbf{operation} $\mathsf{result}\xspace(s,k)$ \label{ln:doneBConsensus}\{\textbf{if} {$\reduce{\neg \mathsf{test}\xspace} %{\mathsf{consistencyTest}\xspace(s) \lor }CS[\ell]=\bot} %{\mathrm{defaultCS}\xspace\lor CS[\ell].BC[\ell']=\bot} %{\mathrm{defaultBS}\xspace$ \textbf{where} $(\ell,\ell'):=(s \bmod M,k \bmod n)$} \textbf{then} {\Return{$\bot$} \textbf{else} \Return{$(CS[\ell].BC[\ell'].est[2])$}}\} \textbf{operation} $\mathsf{deactivate}\xspace(s,k)$ \label{ln:deactivate}\{\textbf{if} {$\reduce{\neg \mathsf{test}\xspace} %{\mathsf{consistencyTest}\xspace(s) \lor }CS[\ell] \neq \bot} %{\mathrm{defaultCS}\xspace$ \textbf{then} $CS[\ell].BC[\ell'] \gets \bot$ \textbf{where} $(\ell, \ell') := (s \bmod M, k \bmod n)$}\} \smallskip \textbf{do forever} \{\ForEach{$(\ell, k) \in \{0,..., M\text{-}1 \} \times \{0,..., n\text{-}1 \} : CS[\ell] \neq \bot} %{\mathrm{defaultCS}\xspace \land x \neq \bot} %{\mathrm{defaultBS}\xspace$ $\land (x.\txD = \bot \lor \mathsf{hasTerminated}\xspace( x.\txD))$ $\mathbf{with }~ x's~ \mathbf{ \emph{fields}}$ $\mathit{seq},r,est[],\mathit{myLeader},\mathit{newR}$ \textbf{\emph{and}} $\txD$ \textbf{\emph{where}} $x := CS[\ell].BC[k]$\label{ln:doforeverBcon}}{{ \lIf{$est[2] = \bot \land \txD \neq \bot \land \mathsf{hasTerminated}\xspace(\txD)$\label{ln:noactiveTranmisssion}}{$\txD \gets \bot$} \lIf{$est[2] \neq \bot \land (\txD = \bot \lor \mathsf{hasTerminated}\xspace(\txD))$\label{ln:txDurbReBroadcastIf}}{$\txD \gets \mathsf{urbBroadcast}~\mathrm{DECIDE}(\mathit{seq},k,v)$\label{ln:txDurbReBroadcast}; \textbf{continue}} $(r,myLeader) \gets (\max\{r,\mathit{newR}\}) +1,\mathsf{leader})$\label{ln:letMyLeader}\tcc{read $\Omega$} \tcc{Phase 0 : select a value with the help of $\Omega$} \Repeat{$(est[2] \neq \bot \lor \txD \neq \bot) \lor \{[\mathrm{PHASE}(0,\bull,\mathit{seq},k,r,\bullet)$ \emph{received from} $n-t$ \emph{nodes}$] \land [\mathrm{PHASE}(0,\bull,\mathit{seq},k,r,\bullet)$ \emph{received from} $p_{myLeader} \lor myLeader \neq \mathsf{leader}]\}$\label{ln:repeatPhase0End}}{\textbf{broadcast} $\mathrm{PHASE}(0,\mathsf{True}\xspace,\mathit{seq},k,r, est[0],myLeader,r)$\label{ln:repeatPhase0Start}} \lIf{$[\mathrm{PHASE}(0,\bull,\mathit{seq},k,r,\bull,\ell,\bull)$ \emph{received from a majority}$] \land [(0,\bull,\mathit{seq},k,r, v,\bullet)$ \emph{received from} $p_{\ell}]$}{$est[1] \gets v$ \textbf{else} $est[1] \gets \bot$\label{ln:est1GetsV}} \tcc{Phase 1 : try to decide on an $est[1]$ value} \Repeat{$(est[2] \neq \bot \lor \txD \neq \bot) \lor [\mathrm{PHASE}(1,\bull,\mathit{seq},k,r ,\bullet)$ \emph{received from} $n-t$ \emph{nodes}$]$\label{ln:repeatPhase1End}}{\textbf{broadcast} $\mathrm{PHASE}(1,\textsf{True}\xspace,\mathit{seq},k,r, est[1], r)$\label{ln:repeatPhase1Start}} \textbf{let} $rec = \{est[1] : \mathrm{PHASE}(1,\bull,\mathit{seq},k,r, est[1])$ {was received}$\}$\label{ln:letREcEst2}\; \Switch{$rec$}{ \lCase{$\{v\} \land \txD = \bot$}{$\txD \gets \mathsf{urbBroadcast}~\mathrm{DECIDE}(\mathit{seq},k,v)$\label{ln:txDurbBroadcast}} \lCase{$\{\bot,v\}$}{$est[0] \gets v$ \texttt{/* $\bot$ \ems{must not be} in $v$'s domain */}\label{ln:botVcase}} \lCase{$\{\bot\}$}{\textbf{continue}\label{ln:botOnlycase}} } } } \textbf{upon} $\mathsf{PHASE}(\mathit{nJ},\mathit{aJ},\mathit{sJ},\mathit{kJ},\mathit{rJ}, \mathit{vJ}, \mathit{myLeaderJ},\mathit{newRj})$ \textbf{arrival} \textbf{from} $p_j$ \textbf{do} \Begin{ \lIf{$(\reduce{\neg \mathsf{test}\xspace} %{\mathsf{consistencyTest}\xspace(\mathit{sJ}) \lor }CS[\mathit{sJ} \bmod M] = \bot} %{\mathrm{defaultCS}\xspace) \land \mathit{aJ}$}{\{\textbf{send} $\mathrm{PHASE}(\mathit{nJ},\mathsf{False}\xspace,\mathit{sJ},\mathit{kJ},\mathit{rJ}, \mathit{vJ}, \mathsf{leader},\mathit{newR})$ \textbf{to} $p_j$; \Return\}\label{ln:phaseArrivalValidate}} \textbf{let} $O:=CS[\mathit{sJ} \bmod M].BC[\mathit{kJ} \bmod n]$\label{ln:letOR}\; \lIf{$O=\bot} %{\mathrm{defaultBS}\xspace$\label{ln:OdBS}}{$O.(\mathit{seq},r,est,\mathit{myLeader},\mathit{newR}) \gets (\mathit{sJ},\mathit{rJ},[\mathit{vJ},\bot,\bot],\mathsf{leader},\max\{\mathit{rJ},\mathit{newRj}\})$\label{ln:newRAgregateA}} \lElse{$O.\mathit{newR} \gets \max\{O.\mathit{rJ},O.\mathit{newR},\mathit{newRj}\}$\label{ln:newRAgregateB}} \lIf{$\mathit{nJ}=1 \land O.est[1] = \bot$}{$O.est[1] \gets \mathit{vJ}$\label{ln:nJ1OestGets}} \lIf{$\mathit{aJ}$}{$\mathbf{send}~\mathrm{PHASE}(\mathit{nJ},\mathsf{False}\xspace,\mathit{sJ},\mathit{kJ},\mathit{rJ}, \mathit{vJ}, O.\mathit{myLeader}$, $\max \{O.r,O.\mathit{newR}\})~ \mathbf{to}~ p_j$\label{ln:letORsend}} } \textbf{upon} $\mathsf{DECIDE}(\mathit{sJ},\mathit{kJ},\mathit{vJ})$ \textbf{arrival from} $p_j$ \textbf{do} \label{ln:decideArrival}\Begin{ \If{$\reduce{\mathsf{test}\xspace} %{\mathsf{consistencyTest}\xspace(\mathit{sJ}) \land }CS[\mathit{sJ} \bmod M] \neq \bot} %{\mathrm{defaultCS}\xspace$\label{ln:CSsJMsCS}}{ \textbf{let} $O:=CS[\mathit{sJ} \bmod M].BC[\mathit{kJ} \bmod n]$\label{ln:oAssigment}\; \lIf{$O=\bot} %{\mathrm{defaultCS}\xspace$\label{ln:initOthatisBot}}{$O.(\mathit{seq},r,est,\mathit{myLeader},\mathit{newR}) \gets (\mathit{sJ},0,[\mathit{vJ},\mathit{vJ},\bot],\mathsf{leader},0)$\label{ln:newRAgregateC}} \lIf{$O.est[2] = \bot$}{$O.est[2] \gets \mathit{vJ}$\label{ln:Oest2GetsV} \texttt{/* decide $v$ */}\label{ln:decideArrivalEnd}} } } \caption{\label{alg:consensusBinary}A self-stabilizing algorithm for indulgent zero-degrading binary consensus; code for $p_i$} \end{\algSizeSmall} \end{algorithm*} \Section{Self-stabilizing Indulgent Zero-degrading Binary Consensus} \label{sec:binary} Algorithm~\ref{alg:consensusBinary} is our self-stabilizing variation on Guerraoui and Raynal~\cite{DBLP:journals/tc/GuerraouiR04}. The main difference between the proposed solution and Algorithm~\ref{alg:consensusBinaryNon} occurs after a value was decided. Then, Algorithm~\ref{alg:consensusBinaryNon} broadcasts before terminating (lines~\ref{ln:vBroadcastNon} and~\ref{ln:finalDeci}) whereas our self-stabilizing solution repeats the broadcast until the consensus object is deactivated by the invoking algorithm. This follows a well-known impossibility~\cite[Chapter 2.3]{DBLP:books/mit/Dolev2000} that self-stabilizing systems cannot terminate. Specifically, in the context of self-stabilization, Algorithm~\ref{alg:consensusBinaryNon} can be started in a system state in which exactly half of the nodes are at the (normal) initial state of binary objects. Moreover, due to the presence of transient faults, the program counters of the other half of the nodes \ems{can} point to the return command in line~\ref{ln:vBroadcastNon}. Starting from this state will cause the system to violate the termination property. A self-stabilizing solution can avoid this violation by repeating the broadcast of the decided value until the consensus object is deactivated. Note that one can reduce the overhead of the proposed solution by simply lowering the broadcast repetition rate, which in turn extends the stabilization time. \Subsection{Variables} As explained in Section~\ref{sec:spec}, the proposed binary consensus objects are used by multivalued consensus objects, \emph{i.e.,}\xspace $BC[]$ is an array of $n$ binary consensus objects and $CS[]$ is an array of $M$ multivalued consensus objects. The binary consensus objects of Algorithm~\ref{alg:consensusBinary} have the private variables, which store the sequence number of the multivalued consensus object, $\mathit{seq}$, a node index, $k:p_k \in \mathcal{P}\xspace$, and current round number, $r$. Also, the results of phase $x \in \{0,1\}$ is stored $est[x]$ and $est[2]$ stores the decided value. Algorithm~\ref{alg:consensusBinary} also stores the current identity of the leader, $\mathit{myLeader}$, \ems{the} round number aggregated from all received values, $\mathit{newR}$, and the transmission descriptor of the reliable broadcast of the decided value $\txD$. We say the binary object $CS[\ell].BC[k]$ is active when $CS[\ell]\neq \bot$ and $CS[\ell].BC[k]\neq \bot$. For a given active binary object $x:=CS[\ell].BC[k]$, we say that $x$ has an active reliable broadcast when $(x.\txD \neq \bot \land \mathsf{hasTerminated}\xspace(x.\txD))$, \emph{i.e.,}\xspace $x.\txD$ stores a descriptor of a transmission that has not terminated. \Subsection{Message structure} Algorithm~\ref{alg:consensusBinary} uses the $\mathsf{DECIDE}(\mathit{seq},\mathit{k},\mathit{v})$ and $\mathsf{PHASE}(\mathit{phase},\mathit{ackNeed},\mathit{seq},\mathit{k},\mathit{r}, \mathit{v}, \mathit{leader},\mathit{newR})$ messages, where the field $\mathit{phase}$ refers to the phase number, $\mathit{ackNeed}$ indicates whether a reply is needed, $\mathit{seq}$ is the sequence number, $\mathit{k}$ is the node index, $\mathit{r}$ is the round number, $\mathit{v}$ is the estimated value, $\mathit{leader}$ is the round leader, and $\mathit{newR}$ is the sender's round number. \Subsection{Interface operations} The operation $\mathsf{propose}(s,k,v)$ \ems{(Section~\ref{sec:spec})} allows the invoking node to propose value $v$ with sequence number $s$ and node index $k$ (line~\ref{ln:scdBroadcastM}). The operation $\mathsf{result}\xspace(s,k)$ returns the decided value, if such decision occurred (line~\ref{ln:doneBConsensus}). Otherwise, $\bot$ is returned. The operation $\mathsf{deactivate}\xspace(s,k)$ assigns $\bot$ to $CS[s].BC[k]$ (line~\ref{ln:deactivate}). \Subsection{The do forever loop (lines~\ref{ln:doforeverBcon} to~\ref{ln:txDurbBroadcast})} The nodes iterate over all active binary objects, $x$, that do not have an active reliable broadcast. In case $x$ has a decided value and it had an active transmission that has terminated (line~\ref{ln:noactiveTranmisssion}), $p_i$ initializes $x$'s transmission descriptor. Also, in case $x$ has a decided value but is has no active transmission (line~\ref{ln:txDurbReBroadcastIf}), $p_i$ broadcasts the decided value. In line~\ref{ln:letMyLeader}, $p_i$ increments the round number and sample the $\Omega$ failure detector. Algorithm~\ref{alg:consensusBinary} considers situations in which, due to a transient fault, the round numbers go out of sync. It does this by letting $\mathit{newR}$ aggregate the highest round number that is disseminated in each message exchange (lines~\ref{ln:newRAgregateA},~\ref{ln:newRAgregateB},~\ref{ln:letORsend}, and~\ref{ln:newRAgregateC}). Then, at the start of a new round, the highest known round number is used (line~\ref{ln:letMyLeader}). \ems{Although the above example considers a case that can only happen before the start of the system execution, cf. Section~\ref{sec:arbitraryTransientFaults}, the system cannot know whether its current state is the starting one. Therefore, the system has to always be ready to recover from arbitrary transient faults. We also clarify that our model does not limit the number of nodes that can be affected by any arbitrary transient faults. It is only the example above that makes this assumption.} \Subsubsection{Phase 0 (lines~\ref{ln:repeatPhase0Start} to~\ref{ln:est1GetsV})} In this phase $p_i$ broadcasts $\mathrm{PHASE}(0,\mathsf{True}\xspace,s,k,r,$ $est[0],myLeader,r)$, such that the phase field is 0, acknowledgment is needed, the sequence number is $\mathit{seq}$, the node index is $k$, the round number is $r$, the estimated result is $est[0]$, the message leader is $myLeader$ and the message aggregated round number is $r$. This broadcasting repeats as long as the binary object neither has an active broadcast, nor stores a decided value. Moreover, the broadcasting continues until $\mathrm{PHASE}(0,\bull,\mathit{seq},k,r,\bullet)$ is received from $n-t$ nodes (which means that phase 0 messages were received from a majority of nodes during round $r_i$), or $\mathrm{PHASE}(0,\bull,\mathit{seq},k,r,\bullet)$ is received from $p_{myLeader} \lor myLeader \neq \mathsf{leader}]\}$ (which means that some nodes follow a leader different than $p_{myLeader_i}$ during $r_i$). Phase 0 ends by testing in line~\ref{ln:est1GetsV} whether a phase 0 message was received from a majority of nodes that have reported on the same leader, $p_\ell$, from which a message was received. If this is the case, $p_i$ uses the \ems{value,} $v$, received from $p_\ell$ as the estimated result for phase 1 by assigning $v$ to $est_i[1]$. Otherwise, $\bot$ is assigned. \Subsubsection{Phase 1 (lines~\ref{ln:repeatPhase1Start} to~\ref{ln:txDurbBroadcast})} In this phase $p_i$ broadcasts $\mathrm{PHASE}(1,\textsf{True}\xspace,\mathit{seq},k,r, est[1], r)$, such that the phase field is 1, acknowledgment is needed, the sequence number is $\mathit{seq}$, the node index is $k$, the round number is $r$, the estimated result is $est[1]$ and the message aggregated round number is $r$. As in phase 0, this broadcasting repeats as long as the binary object neither has an active broadcast, nor stores a decided value. Moreover, the broadcasting continues until $\mathrm{PHASE}(1,\bullet,\mathit{seq},k,r ,\bullet)$ was received from $n-t$ nodes (which means that phase 1 messages were received from a majority of nodes during round $r_i$). Phase 1 ends by testing the set, $rec_i$, of received estimated results during this phase (line~\ref{ln:letREcEst2}). By the quasi-agreement property (Section~\ref{sec:back}), $rec_i\in \{ \{v\}, \{v, \bot\}, \{\bot\} \}$ holds. When $rec_i = {v}$ holds, $p_i$ can reliably broadcast $\mathrm{DECIDE}(\mathit{seq},k,v)$ (line~\ref{ln:txDurbBroadcast}). When $rec_i = \{v, \bot\}$ holds, $p_i$ uses $v$ as the new estimated value $est_i[0]$ for round $r+1$ since some other node might have decided $v$ (line~\ref{ln:botVcase}). When $rec_i=\{\bot\}$ holds, $est_i[0]$ is unchanged before round $r+1$ (line~\ref{ln:botOnlycase}). \Subsection{The arrival of $\mathsf{PHASE}()$ messages} This arrival updates (and even initializes) the local state of the binary consensus, $O_i$, that has the sequence number $\mathit{sJ}$ and node index $\mathit{kJ}$, where $\mathit{nJ},\mathit{aJ},\mathit{sJ},\mathit{kJ}$, $\mathit{rJ}, \mathit{vJ}, \mathit{myLeaderJ},\mathit{newRj}$ are the message fields. Before this, there is a need to test $\mathit{sJ}$ and validate that $CS[\mathit{sJ} \bmod M]$ is an active object. If this is not the case, a reply is sent to the sender (if $\mathit{aJ}$ indicates that this is needed) and the procedure returns (line~\ref{ln:phaseArrivalValidate}). Line~\ref{ln:letOR} prepares the binary consensus object $O_i$ and line~\ref{ln:OdBS} tests whether $O_i$ needs to be initialized. Otherwise, Algorithm~\ref{alg:consensusBinary} updates the aggregated round number (line~\ref{ln:newRAgregateB}). Line~\ref{ln:nJ1OestGets} is applicable only for phase 1 messages. It tests whether $O_i$ has $\bot$ as its estimated result. When this is the case, $\mathit{vJ}$ is used as $O_i$'s estimated value. The procedure ends by acknowledging the sender, if needed (line~\ref{ln:letORsend}). \Subsection{The arrival of $\mathsf{DECIDE}()$ message} The arrival of $\mathsf{PHASE}(\mathit{sJ},\mathit{kJ},\mathit{vJ})$ messages can update (and even initialize) the decided value, $\mathit{vJ}$, of the binary consensus, $O_i$, that has the sequence number $\mathit{sJ}$ and node index $\mathit{kJ}$. Before this is done, there is a need to test $\mathit{sJ}$ and validate that $CS[\mathit{sJ} \bmod M]$ is an active object (line~\ref{ln:CSsJMsCS}). If this is the case, the procedure checks whether $O_i$ needs to be initialized together with the assignment of the decided value (line~\ref{ln:initOthatisBot}). Otherwise, line~\ref{ln:Oest2GetsV} simply assigns $\mathit{vJ}$ to $O_i.est[2]$. \Section{Algorithm~\ref{alg:consensusBinary}'s Correctness} \label{sec:correctness} Theorems~\ref{thm:recoveryConsensusBinary} and~\ref{thm:clousureConsensusBinary} show the convergence and closure properties. }%{\vspace*{-\medskipamount} \begin{theorem}[Algorithm~\ref{alg:consensusBinary}'s Convergence] % \label{thm:recoveryConsensusBinary} % Let $R$ be an execution of Algorithm~\ref{alg:consensusBinary}. Suppose that \reduce{for any sequence number $s$, any processor $p_i \in \mathcal{P}\xspace$ and a step $a_i \in R$ in which $p_i$ calls $\mathsf{test}\xspace} %{\mathsf{consistencyTest}\xspace()$, it holds that $\mathsf{test}\xspace} %{\mathsf{consistencyTest}\xspace_i(s)=\mathsf{True}\xspace$. Also,} $\forall x \in \mathit{Correct}:CS_x[s \bmod M] \neq \bot$ holds in every system state of $R$. Moreover, $\exists p_j \in \mathcal{P}\xspace : j \in \mathit{Correct}$ for which in every system state of $R$, it holds that $CS_i[s \bmod M] \neq \bot \land CS_i[s \bmod M].BC[k \bmod n] \neq \bot$ for some $k:p_k \in \mathcal{P}\xspace$. Eventually the system reaches a state, $c \in R$, in which $\forall x \in \mathit{Correct} : CS_x[s \bmod M].BC[k \bmod n].est[2]\neq\bot$ holds. % \end{theorem} }%{\vspace*{-\bigskipamount} \begin{proof} Claims~\ref{thm:testSmeanAllactive},~\ref{thm:termination}, and~\ref{thm:xDecides} imply the proof. }%{\vspace*{-\medskipamount} \begin{claim} % \label{thm:testSmeanAllactive} % Suppose that $CS_i[s \bmod M].BC[k \bmod n].est[2]\neq\bot$ holds in $R$'s starting state. Eventually $\forall x \in \mathit{Correct}:CS_x[s \bmod M].BC[k \bmod n] \neq \bot$ holds throughout $R$. \end{claim} }%{\vspace*{-\medskipamount} \begin{claimProof}{\textbf{\ref{thm:testSmeanAllactive}.~~}} Every iteration of the do forever loop (lines~\ref{ln:doforeverBcon} to~\ref{ln:txDurbBroadcast}) includes the binary consensus object $CS_i[s \bmod M].BC[k \bmod n]$ (line~\ref{ln:doforeverBcon}). Note that $CS_i[s \bmod M].BC[k \bmod n].est[2]\neq\bot$ in the starting system state of $R$ implies that $CS_i[s \bmod M].BC[k \bmod n].est[2]\neq\bot$ holds throughout $R$ due to the theorem assumptions and the fact that Algorithm~\ref{alg:consensusBinary} never assigns $\bot$ to $CS_i[s \bmod M].BC[k \bmod n].est[2]$. Thus, the rest of the proof assumes, without loss of generality, that $CS_i[s \bmod M].BC[k \bmod n].est[2]\neq\bot$ holds throughout $R$. % Whenever $CS_i[s \bmod M].BC[k \bmod n].\txD \neq \bot$ holds, $\mathsf{hasTerminated}\xspace_i(\txD)$ holds eventually (\reduce{due to the}URB-termination\reduce{property}). Thus, the if-statement condition in line~\ref{ln:txDurbReBroadcastIf} holds eventually and $\mathrm{DECIDE}(s,k,v)$ is URB broadcast (line~\ref{ln:txDurbReBroadcast}). Recall that $v$'s domain does not include $\bot$ (line~\ref{ln:botVcase}). Upon the URB-delivery of $\mathrm{DECIDE}(s,k,v)$ at any $p_x: x \in \mathit{Correct}$, we have $\forall p_x \in \mathcal{P}\xspace: x \in \mathit{Correct}:CS_x[s \bmod M].BC[k \bmod n] \neq \bot$ (lines~\ref{ln:decideArrival} to~\ref{ln:decideArrivalEnd}). % \end{claimProof} }%{\vspace*{-\medskipamount} \begin{claim} \label{thm:termination} For any sequence number $s$, processor $p_k$'s proposal, and round $r>0$, there is no correct processor that considers indefinitely this consensus task at round $r$. \end{claim} }%{\vspace*{-\medskipamount} \begin{claimProof}{\textbf{\ref{thm:termination}.~~}} Without loss of generality, let us assume that $p_i \in \mathcal{P}\xspace$ does not decide during round $r$, \emph{i.e.,}\xspace $CS_i[s \bmod M].BC[k \bmod n].est[2]=\bot$ throughout $R$. Generality is not lost due to the proof of Claim~\ref{thm:testSmeanAllactive} since the case in which $CS_i[s \bmod M].BC[k \bmod n].est[2]\neq\bot$ holds, implies that eventually $\forall p_x \in \mathcal{P}\xspace: x \in \mathit{Correct}:CS_x[s \bmod M].BC[k \bmod n] \neq \bot$ holds, \emph{i.e.,}\xspace termination. % % % % Towards a contradiction, suppose that $r$ is the smallest round in which a correct processor $p_i$ executes indefinitely. The only two loops in which $p_i$ can continue to execute forever in round $r$ are the repeat-until loops in lines~\ref{ln:repeatPhase0Start} to~\ref{ln:repeatPhase0End} and~\ref{ln:repeatPhase1Start} to~\ref{ln:repeatPhase1End}. By the choice of $r$ as well as lines~\ref{ln:letMyLeader},~\ref{ln:letOR}, and~\ref{ln:letORsend}, no correct processor can continue to execute forever in round $r'< r$. Therefore, $p_i$ receives $\mathrm{PHASE}(0,\bullet,s,k,r,\bullet)$ at least $(n-t)$ times. Moreover, if its current leader, $p_{myLeader_i}$, is correct, $p_i$ receives at least one $\mathrm{PHASE}(0,\bullet,s,k,r,\bullet)$ message from $p_{myLeader_i}$. Furthermore, if $p_{myLeader_i}$ is faulty, eventually it holds that $myLeader_i \neq leader_i$ (by $\Omega$'s eventual leadership). Thus, no correct processor $p_i$ can execute forever the repeat-until loop in lines~\ref{ln:repeatPhase0Start} to~\ref{ln:repeatPhase0End} during round $r$. By similar arguments, during phase one of round $r$, processor $p_i$ receives $\mathrm{PHASE}(1,\bullet,s,k,r,\bullet)$ messages at least $(n-t)$ times from the correct processors. Thus, during round $r$, processor $p_i$ does not execute forever the repeat-until loop in lines~\ref{ln:repeatPhase1Start} to~\ref{ln:repeatPhase1End}. Note that we have reached a contradiction with the assumption that $r$ is the smallest round in which a correct processor executes forever and therefore the claim is true. \end{claimProof} }%{\vspace*{-\medskipamount} \begin{claim} % \label{thm:xDecides} % Eventually only the correct nodes are alive and connected and $\forall x \in \mathit{Correct} : CS_x[s \bmod M].BC[k \bmod n].est[2]\neq\bot$. \end{claim} }%{\vspace*{-\medskipamount} \begin{claimProof}{\textbf{\ref{thm:xDecides}.~~}} Assume, toward a contradiction, that no node ever decides with respect to sequence number $s$, $p_k \in \mathcal{P}\xspace$, and proposal $v \in V$. Recall $\Omega$'s eventual leadership and the fact that faulty nodes eventually crash (by definition). Thus, Claim~\ref{thm:termination} implies the existence of a finite round number $r$ from which (a) only the correct nodes are alive and connected, as well as (b) all correct $p_i \in \mathcal{P}\xspace$ share the same correct leader, \emph{e.g.,}\xspace $p_d$, in $\mathit{myLeader}_i$. % The end condition of the repeat-until loop in line~\ref{ln:repeatPhase0End} holds for $p_i$ eventually. This is because there are more than $n/2$ correct nodes. Each such node, including $p_x$, broadcasts $\mathrm{PHASE}(0, \bullet,s,k,r,v,\bullet)$ and receives at least $n-t$ times the messages $\mathrm{PHASE}(0, \bullet,s,k,r,\bullet)$ (cf. Claim~\ref{thm:termination}'s proof). Once line~\ref{ln:repeatPhase0End}'s condition holds, by the same reasons, also the if-statement condition in line~\ref{ln:est1GetsV} holds as well. Thus, $p_i$ assigns $v$ to $CS[s].BC[k]_i.est[1]$, and during phase $1$ of round $r$, $p_i$ only sends $\mathrm{PHASE}(1, \bullet,s,k,r,v,\bullet)$. Since this is true for any correct $p_i$, it must be that $rec_i =\{v\}$ (line~\ref{ln:letREcEst2}). Therefore, every correct $p_i \in \mathcal{P}\xspace$ executes line~\ref{ln:txDurbBroadcast}, in which $p_i$ URB-broadcasts $\mathrm{DECIDE}(s,k,v)$. Moreover, upon the URB delivery of $\mathrm{DECIDE}(s,k,v)$, every correct node decides in line~\ref{ln:Oest2GetsV} (Claim~\ref{thm:testSmeanAllactive}). % \end{claimProof} This completes Theorem~\ref{thm:recoveryConsensusBinary}'s proof. \end{proof} Theorem~\ref{thm:clousureConsensusBinary} uses the definition of consistent executions. Let $p_i,p_k \in \mathcal{P}\xspace$ be two nodes in the system and $s$ be a sequence number. Let $c$ be a system state in which the if-statement condition in line~\ref{ln:binProposeInvoke} holds with respect to $p_i$. Moreover, no communication channel include the messages $\mathsf{DECIDE}(sek=s,k=x,\bullet)$ and $\mathsf{PHASE}(\bullet,sek=s,k=x,\bullet)$. In this case, we say that $p_i$ can have a consistent invocation of Algorithm~\ref{alg:consensusBinary}'s $\mathsf{propose}_i(s,k)$ in $c$. Let $R$ be an execution of Algorithm~\ref{alg:consensusBinary} in which for any $c' \in R$, for any $p_i \in \mathcal{P}\xspace$ we can either (i) say that $p_i$ can have consistent invocations of $\mathsf{binPropose}_i()$ in $c$, or (ii) $c'$ is the result of only consistent invocations of $\mathsf{propose}()$. In this case, we say that $R$ is a consistent execution of Algorithm~\ref{alg:consensusBinary}. }%{\vspace*{-\medskipamount} \begin{theorem} % \label{thm:clousureConsensusBinary} % Let $R$ be a consistent execution of Algorithm~\ref{alg:consensusBinary}. The system demonstrates in $R$ a construction of a bounded-size array of binary consensus objects. \end{theorem} }%{\vspace*{-\bigskipamount} \begin{proof} \noindent \textbf{Termination, validity, and integrity.~~} Termination holds due to Theorem~\ref{thm:recoveryConsensusBinary}. Integrity holds since $p_i \in \mathcal{P}\xspace$ decides by assigning a non-$\bot$ value to $O_i.est[2]$. This happens only in line~\ref{ln:Oest2GetsV} and when $O_i.est[2]=\bot$. Thus, it can happen at most once per unique pair of sequence number, $\mathit{sJ}$, and processor identifier, $\mathit{kJ}$, cf. line~\ref{ln:oAssigment} for the assignment of $O_i$'s value. With respect to validity, by line~\ref{ln:txDurbBroadcast} we can see that $\mathrm{DECIDE}(s,k,v)$ messages can only be sent with a non-$\bot$ value in the field $v$ since $\bot$ is not in the domain, $V$, of values that one can propose. Thus, when $p_i$ receives a $\mathrm{DECIDE}()$ message, line~\ref{ln:Oest2GetsV} never assigns to $O_i.est[2]$ a $\bot$-value. That is, $p_i$ decides on a non-$\bot$ value that comes from $est[1]$ of some entry $CS_j[s].BC[k]$, which in turn comes from $est[0]$ of some entry $CS_x[s].BC[k]$, where $p_j,p_x \in \mathcal{P}\xspace$. Since $R$ is a consistent execution, $est[0]$ can contain only proposed values that Algorithm~\ref{alg:consensusBinary} assigns in line~\ref{ln:scdBroadcastM}. Moreover, $est[1]$ can contain only values that Algorithm~\ref{alg:consensusBinary} copied from $est[0]$ in lines~\ref{ln:est1GetsV} and~\ref{ln:nJ1OestGets}. Thus, the validity property holds. \noindent \textbf{Agreement.~~} Claim~\ref{thm:singleValue} implies agreement since it shows that only a single value can be decided in a consistent execution. }%{\vspace*{-\medskipamount} \begin{claim} % \label{thm:singleValue} % Let $r$ be the smallest round during which any $p_i \in \mathcal{P}\xspace$ URB-broadcasts $\mathrm{DECIDE}(s,k,v)$. Suppose that $p_j \in \mathcal{P}\xspace$ also URB broadcasts $\mathrm{DECIDE}(s,k,v')$ during round $r$. (i) It holds that $v' = v$. Let $v''$ be the local estimate $CS_x[s \bmod M].BC[k \bmod n].est[0]$ of any $p_x \in \mathcal{P}\xspace$ that proceeds to round $r+1$. (ii) It holds that $v=v''$. \end{claim} }%{\vspace*{-\medskipamount} \begin{claimProof}{\textbf{\ref{thm:singleValue}.~~}} \noindent \emph{Invariant (i).~~} % By the code of Algorithm~\ref{alg:consensusBinary}, $p_i$ receives during $r$ at least $n-t$ times the message $\mathrm{PHASE}(0, \bullet,s,k,r,v,\bullet)$, see the proof of Claim~\ref{thm:termination}. Moreover, $p_j$ has received during round $r$ at least $n-t$ times the message $\mathrm{PHASE}(1,\bullet,s,k,r,v,\bullet)$. During consistent executions, $p_x \in \mathcal{P}\xspace$ can only transmit (and perhaps retransmit) one $\mathrm{PHASE}(0, \bullet,s,k,r,v,\bullet)$ message. Due to the property of majority intersection, $p_i$ and $p_j$ receive during round $r$ the same message $\mathrm{PHASE}(1,\bullet,s,k,r,w,\bullet)$ from some processor $p_x\in \mathcal{P}\xspace$. Since both $p_i$ and $p_j$ executes line~\ref{ln:txDurbBroadcast} during round $r$, it must be the case that $w=v=v'$. \noindent \emph{Invariant (ii).~~} % Suppose that some correct $p_i \in \mathcal{P}\xspace$ URB broadcasts $\mathrm{DECIDE}(s,k,v)$ during a round $r$. Also, $p_j \in \mathcal{P}\xspace$ continues to round $r + 1$. We have to prove that $CS_j[s \bmod M].BC[k \bmod n].est[0]= v$ when $p_j$ starts round $r + 1$. Since $p_i$ URB broadcasts $\mathrm{DECIDE}(s,k,v)$ during round $r$, lines~\ref{ln:repeatPhase1End} and~\ref{ln:txDurbBroadcast} implies that there were at least $(n-t)$ nodes that have sent $\mathrm{PHASE}(1,\bullet,s,k,r,v,\bullet)$ to $p_i$ during round $r$. By the fact that $n-t > n/2$ and the majority intersection property, we know that $p_j$ also had to receive during round $r$ at least one of these $\mathrm{PHASE}(1,\bullet,s,k,r,v,\bullet)$ messages. Also, it follows from \reduce{the quasi-agreement property (}Corollary~\ref{thm:quasiAgreement}\reduce{)} that $p_j$ receives both $v$ and $\bot$ (and no other value) in the phase $1$ of round $r$, \emph{i.e.,}\xspace $rec_j = \{v, \bot\}$, because $rec_j\neq \{v\}$ since $rec_j\neq \{v\}$ implies that $p_j$ URB broadcasts $\mathrm{DECIDE}(s,k,v)$ during $r$. Thus, $p_j$ assigns $v$ to $CS_j[s \bmod M].BC[k \bmod n].est[0]$ before continuing to round $r+1$. \end{claimProof} This completes Theorem~\ref{thm:clousureConsensusBinary}'s proof. \end{proof} \remove{ \Section{Self-Stabilizing Indulgent Zero-degrading Consensus} \label{sec:bounded} In this section, we explain how to transform our unbounded self-stabilizing URB algorithm to a bounded one. We note the existence of several such techniques, \emph{e.g.,}\xspace Awerbuch \emph{et al.}\xspace~\cite{DBLP:conf/infocom/AwerbuchPV94}, Dolev \emph{et al.}\xspace~\cite[Section 10]{DBLP:journals/corr/abs-1806-03498} and Georgiou \emph{et al.}\xspace~\cite{DBLP:conf/podc/GeorgiouLS19}. The ideas presented in these papers are along the same lines. They present a transformation that takes a self-stabilizing algorithm for message-passing systems that uses unbounded operation indices and transforms it into an algorithm that uses bounded indices. The transformation uses a predefined maximum index value, say, $\mathrm{MAXINT} = 2^{64}-1$, and it has two phases. \textsf{(Phase A)} As soon as $p_i$ discovers an index that is at least $\mathrm{MAXINT}$, it disables new invocations of operations. \textsf{(Phase B)} Once all non-failing processors have finished processing their operations, the transformation uses an agreement-based global restart for initializing all system variables. After the end of the global restart, all operations are enabled. For further details, please see~\cite{DBLP:conf/infocom/AwerbuchPV94,DBLP:journals/corr/abs-1806-03498,DBLP:conf/podc/GeorgiouLS19}. } \Section{Conclusions} \label{sec:disc} We showed how a non-self-stabilizing algorithm for indulgent zero-degrading binary consensus by Guerraoui and Raynal~\cite{DBLP:journals/tc/GuerraouiR04} can be transformed into one that can recover after the occurrence of transient faults. We also obtained a self-stabilizing asynchronous $\Omega$ failure detector from the non-self-stabilizing construction by Most{\'{e}}faoui, Mourgaya, and Raynal~\cite{DBLP:conf/dsn/MostefaouiMR03}. As an extension, we note that Ben{-}Or~\cite{DBLP:conf/podc/Ben-Or83} presented a randomized binary consensus (using local coins). It differs from Algorithm~\ref{alg:consensusBinaryNon} only in line~\ref{ln:continueNon}, where it assigns to $est[0]$ a random binary value. This is orthogonal to the algorithm's ability to recover from transient-faults. As future work, we encourage the reader to take these building blocks into account as well as the techniques used to make them self-stabilizing when designing distributed systems that can recover from transient faults. }%{\vspace*{-\smallskipamount}
{'timestamp': '2020-10-13T02:29:39', 'yymm': '2010', 'arxiv_id': '2010.05489', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05489'}
arxiv
\section{Introduction}\label{sec:introduction}} \IEEEPARstart{S}{atoshi Nakamoto} introduced blockchain as a P2P network for cryptocurrencies like bitcoin \cite{bitcoin}. It has also found applications in smart contract-based decentralized applications (DApp) like medical records \cite{medical} and IoT applications \cite{IoT}. The bitcoin protocol in \cite{bitcoin} consists of a chain of blocks in which each block includes a reference to the previous block in the form of a block hash. The miners in the network collect multiple transactions from the clients and create a block by solving a computationally challenging problem called PoW. While creating a new block, this protocol restricts the miner from referring to the longest chain's tip to maintain consensus among all the network nodes. Each client in the network validates the transactions through local copies of the blocks present with them. The difficulty of the PoW task is adaptively set so that a block is created approximately once every 10 minutes in the entire network. As per the measurement study conducted in \cite{info}, 10 minutes block interval was very high compared to the P2P network's delay diameter ($D$). Because of this overestimation of delay diameter, bitcoin's consensus rule \cite{bitcoin} has severe scalability limitations in terms of the number of transactions processed per second (TPS). Bitcoin's network processes around $300000$ transactions in a day \cite{tps} which limits the TPS to $3-4$. Another major issue with the bitcoin protocol is the double-spend attack \cite{Rosenfeld}, where an attacker creates a secret chain with a block having a transaction that is a replacement for the original payment transaction to a merchant. An attacker publishes her secret chain with high probability after receiving the product from the merchant. To counter the double-spend attack the merchant should wait till the block with his transaction issued by the attacker achieves the required number of confirmations \cite{Rosenfeld} before delivering his product to the attacker. In this paper, we propose two models for improving the transaction throughput in PoW based blockchain networks without compromising the fairness of the blockchain system. We propose a mathematical model for optimizing the TPS for the longest chain rule bitcoin protocol in the first model. We framed an optimization problem with the main chain growth rate as a cost function and double-spend attack characterized by attacker's hash rate $q$, delay diameter $D$ as constraints. The $D$ is modeled by considering the blockchain as an Erd$\ddot{o}$s-R$\acute{e}$nyi random network topology \cite{E-R}. The main chain growth rate is derived as a concave function \cite{Boyd} of block-creation rate ($\lambda$). The TPS is obtained as a function of $\lambda$, block size ($b$), and $D$. Our model ensures an increase in $\lambda$, resulting in improved throughput. Through simulation results, it is shown that this is achieved without disturbing the balance between the hash rate and rewards of miners. However, accelerating $\lambda$ beyond the optimal value proposed in this model causes more blocks in the network. This results in some honest nodes not having all the blocks created in the network and not extending the longest chain. This makes the system unfair in terms of the balance between hash rates and the rewards of miners. On the other hand, with a high probability, the attacker who does not follow the bitcoin protocol will increase her chain and gain from the double-spend attack \cite{Rosenfeld}. To overcome this effect in \textit{the longest chain rule} protocol, we propose a second model named Unsupervised Learning based consensus protocol for blockDAG (UL-blockDAG), a consensus protocol for DAG structure of the ledger instead of a chain of blocks. In the second model, while creating a new block, the miner includes reference to all its predecessor blocks called tips/leaf blocks (observed locally in its DAG) in its block header. This results in a DAG structure similar to the blockDAG structure in SPECTRE \cite{spectre} and PHANTOM \cite{phantom}. In this protocol, each client constructs a blockDAG structure and simultaneously follows the two-step strategy to achieve the consensus. In the first step, each client (node) applies a Graph clustering algorithm \cite{cluster} for two clusters and separates the blocks with less inter-connectivity in the DAG. The intuition for applying the Graph clustering algorithm is to counter the double-spend attack. The attacker does not publish the blocks with double-spend transactions immediately after the creation. Instead, the attacker maintains its ledger secretly until the main ledger reaches the required number of confirmations. So, the attacker's secret chain does not have well-connected blocks, and the client can easily separate those blocks by applying the unsupervised learning-based Graph clustering algorithms in \cite{cluster}. Finally, the client left with the blocks with well-connectivity, which are called honest blocks. In the second step, the ordering algorithm arranges the honest blocks in topological order, which makes this consensus mechanism suitable for smart contract applications, especially in the Internet of Things (IoT) services due to fast confirmation times. The simulation results show that each honest client counter-attack the attacker's double-spend strategy by executing the unsupervised learning-based clustering algorithm. The results also show that the drastic improvement in the TPS without compromising the fairness of the network. The rest of the paper is organized as follows. In section 2, we present the related work. Section 3 describes the System model and parameters. Section 4 describes the preliminaries for optimal throughput in the longest chain rule and unsupervised learning based-clustering algorithm. In section 5, we present the optimal longest chain rule. In section 6, we present an unsupervised learning based consensus mechanism for blockDAG. Section 7 discuss simulation results. Section 8 concludes the paper and give future directions for research. \section{Related Work} A GHOST (Greedy Heaviest Observed Sub-tree) rule was proposed in \cite{ghost}, where, instead of the longest chain consensus rule, the path of the subtree with the combined hardest PoW is chosen. A variant of the GHOST protocol was used in the Ethereum blockchain \cite{ethereum}. However, the TPS for this protocol is still relatively less \cite{ether} and susceptible to attacks described in \cite{on_trees}. A SPECTRE protocol is proposed in \cite{spectre}, which builds with the concept of the blockDAG structure of the ledger. This protocol describes the ordering of the blocks in the DAG based on the pairwise voting procedure. The pairwise ordering relation is not transitive, and it does not always give the complete linear ordering of the blocks due to the Condorcet paradox \cite{condorcet}. Smart contracts are the general computations on a particular task between two or more parties in the network. In order to achieve the consensus on the computations, smart contracts need linear ordering of the blocks/transactions. Even though the TPS is much higher than \cite{bitcoin} and \cite{ghost}, SPECTRE is not suitable for smart contract applications. A PHANTOM protocol is proposed in \cite{phantom} based on similar lines of SPECTRE, where, instead of pairwise ordering in SPECTRE, maximum k-cluster subDAG algorithm followed by ordering algorithm were proposed in PHANTOM. While, PHANTOM gives high transaction throughput and total ordering the blocks. However, there is a trade-off between \textit{the anti-cone size} parameter \textit{k} and confirmation times and also susceptible to liveness attack described in \cite{conflux}. A blockchain or DAG protocol based on delayed rewards proposed in \cite{delayed_rewards} to address security against double-spend attacks. The protocol creates a staking mechanism similar to proof-of-stake by delaying the rewards and also punishes the attacker using \textit{fraud-proofs} by slashing or eliminating the miner's future rewards. A permissioned blockchain, Hyperledger Fabric, was proposed in \cite{fabric} with Practical Byzantine Fault Tolerant (PBFT) distributed consensus protocol for running distributed applications. PBFT achieves high transaction throughput but is limited to only a few nodes due to communication overhead. A cryptocurrency for the Internet of Things called IOTA, which is scalable, lightweight, and Quantum secure, was proposed in \cite{iota} based on the DAG structure of transactions. However, the initial IOTA project \cite{iota} does not design with a smart contract layer. The IOTA team has built the smart contracts on layer-2 \cite{iota_smart} as off-chain smart contracts. \section{System model and Notations} The parameters used in our frameworks are listed in TABLE \ref{table:symbols}. In this work, we stick to Bitcoin's model \cite{bitcoin} in every aspect -- transactions, blocks, PoW, information propagation in the P2P network \cite{info}. The only difference between the optimal longest chain rule and unsupervised learning based consensus protocol is the ledger structure. The first one is similar to the bitcoin protocol. In the second framework, instead of a reference to a single block, the newly created block references more than one block in its header and generates the ledger's DAG structure. We refer to the models in \cite{ghost},\cite{E-R} for delay diameter $D$, where the bitcoin P2P network is considered as an Erd$\ddot{o}$s - R$\acute{e}$nyi random network topology. The model specified in \cite{spectre} and \cite{phantom} is used for blockDAG structure of the ledger, where the miners and other nodes follow the mining protocol - \begin{enumerate}[] \item When a miner/node creates/receives a block, broadcast it to all neighboring peers in $V$. More formally, if $c_1, c_2 \in V$, then $G_t^{c_1} \subseteq G_{t+D}^{c_2}$. \item while creating a new block, the miner includes references to all the leaf-blocks/tips (observed in its local copy of the DAG ($G_t^c$)) in its block header. \end{enumerate} As per the mining protocol, every new block $\mathbf{B}$ reaches the entire network in time $D$. While creating a new block at time $t$, the honest miner refers to all the published blocks before time $t-D$, i.e., $tips \in G_{t-D}^{c}$. If $\mathbf{B'}$s miner is honest, then it broadcast $\mathbf{B}$ to all its neighboring peers. So, any block $\mathbf{C}$ created after time $t+D$ refer $\mathbf{B}$ directly or indirectly. Even though the blocks created between $[t-D, t+D]$ are neither referred by $\mathbf{B}$ nor referred $\mathbf{B}$, the $\mathbf{B'}$s miner receives all those blocks by the time $t+2D$. \begin{table}[!t] \renewcommand{\arraystretch}{1.3} \caption{ \\ Parameters used in the proposed the frame works} \centering \begin{tabular}{c l} \hline \textbf{Symbols}& \textbf{Description} \\ \hline $n$ & Number of nodes in the network \\ $q$ & Fraction of the attacker's hashrate \\ $N_t$ & Number of peers connected to each node/client \\ $P_e$ & Probability of existence of an edge between two nodes \\ $b$ & Block size in \textbf{MB} \\ $R$ & Upload bandwidth \\ $h$ & Depth of the tree in \cite{delay} \\ $T_p$ & Maximum Prpogation delay between a pair of nodes \\ $p_c$ & Computational power with node $c$\\ $\lambda$ & Block creation rate \\ $\beta$ & Main chain growth rate \\ $G$ & Block DAG \\ $G_U$ & Undirected version of $G$ \\ $C$ & Set of the blocks in $G/G_U$ \\ $E$ & References to blocks in $G/G_U$ \\ $C_1$ & Blocks created by honest nodes $(C_1 \subseteq C)$ \\ $C_2$ & Blocks created by attacker (malicious) nodes $(C_2 \subset C)$ \\ $\textbf{A}_\textbf{d}$ & Adjacency matrix of blockDAG \\ $\textbf{A}$ & Symmetrized Adjacency matrix for $G_U$ \\ $\textbf{D}$ & Degree matrix \\ $d_i$ & $i^{th}$ diagonal entry in $\textbf{D}$ \\ $\textbf{L}$ & Laplacian matrix \\ $\textbf{x}$ & Cluster indicator vector for $C_1$ and $C_2$ \\ $\lambda_i$ & $i^{th}$ eigen value of $\textbf{L}$ \\ $D$ & End-to-end delay in the network \\ $c$ & Client/Node in the network \\ $V$ & Set of the clients/nodes in the blockchain network \\ $G_t^c$ & Locally observed blockDAG at client/nodes $c \in V$ at time $t$ \\ $\epsilon$ & Probability of successful double-spend attack \\ $k$ & Number of confirmations \\ $N$ & Height of the blockchain or blockDAG \\ $m$ & Number of mining nodes in the network \\ \hline \end{tabular} \label{table:symbols} \end{table} \section{Preliminaries} \subsection{P2P network preliminaries} \begin{lemma} Consider the blockchain P2P network as an Erd$\ddot{o}$s-R$\acute{e}$nyi random network as in \cite{E-R}, the worst-case end-to-end block propagation time in the network as per \cite{delay} is \end{lemma} \begin{align} \label{eq:D} D = h \left(T_p + \frac{b}{R} N_t\right), \end{align} where the degree of the node\footnote{The popular blockchain networks (like bitcoin) were implemented with a fixed maximum number of peers ($N_t = 8$).} ($N_t$) is derived from a binomial distribution as \begin{align} N_t &= (n-1)P_e \end{align} and \begin{align} h &= \lceil{\log_{N_t}\big(n(N_t - 1)+1 \big)}\rceil \end{align} where, $\lceil . \rceil$ is a ceiling function\footnote{For all $x \in \mathbb{R}$, $\lceil x \rceil$ is the least integer number greater than or equal to the given $x$.}. \subsection{Spectral graph theory preliminaries} The following definitions of spectral graph theory are used in our work. Let $G = (C, E)$ be a directed graph with vertex set $C$ and edge set $E$. We assumed that the graph is unweighted.\\ \textbf{Definition 1. (Adjacency matrix).} The adjacency matrix $\textbf{A}_\textbf{d}$ of a directed graph $G$ is an $\mid C\mid \times \mid C\mid$ matrix such that \begin{equation} (\textbf{A}_\textbf{d})_{ij} = \begin{cases} 1,& \text{if } (i,j)\hspace{0.05cm} \epsilon \hspace{0.05cm} E\\ 0, & \text{otherwise} \end{cases} \end{equation} where, $\mid C\mid$ is the total number of vertices\footnote{In this framework, Blocks are the vertices of the graph $G$/$G_U$.} of the graph $G_U$.\\ \textbf{Definition 2. (Symmetrization).} The symmetric adjacency matrix $\textbf{A}$ from $\textbf{A}_\textbf{d}$ without changing the number of edges \cite{symmetrization} is obtained as follows \begin{equation} \mathbf{A = A_d + A_d^T}, \end{equation} where, $\mathbf{A_d^T}$ is the transpose of the matrix $\mathbf{A_d}$,1 and $\textbf{A}$ represents the adjacency matrix of undirected graph ($G_U$) for the original directed graph $G$. \\ \textbf{Definition 3. (Degree Matrix).} The degree matrix $\textbf{D}$ of the graph (\textbf{$G_U$}) is obtained from $\mathbf{A}$ as follows \begin{equation} \mathbf{D} = \textbf{diag}\{d_1,d_2,\dots,d_{\mid C \mid}\} \end{equation} where, \begin{equation} d_i = \sum_{j=1}^{\mid C \mid} \textbf{A}_{ij} \end{equation} \textbf{Definition 4. (Laplacian Matrix).} The graph Laplacian matrix $\textbf{L}$ is defined as \begin{equation} \mathbf{L = D - A} \end{equation} Th important properties of $\textbf{L}$ are defined in \cite{cluster}. \\ \textbf{Definition 5. {Rayleigh Ratio}.} The main tool in the optimization problem for graph clustering is Rayleigh ratio \cite{R-R} defined as \begin{equation} R(L) = \mathbf{\frac{x^T L x}{x^T x}} \\ \end{equation} and \begin{equation} \lambda_{min} < R(L) < \lambda_{max} \end{equation} Where, \begin{itemize} \item $\mathbf{x} \in \mathbb{R}^{\mid C \mid}$ is an orthonormal eigen vector of $\textbf{L}$ also used as cluster indicator vector in graph clustering problem. \item $\lambda_{min}$ and $\lambda_{max}$ are minimum and maximum eigen values of $\textbf{L}$. \end{itemize} \section{Optimal Throughput in Longest chain rule protocol} This section describes the first framework -- a mathematical model for optimizing the TPS in the longest chain rule blockchain protocol. The delay diameter $D$ is modeled by assuming the blockchain P2P network as an Erd$\ddot{o}$s - R$\acute{e}$nyi random network topology. The lower-bound on the main chain growth rate $\beta$ of the longest chain rule network is obtained as a function of $\lambda$ and $D$. The TPS is defined as a function of $\beta$, $b$ and $K$. The optimal $\lambda$ for scaling the TPS is obtained by considering the $D$ and double-spend attack characterized by $q$ as constraints for the optimization problem. The constraint to counter the double-spend attack is defined as inequality between the main chain growth rate $\beta$ and the blocks created by an attacker with a proportion of hash rate $q$ of the total hash rate of the network. \begin{lemma} \label{lemma:beta} For the longest chain rule blockchain network with a block creation rate $\lambda$ and delay diameter $D$, the lower bound on the main chain growth rate $\beta$ for a small $\delta$ ($\delta << 1$) is \begin{equation} \beta \geq \dfrac{\lambda}{1 + \lambda D - \dfrac{3+\delta}{\sqrt{N}} } \label{eq:beta_lim} \end{equation} \end{lemma} \proof See Appendix A. \begin{corollary} The number of blocks\footnote{The blockchain's height and the number of blocks are the same in the longest chain rule consensus protocol.} created in the network increase with time. For $N\to\infty$ \begin{align} \label{eq:beta_inf} \beta \geq \dfrac{\lambda}{1+\lambda D}. \end{align} \end{corollary} \begin{theorem} \label{them:tps} In a blockchain network with throughput $TPS(\lambda,b)$ and delay diameter $D$, the optimal block creation rate is \begin{align} \label{eq:opt_lam_N} \lambda &= \frac{1}{D} \end{align} and the optimal transaction throughput is given by \begin{align} TPS(\lambda,b) = \frac{b K}{2 h \left(T_p + \frac{b}{R} N_t\right)} \label{eq:opt_tps} \end{align} \end{theorem} \proof Our goal is to maximize the number of transactions per second $TPS(\lambda,b)$ with very low probability of successful double-spend attack. So, the optimization problem can be framed as \begin{align} \label{eq:opt} \max_{\lambda} \quad TPS(\lambda,b) \\ \text{s.t} \quad q < \frac{\beta}{\lambda} \label{eq:constaint1} \\ \frac{1}{\lambda} \geq D \label{eq:constaint2} \end{align} where, $q\lambda$ is the attacker's chain growth rate and $\frac{1}{\lambda}$ is the block creation interval. \begin{align} \because TPS(\lambda,b) = \beta b K, \end{align} substituting for $\beta$ from \eqref{eq:beta_lim} in \eqref{eq:opt}, the optimal $\lambda$ is obtained by solving \begin{align} \label{eq:opt_lam} \max_{\lambda} \quad \frac{\lambda}{1 - \dfrac{3+\delta}{\sqrt{N}} + \lambda D } \\ \text{s.t} \quad q \left(1 - \frac{3+\delta}{\sqrt{N}} + \lambda D \right) < 1 \\ \lambda D \leq 1 \end{align} The solution to the optimization problem is provided in Appendix B. \section{The Unsupervised Learning-based blockDAG (UL-blockDAG) consensus protocol} In this section, we discuss the operation of the proposed blockDAG consensus protocol. The protocol consists of the following two steps- \begin{itemize} \item Separating the blocks (with less inter-connectivity) created by an attacker from the well-connected blocks in the blockDAG using the spectral graph theory-based Unsupervised Learning algorithm. \item A topological ordering of the blocks based on the directed edges in DAG structure. \end{itemize} \subsection{Spectral graph clustering for DAG} The graph clustering is defined in two ways by maximizing the intra-cluster edge connections and minimizing the inter-cluster edge connections. Consider an undirected and unweighted graph $G_U$ of a blockDAG $G=(C,E)$. The input data to find the similarities between the intra-cluster vertices is the adjacency matrix $A$. The objective is to find the cluster indicator vector $\mathbf{x} = (x_1, x_2, \dots, x_{|C|})$, which maps vertices of graph $G_U$ to real numbers so that $(x_i - x_j)^2$ should be small (maximal connected vertices stay as close together as possible). The optimization problem for graph clustering based on spectral graph theory \cite{opt_prob}, \cite{Laplacian} is \begin{align} \label{eq:opt_cluster} \argmin_{\mathbf{x} \in \mathbb{R}^{\mid C \mid} } \quad & \mathbf{x^T L x} \\ \text{s.t} \quad & \mathbf{x^T 1} = 0 \label{eq:c1} \\ & \mathbf{x^T x} = 1 \label{eq:c2} \end{align} The solution to the above optimization problem with the objective function $\argmin_{\mathbf{x} \in \mathbb{R}^{\mid C \mid} } \mathbf{x^T L x}$ gives a trivial solution \cite{Laplacian} $\mathbf{x}=\mathbf{1}$ for an eigenvalue $\lambda_{min} = 0$. This causes uncertainty in clustering the graph's vertices by mapping all vertices of $G$ with a constant value $x_i = 1$, for all $i$. The constraint in \eqref{eq:c1} eliminates this uncertainty. The \textit{sign} of the elements of the eigenvector $\mathbf{x}$ decides the clustering process and there is no constraint on the magnitude of $\mathbf{x}$. Therefore, the normalization \eqref{eq:c2} is imposed on \eqref{eq:opt_cluster}. Thus, by the Rayleigh-Ritz theorem \cite{R-R}, the solution to the above optimization problem is the eigenvector ($\mathbf{x}$) corresponding to the second smallest eigenvalue ($\lambda_2$) of $\mathbf{L}$ (the smallest non-zero eigenvalue). Finally, the \textit{sign} of the real value $x_i$ (for all $i$) maps the vertices to the two clusters $C_1$ and $C_2$ of graph $G$. This entire graph clustering procedure is shown in Algorithm \ref{Algorithm1}. The intuition for using Algorithm \ref{Algorithm1} for separating the attacker blocks is explained through the following example. \begin{algorithm}[!t] \caption{Spectral graph clustering for DAG}\label{Algorithm1} \textbf{Input:} G - DAG \\ \textbf{output:} $C_1, C_2$ \begin{algorithmic}[1] \Procedure{FIND-CLUSTERS}{$G$} \State Construct $\textbf{A}_\textbf{d}$ for $G$ \State Compute $\textbf{A} = \textbf{A}_\textbf{d} + \textbf{A}_\textbf{d}^\textbf{T}$ \State Compute the Laplacian matrix $\textbf{L} = \textbf{D}-\textbf{A}$ \State Compute $\textbf{x}$ \Comment eigen vector corresponding to $2^{nd}$ \hspace*{3.3cm} smallest eigen value of $\textbf{L}$ \For {$x_i \in \mathbf{x}$} \If{$x_i >= 0$} \State $C_1.append$($vertex \in C$ mapped to $x_i$) \Else \State $C_2.append$($vertex \in C$ mapped to $x_i$) \EndIf \EndFor \State \textbf{return} $C_1$, $C_2$ \EndProcedure \end{algorithmic} \end{algorithm} \begin{figure}[h] \centering \resizebox{\columnwidth}{!}{ \input{./figs/Attacker.tex} } \caption{An example of a blockDAG attacker model. Block $\textbf{15}$ created by an attacker has a conflicting transaction with a transaction in block $\textbf{3}$ shown by rounded text. The blocks from $\mathbf{0-14}$ are generated by honest miners and an attacker keeps the blocks from $\textbf{15}-\textbf{17}$ in secret until $\textbf{3}$ attained sufficient confirmations (In this case $3$ confirmations) and broadcast all the blocks created by the attacker. Observe that there are no references to attacker blocks $\textbf{15}-\textbf{17}$ from the blocks created by honest nodes indicates blocks $\textbf{15}-\textbf{17}$ created in secret, but both the honest block ($\textbf{14}$) and the attacker block ($\textbf{19}$) has a reference to block $\textbf{18}$ indicate the attacker broadcasted the blocks after the creation of block $\mathbf{18}$.} \label{fig:attacker_model} \end{figure} An attacker model of blockDAG structure is shown in Fig. \ref{fig:attacker_model}. The red-colored blocks show the blocks created by an attacker in secret to attempt the double-spend attack. The attacker creates a block with a conflicting transaction\footnote{The transactions which claim the same sources of cryptocurrency are called conflicting transactions. For example, in a bitcoin network, a node that acts as an attacker attempts a double-spend attack by creating two conflicting transactions with the same Unspent Transaction Output (UTXO) \cite{bitcoin}.} for an honest block's original transaction and creates a chain of blocks in secret. When the block with an original transaction attained the required number of confirmations, the attacker broadcast the secret chain. Fig. \ref{fig:eigen_vector} shows the output of Algorithm \ref{Algorithm1} for the blockDAG $G$ has shown in Fig. \ref{fig:attacker_model}. The positive and negative elements of the eigenvector $\mathbf{x}$ for the blockDAG $G$ in Fig. \ref{fig:attacker_model} are mapped to discrete values in the set $\{1,-1\}$ which represents the clusters $C_1$ and $C_2$. The blocks from $\textbf{0}-\textbf{13}$ added to $C_1$ and the attacker blocks $\textbf{15}-\textbf{19}$ along with block $\textbf{14}$ that reference $\textbf{18}$ (an attacker block) are added to $C_2$. The order of the matrix $A_d$ is $|C| \times |C|$. In Algorithm \ref{Algorithm1}, construction of $A_d$, computing $A$ and $L$ will take $\mathcal{O}(|C|^2)$ operations and computing $\mathbf{x}$ will take $\mathcal{O}(|C|^3)$ operations. Finally, sorting the eigenvalues will be computed in $\mathcal{O}(|C| \log |C|)$ operations and finding $C_1$ and $C_2$ will take $\mathcal{O}(|C|)$ operations. So, Algorithm \ref{Algorithm1} for finding the clusters $C_1$ and $C_2$ from the blockDAG $G$ will be computed in $\mathcal{O}(|C|^3)$ operations. As the block creation is a Poisson random process (See Lemma \ref{lemma:beta_dag}), the size of vertices $|C|$ of $G$ depends on $\lambda$. \begin{figure}[!t] \centerline{\includegraphics[width=\columnwidth]{./figs/eigen_vector.eps}} \caption{Grouping the blocks in blockDAG shown in Fig. \ref{fig:attacker_model} into two clusters. The blocks above the green line are added to $C_1$ and blocks below the green line are added to $C_2$.} \label{fig:eigen_vector} \end{figure} \subsection{The client protocol} A client/node is either a miner having a high computational power to solve the PoW problem or a simple node with no mining power. The client protocol is a two-step consensus protocol described through the following two algorithms. \subsubsection{Separating the attacker blocks and honest blocks} For all $c \in V$, the input $G_t^c$ to Algorithm 2 at each time instant $t$ has shown in Fig. \ref{fig:algo_2}. For simplicity, at each time instant, a hypothetical block $H$ added to $G_t^c$. \begin{algorithm}[!t] \caption{Finding the list of confirmed blocks}\label{Algorithm2} \textbf{Input:} $G_t^c$, $k$, $N$ - Height at which decision on confirmation \\ \hspace{1cm} to be made \\ \textbf{output:} $\textbf{blueList}$ - A set of confirmed blocks \begin{algorithmic}[1] \Procedure{FIND-LIST}{$G^c_t,k,N$} \State $G \gets G^c_t \backslash $ \{All left most blocks till $height = N-1$\} \State $C_1, C_2 \gets {FIND-CLUSTERS}(G)$ \For{all $B \in C_1 \cap$ Blocks at height $N$} \State \textbf{blueList}.add(B) \EndFor \State \textbf{return} $\textbf{blueList}$ \EndProcedure \end{algorithmic} \end{algorithm} Algorithm \ref{Algorithm2} operates as follows - \begin{itemize} \item Given a blockDAG $G_t^c$ observed locally at each client $c$ at a particular time $t$, the algorithm finds the clusters $C_1$ and $C_2$ each time recursively at each block height after adding new blocks to $G_t^c$. \item Whenever blocks at a particular height ($N-1$) attain the required number of confirmations, the client excludes those blocks from the input $G_t^c$ to construct $G$. \item To decide the confirmation of blocks at height $N$, the client needs to reach the height $N+k+1$ in its local blockDAG $G_t^c$. Suppose a client observed the current block height $N$ in its local blockDAG $G_t^c$. \item To assign the blocks at height $N$ to clusters $C_1$ and $C_2$, the client considers the blocks in heights [$N$, $N+k+1$]. So the symmetric matrix $\mathbf{L}$ is the order of the total number of blocks in the heights [$N$, $N+k+1$] present in $G_t^c$. \item The confirmed blocks added to the $\textbf{blueList}$ for arranging them into topological order as described in Algorithm \ref{Algorithm3}. \end{itemize} \begin{figure}[!t] \begin{subfigure}{.45\columnwidth} \resizebox{\textwidth}{!}{ \input{./figs/h_1.tex} } \caption{At height=1} \label{fig:h1} \end{subfigure} \hfill \begin{subfigure}{.45\columnwidth} \resizebox{\textwidth}{!}{ \input{./figs/h_2.tex} } \caption{At height=2} \label{fig:h2} \end{subfigure} \\ \begin{subfigure}{.45\columnwidth} \resizebox{\textwidth}{!}{ \input{./figs/h_3.tex} } \caption{At height=3} \label{fig:h3} \end{subfigure} \hfill \begin{subfigure}{.45\columnwidth} \resizebox{\textwidth}{!}{ \input{./figs/h_4.tex} } \caption{At height=4} \label{fig:h4} \end{subfigure} \\ \begin{subfigure}{.45\columnwidth} \resizebox{\textwidth}{!}{ \input{./figs/h_5.tex} } \caption{At height=5} \label{fig:h5} \end{subfigure} \hfill \begin{subfigure}{.45\columnwidth} \resizebox{\textwidth}{!}{ \input{./figs/h_6.tex} } \caption{At height=6} \label{fig:h6} \end{subfigure} \\ \begin{subfigure}{.45\columnwidth} \resizebox{\textwidth}{!}{ \input{./figs/h_7.tex} } \caption{At height=7} \label{fig:h7} \end{subfigure} \caption{An example to show the operation of Algorithm 2. As time progresses, clustering and confirmation of blocks to $C_1$ (blue) and $C_2$ (red).} \label{fig:algo_2} \end{figure} Let $C$ is the set of blocks in the graph $G$ of line $2$ in Algorithm \ref{Algorithm2}. Asymptotically, Algorithm \ref{Algorithm2} computes $blueList$ in $\mathcal{O}(|C|^3)$ operations. Algorithm 2 is illustrated with the following example shown in Fig. \ref{fig:algo_2} and Fig.\ref{fig:algo_2_spectral}. In this example, we assume the number of confirmations $k=4$ is constant and leave the analysis of $k$ to the next subsection. The attacker creates a conflicting transaction to a transaction in block $\mathbf{3}$ and includes it in block $\mathbf{15}$. The attacker keeps the blocks $\mathbf{15-18}$ secret until the blocks at $height = 1 $ (blocks $\mathbf{1-3}$) attain k = 4 number of confirmations by the other clients in the network and broadcast all the blocks from $\mathbf{15-19}$ whenever the other clients reached $height=6$. Each client will confirm the blocks at a particular height $N$ to either of the clusters $C_1$ or $C_2$ whenever it noticed the height increases to $N+k+1$ in $G_t^c$. For example, a client confirms the blocks at $height=1$, when it reaches $height=6$. Here, at $height=6$, the blocks $\mathbf{1-3}$ are confirmed to $C_1$ (shown in blue), and block $\mathbf{15}$ is added to $C_2$ (shown in red). At $height=7$, the client excludes blocks $\mathbf{1-3}$ and $\mathbf{15}$ from $G_t^c$ (As per line $2$ of Algorithm \ref{Algorithm2}). Here, the blocks $\mathbf{4-6}$ are added to $C_1$, and block $\mathbf{16}$ is added to $C_2$. \begin{figure}[!t] \begin{subfigure}[b]{0.45\columnwidth} \includegraphics[width=\linewidth]{./figs/h_1.eps} \caption{At height = 1} \label{fig:h_1} \end{subfigure} \hfill \begin{subfigure}[b]{0.45\columnwidth} \includegraphics[width=\linewidth]{./figs/h_2.eps} \caption{At height = 2} \label{fig:h_2} \end{subfigure} \\ \begin{subfigure}[b]{0.45\columnwidth} \includegraphics[width=\linewidth]{./figs/h_3.eps} \caption{At height = 3} \label{fig:h_3} \end{subfigure} \hfill \begin{subfigure}[b]{0.45\columnwidth} \includegraphics[width=\linewidth]{./figs/h_4.eps} \caption{At height = 4} \label{fig:h_4} \end{subfigure} \\ \begin{subfigure}[b]{0.45\columnwidth} \includegraphics[width=\linewidth]{./figs/h_5.eps} \caption{At height = 5} \label{fig:h_5} \end{subfigure} \hfill \begin{subfigure}[b]{0.45\columnwidth} \includegraphics[width=\linewidth]{./figs/h_6.eps} \caption{At height = 6} \label{fig:h_6} \end{subfigure} \\ \begin{subfigure}[b]{0.45\columnwidth} \includegraphics[width=\linewidth]{./figs/h_7.eps} \caption{At height = 7} \label{fig:h_7} \end{subfigure} \caption{Spectral properties for $2-clusters$ of blockDAGs shown in Fig. \ref{fig:algo_2}.} \label{fig:algo_2_spectral} \end{figure} Fig.\ref{fig:algo_2_spectral} shows the spectral properties (The eigenvector corresponding to second smallest eigenvalue) of the blockDAG $G_t^c$ structures shown in Fig. \ref{fig:algo_2}, which illustrates assigning the blocks to clusters $C_1$ (above the orange line) and $C_2$ (below the orange line). Fig. \ref{fig:h_6} and \ref{fig:h_7} show the blocks $\mathbf{1-6}$ shown in blue colour are added to $\mathbf{blueList}$ and blocks ($\mathbf{15-16}$) are separated from the blocks created by the honest nodes. \subsubsection{Ordering of confirmed blocks} Finally, the blocks added to the $\textbf{blueList}$ can be arranged in topological order ($\textbf{ordList}$) as described in Algorithm \ref{Algorithm3} begins with initializing an empty topological queue (\textit{topo\_ q}) and empty ordered list ($\textbf{ordList})$. \begin{algorithm}[!b] \caption{Ordering of blocks}\label{Algorithm3} \textbf{Input:} $G_t^c$, $\textbf{blueList}$ \\ \textbf{output:} $\textbf{ordList}$ - an ordered list of blocks \begin{algorithmic}[1] \Procedure{ord}{$G^c_t$,$\textbf{blueList}$} \State Intialize empty queue \textit{topo\_ q} and empty $\textbf{ordList}$ \State \textit{topo\_ q.push}(\textit{genesis}) \While{\textit{$topo\_ q \neq \phi $}} \State $B \gets topo\_q.pop() $ \State $\textbf{ordList}.add(B)$ \State $children(B) \gets \{j: (j,B) \in E\} $ \State Sort($children(B)$) based on their $hash$ values \For{all $C \in children(B) \cap \textbf{blueList}$} \State $topo\_q.push(C)$ \EndFor \EndWhile \State \textbf{return} $\textbf{ordList}$ \EndProcedure \end{algorithmic} \end{algorithm} \begin{itemize} \item Each client add the blocks in $\textbf{blueList}$ to $topo\_q$ starting from the $genesis$ block. \item Arrange the $children$\footnote{children of a block $\mathbf{B}$ are the blocks that refer to $\mathbf{B}$ directly in the blockDAG.} of a block in ascending order of their hash value, which indicates the block with a lesser hash value (block with smaller hash than the target value in PoW puzzle \cite{bitcoin}) added first among children of $\mathbf{B}$ with the same block height. \end{itemize} When a block $\mathbf{B}$ is pushed into \textit{topo\_ q}, all blocks referenced by $\mathbf{B}$ are also pushed. The algorithm adds all the blocks and their children in $\mathbf{blueList}$ to \textit{topo\_ q}. The client $c$ executes Algorithm \ref{Algorithm3} in $\mathcal{O}(|\mathbf{blueList}|+|E|)$. \subsubsection{Transaction security} Consider a transaction $tx \in \mathbf{B}$, where $\mathbf{B}$ is in $\mathbf{blueList}$ of $G_t^c$. In order to make $tx$ invalid, an attacker creates a conflicting transaction $tx'$ in a block $\mathbf{C}$, which is a part of the attacker's secret chain similar to the secret chain shown in Fig. \ref{fig:attacker_model}. The recipient of the $tx$ wait for $k$ number of confirmations to find the $\mathbf{blueList}$ around the $tx$ and eliminate the block having $tx'$ as invalid. Thus, the implication of block security through $k$ is also implicated to transaction security. \subsection{Mathematical Analysis of UL-blockDAG} The block creation rate $\lambda$ is very large for creating the blockDAG structure of ledger. So, the UL-blockDAG protocol does not rely on the condition $\lambda D << 1$ which is imposed on longest chain rule (bitcoin) and optimal longest chain rule protocols. \subsubsection{Transaction throughput (TPS)} \begin{lemma} \label{lemma:beta_dag} For a UL-blockDAG protocol based blockchain network generating blocks at a rate $\lambda$ and delay diameter $D$, the lower bound on the main chain growth rate $\beta$ for a small $\delta$ ($\delta << 1$) is \begin{equation} \beta \geq \frac{\lambda D}{1 + D - \frac{3+\delta}{\sqrt{N}}} \label{eq:beta_dag} \end{equation} \end{lemma} \proof See Appendix C. \begin{corollary} For $N\to\infty$ \begin{equation} \label{eq:beta_dag_inf} \beta \geq \frac{\lambda D}{1 + D}. \end{equation} \end{corollary} \begin{lemma} The minimum TPS in blockDAG ledger based blockchain network is \begin{equation} TPS(\lambda,b) = \frac{\lambda D}{1+D} b K \approx \lambda b K \end{equation} \end{lemma} \subsubsection{Number of confirmations (k)} \textbf{Definition 6. {\textit{future}(B)}.} The \textit{future} of a block $\textbf{B}$ is a set of all the blocks which refer to block $\textbf{B}$ directly or indirectly, which were created after the block $\textbf{B}$. The spectral clustering algorithm is based on intra-cluster and inter-cluster references depend on the \textit{future} of a block till the block attain the required number of confirmations $k$. Similarly, $future^i(\textbf{B})$ is denoted as a set of blocks that refer to $\textbf{B}$ directly or indirectly at height $i$ in $G_t^c$ and $future^i(\textbf{B}) \subseteq future(\textbf{B})$. \\ \textbf{Definition 7. {Risk(\textbf{B},k)}.} Let $\textbf{B}$ and $\textbf{B}'$ are honest and attacker blocks respectively having conflicting transactions, the risk of including $\textbf{B}'$ instead of $\textbf{B}$ in $\textbf{ordList}$ is defined as \begin{equation} Risk(\textbf{B},k) = Pr\left[\sum_{i=N+1}^{N+k+1}R_{h,i} < R_{a,N+k+1}\right] \label{eq:risk} \end{equation} Where, \begin{itemize} \item \begin{equation} R_{h,i} = \big|future^i(\textbf{B})\big| \end{equation} \item \begin{equation} \sum_{i=N+1}^{N+k+1}R_{h,i} = \Bigg| \left \lbrace \bigcup_{i=N+1}^{N+k+1} future^i(\textbf{B}) \right\rbrace \Bigg| \label{eq:R_h} \end{equation} \item \begin{equation} R_{a,N+k+1} = \Big| future^{N+k+1} (\textbf{B}')\Big| \label{eq:R_a} \end{equation} \end{itemize} \begin{proposition} \label{prop:Risk} Suppose, a block $\mathbf{B}$ included in the DAG $G_t^{c}$ at time $t$ ($\textbf{B} \in G_t^{c}$) and at any time $s >> t$ ($\textbf{B} \in G_s^{c}$) \begin{equation} \lim_{k \to \infty} Risk(\textbf{B},k) = 0 \end{equation} \end{proposition} \begin{lemma} For any $\epsilon > 0$ ($\epsilon << 1$), $Risk(\textbf{B},k) < \epsilon$, the minimum number of confirmations required for the block $\textbf{B}$ is \begin{equation} \frac{3(\lambda D + 1)(1-\epsilon)}{4\left[\lambda (1-q)D + 1\right]} \label{eq:k} \end{equation} \label{lemma:confirmations} \end{lemma} \proof See Appendix D. \subsubsection{Safety and Liveness Properties of the proposed blockDAG consensus protocol} Proposition \ref{prop:Risk} essentially gives the Safety and Liveness properties required for the distributed consensus protocol. Indeed, once $Risk(\mathbf{B},k) < \epsilon$ (based on the minimum number of the confirmations $k$ required for the block $\mathbf{B}$) is satisfied, the client can decide to accept transactions in $\mathbf{B}$ (Liveness). The accepted transactions are guaranteed to be irreversible (Safety) with a probability of $\epsilon$ as confirmations to $\mathbf{B}$ increase with time. \subsection{Suitability for Smart Contract applications} Smart contracts \cite{smartContracts} are the self-executable computer codes deployed on the blockchain with a set of functions and state variables. These smart contracts found applications in Health care \cite{medical}, IoT services \cite{IoT}, and so forth. The execution of smart contract functions changes the values of one or more state variables. The change of state variable values create transactions on the blockchain. These transactions included in the blocks construct a DAG structure called blockDAG. The transactions in a block are ordered as per their order of arrival. To maintain the consistency of the state variable values, the transactions related to that smart contract should be arranged in linear order. The topological ordering algorithm (Algorithm 3) has been used to organize the blocks in a linear order to make the protocol suitable for smart contract applications. The IoT services require a very low operational latency in processing the transactions of the blockchain. The minimum number of confirmations as per \eqref{eq:k} shows the confirmation delay is less in the proposed protocol. \subsubsection{The effect of transaction arrival rate on the security} In some IoT systems, the transaction arrival rate is fluctuant. In the proposed UL-blockDAG protocol, the two independent parallel processes create the blocks with rates $\lambda$ and $\lambda D$ (as per the Lemma \ref{lemma:beta_dag}). In such a scenorio, the blocks are created with lesser block size for lower transaction volume and the blocks are created with larger block size for higher transaction volume. Thus, the transaction arrival rate does not affect the block arrival rate. The confirmation delay $k$ which characterizes the double-spend attack depends on the number of block references to $\mathbf{B}$ in $future(\mathbf{B})$ and also the number of references to a block $\mathbf{B}'$ (having conflicting transaction with a transaction in $\mathbf{B}$) in $future^{N+k+1}(\mathbf{B}')$. Moreover, $future(\mathbf{B})$ and $future^{N+k+1}(\mathbf{B}')$ depends on the two independent processes with rates $\lambda$ and $\lambda D$ (as per Lemma \ref{lemma:beta_dag}), but not on the transaction arrival rate. So, the fluctuation in the transaction arrival rate neither affects the $k$ nor the security of the system. \section{Results and Discussion} \subsection{Event-driven simulation} The event-driven simulator generates the events as per the information propagation protocol \cite{info} for bitcoin protocol with inputs - number of nodes ($n$), block creation rate ($\lambda$), Genesis block ($genesis$), Hash rate distribution ($H$) \cite{hashrate} and duration of the simulation ($Sim\_Time$). The simulator generates the events for creating a block, broadcasting the block to neighbors, and adding the block after verifying the block height and hash of the previous block. \begin{algorithm}[!t] \caption{Event-driven Simulator}\label{Algorithm4} \textbf{Input:} $n$ - number of nodes, $\lambda$ - Block creation rate, $Sim\_Time$ - Duration of the simulation, $genesis$ - Genesis Block, $p_c$ - Fraction of hash rates of each node \\ \textbf{output:} $blockLedger$ \begin{algorithmic}[1] \Procedure{runSim}{$n$,$\lambda$,$Sim\_Time$,$genesis$} \State Initialize empty $event\_q$ and $miners$ \State $t = 0.0$ \State Initialize the $miners$ with inputs and $event\_q$ \Comment It also \\ \hspace{2.5cm} add a new $mine\_block$ event to $event\_q$ \State $add\_peers(8)$ \While{\textit{$ Sim\_Time < t$}} \State $t,t\_event \gets event\_q.pop() $ \State $receive\_event(t,t\_event)$ \EndWhile \State \textbf{return} $blockLedger$ \EndProcedure \end{algorithmic} \end{algorithm} \begin{algorithm}[!b] \caption{Generation of Events} \label{Algorithm5} \textbf{Input:} $t$ - Time of occurrence of an event, $t\_event$ - Event to be executed at time $t$ \\ \textbf{output:} Update blockLedger \begin{algorithmic}[1] \Procedure{genEvents}{$t$, $t\_event$} \If{$t\_event.action ==$ "block"} \State Verify($t\_event.payload$) \State Generate $add\_block$ event \ElsIf{$t\_event.action == $"addblock"} \State $blocks.append(t\_event.payload)$ \State $chain\_head.append(hash(t\_event.payload))$ \State Announce($t\_event.payload$) \State generate $inv$ events \State $t \gets t + random.exp\left(\frac{1} {\lambda \times p_c}\right)$ \State Generate next $mine\_block$ event at $t$ \ElsIf{$t\_event.action == $"inv"} \If{$t\_event.payload$ not in $blocks$} \State Request($t\_event.payload$) \State Generate $get\_block$ event \EndIf \ElsIf{$t\_event.action ==$ "$get\_block$"} \State Send($t\_event.payload$) \EndIf \EndProcedure \end{algorithmic} \end{algorithm} We randomly generate eight peers for each client $c$, similar to the bitcoin P2P network. The timing information for mining a block event of a miner $c$ is drawn from an exponential distribution with mean $\lambda \times p_c$. All the event information stored in a time priority queue named as $event\_queue$. The ledger data stored in a dictionary named $blocks$ with $blockhash$ as a key and $block$ data structure as a value, and the $chain\_head$ stores the list of block hashes. These two data structures were used in the analysis of the protocol. Algorithm \ref{Algorithm4} describes the execution of events from the $event\_queue$ on a time priority basis. The events are divided into four types as per the information propagation protocol described in \cite{info} of bitcoin for propagating a block from miner to reach the entire network. The events are classified as \textit{inv} - sending a new block hash invitation, \textit{getblock} - requesting a new block, \textit{block} - sending a block to its peers and \textit{addblock} - adding a received block to its local copy of the blockchain. After adding a mined/received block, each miner starts mining with exponentially distributed time intervals with a rate of their hash rate (line $9$ of Algorithm \ref{Algorithm5}). The generation of these events is described through Algorithm \ref{Algorithm5}. The payload of an event is defined as \begin{align} t\_event.payload &= \begin{cases} hash(block), & \text{for inv event}.\\ block , & \text{for other events}. \end{cases} \label{eq:t_event} \end{align} \begin{algorithm}[!t] \caption{Modified $addblock$ event for UL-blockDAG}\label{Algorithm6} \textbf{Input:} $t$ - Time of occurrence of an event, $t\_event$ - Event to be executed \\ \textbf{output:} $\textbf{ordList}$ \begin{algorithmic}[1] \Procedure{$addblock$}{$t$, $t\_event$} \State $blocks.append(t\_event.payload)$ \State $chain\_head[bloc\_height].append(hash(t\_event.payload))$ \State Mapping(hash($t\_event.payload$)) \Comment Mapping \\ \hspace*{0.5cm} block hashes to natual numers and construct DAG suitable \hspace*{0.5cm} for consensus algorithm execution \State $\textbf{ordList} \gets$ UL-blockDAG consensus Algorithm \State Announce($t\_event.payload$) \State generate $inv$ events \State $t \gets t + random.exp\left(\frac{1} {\lambda\times p_c}\right)$ \State Generate next $mine\_block$ event at $t$ \State \textbf{return} $\textbf{ordList}$ \EndProcedure \end{algorithmic} \end{algorithm} The simulation Algorithms are similar for blockDAG protocol, except in constructing ledger ($addblock$ event) and consensus algorithm. The $chain\_head$ for blockDAG structure is a dictionary with block height as key and block hashes at that height as values. Algorithm \ref{Algorithm6} describes the modified $addblock$ event for blockDAG protocol simulation. \subsection{Comparison of mainchain block growth rate with simulation results} TABLE \ref{table:values} lists the values of the parameters used for generating the results in this section. See TABLE \ref{table:symbols} for a description of the symbols. \begin{table}[!b] \caption{\\ Parameter values for the case of Bitcoin} \label{table:values} \centering \begin{tabular}{c l} \hline \textbf{Parameter}&\textbf{value}\\ \hline $n$ & $100$ \\ $N_t$ & $8$ \quad \cite{bitnodes} \\ $P_e$ & $8.0/(n-1) \approx 0.08$ \\ $T_p$& $30$ msec \\ $b$ & $4$ MB \\ $R$ & $>$ $25$ Mbps \quad \cite{upload} \quad but chosen $10$ Mbps\\ $K$ & $4$ txn's/KB \quad for bitcoin \cite{blockchain} \\ \hline \end{tabular} \end{table} We have conducted an event-driven simulation using python by generating events for one day as per the information propagation protocol in \cite{info} for bitcoin blockchain network with $n = 100$ nodes, and $13$ miners having the Hashrate distribution shown in \cite{hashrate}. The simulation are conducted such that delay diameter should be equal to $D \approx 10 sec $ calculated for parameter values shown in TABLE \ref{table:values} using \eqref{eq:D}. \begin{figure}[!t] \centering \begin{subfigure}[t]{0.45\textwidth} \centering \includegraphics[width=\columnwidth]{./figs/block_time_height_bitcoin_600_100_nodes2.eps} \caption{$\lambda=\frac{1}{600}$ (Bitcoin)} \label{fig:block_height_600} \end{subfigure} \hfill \begin{subfigure}[t]{0.45\textwidth} \centering \includegraphics[width=\columnwidth]{./figs/block_time_height_bitcoin_12_100_nodes.eps} \caption{$\lambda=\frac{1}{12}$ (Optimal longest chain rule)} \label{fig:block_height_optimal} \end{subfigure} \hfill \begin{subfigure}[t]{0.45\textwidth} \centering \includegraphics[width=\columnwidth]{./figs/cumulative_count_1_day.eps} 11 \caption{$\lambda=1$ (UL-blockDAG protocol)} \label{fig:dag_blocks} \end{subfigure} \caption{Time in sec vs Number of blocks for a duration of $1$ day.} \end{figure} We have chosen the optimal block creation rate $\lambda = \frac{1}{12}$ ($ \frac{1}{\lambda} > D $). Fig. \ref{fig:block_height_600} and Fig. \ref{fig:block_height_optimal} show the block height w.r.to time of creation. In both cases, the main chain growth rate of simulations is satisfied the theoretical lower bound \eqref{eq:beta_inf} for longest chain rule consensus protocol. Fig. \ref{fig:block_height_optimal} also shows the significant increase in TPS to $\approx 4000$ per day. The simulations carried out for UL-blockDAG protocol with $\lambda = 1$ block/sec (or block interval is $1$ sec). Fig. \ref{fig:dag_blocks} shows block growth rate w.r.to to time and compared it with the theoretical lower bound \eqref{eq:beta_dag_inf}. The results show an increase in block growth rate with approximately a block per every second due to blockDAG structure of ledger and the security guaranteed by the UL-blockDAG protocol. \subsection{Correctness of Algorithm \ref{Algorithm2} through simulations} \begin{figure}[!t] \begin{subfigure}[t]{0.45\textwidth} \includegraphics[width=\linewidth]{./figs/attacker_honest_33.eps} \caption{$q = 0.33$} \label{fig:30} \end{subfigure} \hfill \begin{subfigure}[t]{0.45\textwidth} \includegraphics[width=\linewidth]{./figs/attacker_honest_50.eps} \caption{q = 0.51} \label{fig:50} \end{subfigure} \caption{All the blocks created by the miners in a duration of 86 seconds. Attacker blocks are shown in red color, and other miners' blocks are shown in different colors.. Blocks created by the attacker from height $\mathbf{3-7}$ are not included in $\textbf{blueList}$. The coincidence of the blocks created by different miners (with different colored blocks) at each block height indicates multiple blocks at each height due to the ledger's DAG structure.} \label{fig:attacker_honest} \end{figure} We generated the events such that the attacker with $33.33\%$ (and $51 \%$) of hash rate follows the double-spending strategy similar to an example shown in Fig. \ref{fig:algo_2} from $height = 3$ to $height = 7$ by choosing $k=5$. Fig. \ref{fig:attacker_honest} shows a part (for a duration of $86$ sec) of total confirmed blocks ($\textbf{blueList}$) created by all miners in the network, where the attacker blocks (red color) from height $\mathbf{3-7}$ are not included in the $\textbf{blueList}$, and only honest blocks are present from height $3$ to $7$ as per Algorithm \ref{Algorithm2}. \subsection{The fairness of the proposed models} \begin{figure}[!t] \centering \begin{subfigure}[t]{0.45\textwidth} \centering \includegraphics[width=\columnwidth]{./figs/Hashrate_reward_bitcoin_600_100_nodes.eps} \caption{$\lambda=\frac{1}{600}$ (Bitcoin)} \label{fig:sim_600} \end{subfigure} \hfill \begin{subfigure}[t]{0.45\textwidth} \centering \includegraphics[width=\columnwidth]{./figs/Hashrate_reward_bitcoin_12_100_nodes.eps} \caption{$\lambda=\frac{1}{12}$ (Optimal longest chain rule)} \label{fig:sim_optimal} \end{subfigure} \begin{subfigure}[t]{0.45\textwidth} \centering \includegraphics[width=\columnwidth]{./figs/hashrate_reward_1_86400_1.eps} \caption{$\lambda = 1$ (UL-blockDAG)} \label{fig:sim_dag} \end{subfigure} \caption{Hashrate Vs Rewards proportion for $1$ day.} \end{figure} The fairness of both frameworks optimal longest chain rule and UL-blockDAG are shown in Fig. \ref{fig:sim_optimal}, and Fig. \ref{fig:sim_dag}, which shows the proportion of the rewards (shown by red dots) of each miner are nearly equal to their proportion of the hash rates (shown by a line) in the network and is comparable with the rewards proportion for $\lambda = \frac{1}{600}$ shown in Fig. \ref{fig:sim_600}. These results show that the longest-chain rule with an optimal block creation rate of $\lambda = \frac{1}{D}$ and UL-blockDAG protocol with $\lambda = 1$ blockchain networks perform similar to the bitcoin system with block creation rate of $\frac{1}{600}$. Fig. \ref{fig:beyond_optimal} show that in a longest chain rule protocol with the block ceration rate beyond the optimal point \eqref{eq:opt_lam_N}, the miner with the largest hash rate will dominate the system with more rewards than her proportion of the hash rate, resulting in possible double-spend attack by the dominant miner in the network. \begin{figure}[!t] \centering \includegraphics[width=\columnwidth]{./figs/Hashrate_reward_bitcoin_5.eps} \caption{$\lambda=\frac{1}{5}$ \quad ($\lambda > \frac{1}{D} $)} \label{fig:beyond_optimal} \end{figure} \section{Conclusions and Future Research} In this paper, we propose two different frameworks for scaling the transaction throughput (TPS) of the PoW based blockchain networks without compromising the fairness of the system. In the first framework, we obtained an analytical expression for the optimal block creation rate and optimal throughput by considering the bitcoin network as Erd$\ddot{o}$s - R$\acute{e}$nyi random network topology. In the second framework, we show the graph clustering based on the spectral graph theory concepts for DAG to separate the blocks created by an attacker with a double-spend strategy. The simulation results show that Algorithms 2 separates the attacker blocks with different attacker hash rates (0.33 and 0.51) when an attacker tries to attempt a double-spend attack. Algorithm \ref{Algorithm3} orders the blocks in a linear order, making the protocol suitable for smart contract applications. In both frameworks, the results show a significant improvement in the transaction throughput and the fairness of the network in terms of the proportion of the miners' rewards and hash rates. The results also compared the simulated block growth rate with the theoretical lower bound derived for both the frameworks. The theoretical minimum number of confirmations show the lesser confirmation times for the transactions of a block. In the future, we compare the different spectral clustering methods for the proposed consensus protocol for optimizing the computational complexity of the blockDAG consensus protocol. We also explore the methods to avoid the repeated redundant transactions stored in the blocks at the same height due to the DAG structure. \ifCLASSOPTIONcompsoc \section*{Acknowledgments} \else \section*{Acknowledgment} \fi We thank the reviewers for their insightful, helpful, and detailed comments. This work is supported by 5G Research and Building Next-Generation Solutions for Indian Market Project, Department of Information Technology, Government of India. The preliminary versions of this paper - "Optimal Transaction throughput in Proof-of-Work based Blockchain Networks" was published in DECENTRALIZED 2019 \cite{optimal}, and "UL-blockDAG : Unsupervised Learning based Consensus Protocol for Blockchain" was accepted for publication in The Second International Workshop on Blockchain and Mobile Applications (BlockApp) co-located with 40th IEEE International Conference on Distributed Computing Systems (ICDCS) 2020 \cite{icdcs}.
{'timestamp': '2021-07-21T02:14:22', 'yymm': '2010', 'arxiv_id': '2010.05447', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05447'}
arxiv
\section{Introduction} \label{sec:intro} Releasing research papers on the arXiv open repository~\cite{arxiv} is becoming a standard in computer science and other fields ~\cite{biorxiv, medrxiv, psyarxiv}. We argue that arXiving provides great benefits to both individual researchers (Section~\ref{sec:researcher}) and a field as a whole (Section~\ref{sec:field}). Moreover, it helps researchers in all career stages; we fail to find circumstances in which researchers do not benefit from arXiving their work. There are opinions, however, that this open science practice should be prohibited or limited to arXiving anonymized papers only. The beliefs underpinning these views are the following: 1. waiting 3-6 months until a paper is accepted at a conference is a minor inconvenience, and 2. arXiv releases lead to an "almost" single blind conference review process, which may reduce diversity and some studies~\cite{Tomkins12708} claim that it favours people from well-known institutions. % We address the first contra argument in Section~\ref{sec:researcher} and single blind review issues in Section~\ref{sec:fairness-single}. \section{Individual researchers benefit from pre-submission arXiving} \label{sec:researcher} We start by discussing the benefits of arXiv to, especially, early career researchers (ECRs), from the opportunities that come from \textbf{early released non-anonymous preprints}. We will call such practice "arXiving" in the rest of the paper. \mypara{Professional identity building instead of blank C.V.} When arXiving early, authors, particularly ECRs, can build professional identities around the work instead of waiting until acceptance. Activities include events, collaborations, and building informal networks of support outside of their institution~\cite{montgomery2018}. All scholarly work can be listed on a C.V. -- including preprints –- to show research output. While having the most recent publication online might not be important for a professor with 200+ publications, for the early career researcher it is the step from zero to one. The same is true for the time -- 6 months can make career life-or-death difference for an ECR. Increased early visibility through preprints allows others to become aware of new authors. For instance recruiters, who, in our experience, contact candidates; it is not candidates sending applications. Other examples include fellow researchers who are looking for speakers at local meetups, non-academic conferences, workshops, departmental seminars, and so on. In the "wait until acceptance" scenario, an ECR could end up with a blank C.V. \emph{for a few years}. This is even more significant now, when publications are required to \emph{enter the PhD program}. \mypara{Protection against independent re-discovery or idea theft.} Even if a paper is well-written and has a useful contribution, there is still a high chance that it will be rejected. The review process, even at the best conferences, is known to be quite random~\cite{nips-experiment}. Low acceptance rates of 20-30\%~\cite{conf-stats} at CVPR and NeurIPS-like top conferences exacerbate the decision noise problem. % The “wait 3-6 months” argument does not account for the research "arms race," meaning that a paper may be scooped before acceptance. By "scooping" we mean that another researcher independently comes up with the same or very similar idea and publishes it earlier. We modeled the paper submission as a Markov process, for details see Figure~\ref{fig:acceptance-vs-scooping}. “Wait 3-6 months” is an understatement -- it is more like "wait 1-3 years and pray to be lucky." In addition to independent re-discovery, a similar idea could be published by the reviewer of the submission. Not because of malicious intent -- most reviewers respect the strict confidentiality of the review process -- but because of unconscious idea generation, triggered by reading the submission. If an ECR waits for the paper to be accepted and it gets scooped, then there is no way to prove that they had the original idea months or years before. This is extremely unfair and painful, especially if the idea becomes influential and highly cited. On the other hand, if the researcher uploads the work on arXiv, they get a priority timestamp and can start to get cited. Even if someone else presents a similar idea at a conference first, the affected ECR is in a much better position with arXiv. One of the examples of protection by arXiving is a story about SiLU~\cite{Silu2016} vs Swish~\cite{swish2017} activation, which are exactly the same function. SiLU was first proposed in an arXiv paper in June 2016 by Hendrycks and Gimpel and rejected from ICLR 2017~\cite{silu-reject}. Later, in 2017, the same activation was proposed as Swish by a Google Brain group and it was accepted to the ICLR 2018 Workshop track~\cite{swish-accept}. The SiLU was unnoticed, while Swish gained popularity. The arXiv publication helped to establish priority and give the activation function the original name and reference, SiLU, in deep learning frameworks~\cite{silu-tf, silu-pytorch}. \begin{figure}[tpb] \centering \includegraphics[width=0.32\linewidth]{figures/comp_prob_02.pdf} \includegraphics[width=0.32\linewidth]{figures/comp_prob_05.pdf} \includegraphics[width=0.32\linewidth]{figures/comp_prob_08.pdf} \caption{Monte-Carlo simulation (10k runs) of NeurIPS paper acceptance for the different competition levels, with probability 0.2 a paper is accepted. If not accepted, with probability $P_{\textit{comp}}$, then a similar idea comes to another researcher and she submits it to NeurIPS. If the competitors' paper is accepted earlier, the outcome is "scooped". The paper is resubmitted until "accept" or "scooped".} % \label{fig:acceptance-vs-scooping} \end{figure} \mypara{Protection against gate-keeping.} ECRs, especially from non-mainstream labs, may have difficulty writing papers such that they conform to the norms of the community, in terms of framing their ideas and expressing them with established vocabulary. This is even more true for people with non-ML/CV backgrounds and novel ideas. Their papers could be described as “The Puppy with 6 toes"~\cite{how-to-write-good-cvpr} and are easily rejectable. Without arXiv, review gatekeeping is a single point of failure, which is hard to pass even for experienced researchers. Famous and less famous examples are: \begin{itemize}[noitemsep, leftmargin=*] \item{The most cited computer vision paper for decades, SIFT~\cite{SIFT1999}, took three years to get accepted, first submitted in 1997, accepted as a poster in 1999, journal version published in 2004~\cite{Krig2016}.} % \item{SqueezeNet~\cite{squeezenet2016} was rejected from ICLR because, the “novelty of the submission is very limited," ~\cite{squeezenet-review}, while already having wide adoption and >100 citations. Now it has almost 3000 citations on Google Scholar despite never having been officially published in a conference or journal.}% \item{Now famous one-cycle learning rate policy~\cite{OneCycle2018} and super convergence~\cite{smith2019superconvergence} papers by Leslie Smith. Smith released the original work on arXiv in 2015~\cite{smith2015cyclicalarxiv}. The first paper was eventually published in WACV 2017~\cite{smith2017cyclicalwacv}. Its follow-up work, the super-convergence~\cite{smith2017superconvergence} paper was rejected from ICLR-2018~\cite{superconv-review}. Then the fast.ai team read and implemented it in their framework. Later, in 2019, it was accepted at a defence-related conference~\cite{smith2019superconvergence} little-known in the computer vision community.} \end{itemize} \mypara{Distribution; arXiv has become the main "new results feed," from which people discover new work}. A whole ecosystem has been evolving around arXiv. Services like arxiv-sanity~\cite{arxiv-sanity}, arxiv-vanity~\cite{arxiv-vanity}, Papers-with-Code~\cite{paperswithcode}, arxiv-daily-type twitter accounts and recent Papers-with-Code-arXiv integration~\cite{arxiv-blog, paperswithcode-medium} allow researchers cope with the flood of published papers and supplementary materials. Moreover, arXiv is monitored by many practitioners, who are not concerned about whether the work has been endorsed by others, if there is evidence that a method is working well in practice. Work which is not on arXiv reaches much fewer people. There is also a difference if the paper is arXived before or after acceptance. According to Feldman~\emph{et al}\onedot~\cite{feldman2018citation}, "papers submitted to arXiv before acceptance have, on average, 65\% more citations in the following year compared to papers submitted after". \section{Research and broader community benefit from arXiv} \label{sec:field} \mypara{Faster and broader distribution and better explanation.} The most obvious benefit of arXiving is the distribution of authors' research to the community. This research and ideas are often clarified and explained through interaction or blog posts. Such explanatory and presentation work is especially important for new ideas~\cite{hamming1997art} and is logistically much more difficult for anonymous work. Public code and data releases are without the administrative overhead of keeping track of anonymity at all stages. While research results can be distributed in an anonymous preprint, the need to maintain anonymity restricts feedback and code sharing. \mypara{Open access and Funding.} While companies finance research from their own profits, most university research is done on taxpayers’ money. This brings, at the very least, an obligation to share research results in a timely manner. Relatedly, arXiv serves an important role for public access to documents for grant reports and public talks. \mypara{Crowdsourcing review of preprints is the way of Open Science and it tackles more aspects than traditional review.} Let us recall all the discussions and critique about the GPT-2~\cite{GPT2} and GPT-3~\cite{GPT3} models by OpenAI. While the opinions on GPT2/3 and its impact itself might vary, it is hard to deny that GPT2/3 started a large community-wide discussion concerning long-term impact, and machine learning bias in general. These discussions arose on Twitter and blogs at the time that the technical report and later, code, was released for GPT-2, which was posted only as an OpenAI tech report and similarly to GPT-3, released on arXiv. Would three standard reviews from NeurIPS lead to a discussion with the same scale and impact? \mypara{arXiv levels the playing field and reduces famous labs' advantages.} Famous labs have experienced researchers, especially in writing papers, huge hardware resources, etc. Thus, someone from a hypothetical FAANG\footnote{This acronym refers to the most prominent tech companies: Facebook, Amazon, Apple, Netflix, Google.} lab has extensive experience in how to write a “may be boring, but hard to kill” paper~\cite{how-to-write-good-cvpr}. While arXiv and social media publicity could make a difference for famous labs' paper acceptance, famous labs have lots of other weapons in their arsenal such as experienced writers and other resources affecting paper acceptance. Removing arXiv for famous labs would not make a huge difference. Unlike them, ECRs have comparatively less \dmytro{tools in their arsenal} and removing the option to preprint before acceptance means a much reduced ability to participate in the research community. There is a Russian saying for this situation, "\foreignlanguage{russian}{Пока толстый сохнет худой сдохнет}”, -- "While the fat one dries, the thin one dies".% Moreover, \textbf{ECRs are more dependent on having formal publications in their C.V.} than senior researchers. If pre-submission arXiving was not allowed at major conference, ERCs would find it very difficult, unlike senior researcher, to trade early publication, code release and impact for a missed opportunity to publish at a top conference. \section{The single blind review is not much worse than double blind.} \label{sec:fairness-single} \mypara{Single-vs-double blind studies -- the bias reduction is small.} The research quoted in some anti-arXiv arguments are studies by Tomkins~\emph{et al}\onedot~\cite{Tomkins12708} about WSDM-2017 and the study by Bharadhwaj~\emph{et al}\onedot~\cite{bharadhwaj2020deanonymization} by about ICLR 2019-2020. Before delving into details, let us summarize both. They report, via sophisticated statistics, that deanonymization could change the chances of acceptance by 3-4 or less percentage points. In comparison, Lawrence and Cortes~\cite{nips-experiment} have found that the randomness of the review process itself is around 50\%, which is an order of magnitude bigger. We argue, that given such a level of noise, it does not make any sense to trade off all the benefits arXiv provides (Sections~\ref{sec:researcher}, \ref{sec:field}) for removing possible bias, which is 10x less that the randomness of the peer review itself. Besides, the first study contains methodological flaws, precisely explained in \cite{CritisismPNAS}. Specifically, Stelmakh~\emph{et al}\onedot\cite{CritisismPNAS} have shown that "the test used by Tomkins~\emph{et al}\onedot~\cite{Tomkins12708} can, with probability as large as 0.5 or higher, declare the presence of a bias when the bias is in fact absent (even when the test is tuned to have a false alarm error rate below 0.05)." Moreover, "two factors – (d) asymmetrical bidding procedure and (e) non-random assignment of papers to referees – as is common in peer-review procedures today may introduce spurious correlations in the data, breaking some key independence assumptions and thereby violating the requisite guarantees on testing." We point the reader to~\cite{CritisismPNAS} for more details and focus on the more recent study by Bharadhwaj~\emph{et al}\onedot~\cite{bharadhwaj2020deanonymization}. The results can be simplified as follows. Bharadhwaj~\emph{et al}\onedot have found a correlation (authors specifically emphasize that the study does not claim any causality) between pre-acceptance arXiv release and acceptance rate. Specifically, releasing a paper on arXiv might increase its chances of acceptance up to 5 percentage points in the best case for almost everyone, or decrease your chances by 3 percentage points if the authors are totally unknown. Given that the acceptance rate at ICLR is 20-25\%, we argue that the benefits from having preprints, as stated in Section~\ref{sec:researcher}, protecting you in the very likely case of rejection, is much more important for an ECR than a possible 3 percentage point rejection risk increase. \mypara{Authors should not be the only ones, who ensure the unbiased review.} Instead of putting all the burden (e.g. by requiring anonymous arXiving) on the authors, effort might be directed to reviewer training. The computer vision community already started to do this by hosting CVPR Tutorial on writing good reviews~\cite{good-review-tutorial2020}. Another direction is to adjust the review process to minimize possible biases. For example, the reviewers might be asked to read the paper and write the initial review without googling the paper to avoid possible influence of knowing the author names. Such process is not uncommon in grant proposal reviewing. After the initial review, one could perform google and literature search for the related work etc. \section{Conclusions} \label{sec:conclusion} Double-blind review combined with banning non-anonymous preprints does not come for free. While possibly removing a small bias towards "big names", it introduces other biases and limitations. Such limitations are especially harmful for those who are not yet fully established. Is it worthwhile to do arXiving early? We argue that the default research workflow should be the following: once researchers write-up the research piece, they decide if want to submit to a conference, release on arXiv or do both. The choice depends on the particular situation, and only the researchers themselves should decide how to share their work. Finally -- we have likely missed some aspects of this imporant issue and we hope that this paper will be a good starting point for a community-wide discussion. We will post updated versions on arXiv. \section*{Broader Impact} The submission is a position paper, discussing the impact of some aspects of submission and reviewing rules on individual researchers and the research community. The topic of the paper, and thus its content, falls under the "Broader Impact" rubric. \medskip \small \bibliographystyle{plain}
{'timestamp': '2020-10-13T02:26:07', 'yymm': '2010', 'arxiv_id': '2010.05365', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05365'}
arxiv
\section{Introduction} Video face recognition has received increasing interest from the community in recent years \cite{crosswhite2018template, cui2013fusing, hu2014discriminative, li2013probabilistic, liu2014toward, mendez2013volume, parkhi2014compact, taigman2014deepface, schroff2015facenet}, partially due to the growing volume of video content. Compared to an image, a video sequence contains more information about the subject's faces, such as varying poses, expressions, motion, and illumination. The key challenge for video-based face recognition is how to effectively combine facial information available across different video frames to get an appropriate representation of the face in the video. Deep Convolutional Neural Networks (DCNNs) trained on a large dataset have shown the ability to generate compact and discriminative face representations for images that are robust to pose variations, image quality, blur, and occlusions \cite{liu2017sphereface, schroff2015facenet, sun2015deeply, taigman2014deepface}. The naive approach is to represent video as a set of frames and use face features extracted by deep neural network for each frame \cite{schroff2015facenet, taigman2014deepface}. Then the subject's face in the video, called face track, is represented as an unordered set of vectors that allows maintaining the information across all frames. However, this is not computationally efficient for comparing two face tracks. It requires a fusion of matching results and comparison across all pairs of vectors between two face templates. Except for $O(n^2)$ complexity per match operation, face track requires $O(n)$ space per video face, where $n$ - the average number of video frames. That is why most methods aggregate feature vectors into fix-size feature representation for each face track \cite{liu2018dependency, rao2019learning, rao2017attention, sohn2017unsupervised, xie2018comparator, yang2017neural}. It allows constant-time matching computation instead of evaluating all powers. Initially, the aggregation challenge was considered when GIPHY has built its own open-source model called “Giphy Celebrity Detector”\cite{} to automatically annotate GIFs featuring celebrities. This provides better search results for entertainment related queries, which is a vital aspect of GIPHY everyday traffic. Due to the fact that GIFs could be also represented as a set of frames we consider the feature aggregation networks. Unfortunately, the existing methods don't consider multi-identity face appearance in frames. For example, GIFs from popular shows contain more than one face. In this paper, we propose an aggregation model based on self-attention, which can be applied for videos that contain single or multiple identities. Also, we create a synthetic dataset for multi-identity video face recognition. \section{Related Work} \subsection{Image Face Recognition} Face recognition is an actively studied domain with significant achievements in identification and verification tasks \cite{wang2016face, wang2018cosface, zhang2016joint, liu2017sphereface} and a great part of that success is due to deep convolutional neural networks. Most approaches are focused on learning the embedding vector for face representation. The following works focus on exploring different loss functions to improve the feature representation. Both contrastive \cite{chopra2005learning, hadsell2006dimensionality} and triplet \cite{hoffer2015deep, wang2014learning} losses are usually used to increase the Euclidean margin for better feature embedding. The center loss proposed in \cite{wen2016discriminative} learns centroids for features of each identity to reduce intra-class variance. A large margin softmax (L-softmax) \cite{liu2016large} adds angular constraints to each identity to improve feature discrimination, and angular softmax (A-softmax) \cite{liu2017sphereface} adds weights normalization for L-softmax. The ArcFace uses additive angular margin loss \cite{deng2019arcface}. \subsection{Video Face Recognition} Existing methods are classified into the following categories: ones that exploit temporal dynamics and ones that treat video as an orderless set of images. The first group of methods heavily relies on RNNs to account for the temporal dependencies in frame sequences. For example, RNN was employed for head pose estimation \cite{gu2017dynamic}, facial expression recognition \cite{graves2008facial}, and emotion recognition \cite{fan2016video, zhang2018spatial}. Many previous methods have considered the representation of the set of face images as probabilistic distribution \cite{arandjelovic2005face, shakhnarovich2002face}, n-order statistics \cite{lu2013image}, affine hulls \cite{yang2013face, hu2011sparse, cevikalp2010face}, SPD matrices \cite{huang2015log}, manifolds \cite{lee2003video, harandi2011graph, wang2008manifold}, etc. Then, the recognition is performed via similarity or distance measures. Other methods aim to train a supervised classifier on each image set or video to obtain correspondent representation \cite{parchami2017using}. These methods work well under constrained settings but usually struggle to handle the challenging unconstrained scenarios with significant appearance variations. The aggregation based models aim to fuse a set of deep feature vectors into a single vector. It was shown in \cite{best2014unconstrained} that aggregation of multiple face images increases the recognition performance of person identification. Compared to simple average pooling \cite{chen2018unconstrained, ding2017trunk, chen2015end, chowdhury2016one, deng2019arcface}, the recent works show promising results by incorporating the visual quality information on instance level via detection score \cite{ranjan2018crystal} or predicted quality scores \cite{yang2017neural, liu2017quality}. A Component-wise Feature Aggregation Network \cite{gong2019video} aggregates the feature vectors in each component separately by considering the prediction of their quality. The redundancy issue in the video frames is tackled in \cite{gong2019low}. However, none of these approaches consider the multi-identity video recognition setup. \section{Aggregation networks} In the following sections, we'll review proposed single and multi-identity aggregation architectures. To our knowledge, the aggregation of multiple identities has not been addressed so far. We consider a multi-head self-attention mechanism that has been successfully used to encode/decode sequence representation as in \cite{vaswani2017attention}, achieving superior results and better parallelization compared to recurrent encoder/decoder framework. It is used to achieve reweighting according to the context of the features. \begin{figure} \begin{center} \includegraphics[width=1.0\linewidth]{images/aggregator_self_attention.jpg} \end{center} \caption{Example of video sequence aggregation network using self-attention. $n$ is the number of faces in a face track, $d$ is a dimensionality of the embedding, $N$ - is the number of consecutive self-attention blocks of the encoder. Figure is read in a bottom-up fashion.} \label{fig:self_attention_arc} \end{figure} \subsection{Feature extractor} To get a compact representation for each image in a given set, we use a publicly available \href{https://github.com/deepinsight/insightface}{ArcFace model} \cite{deng2019arcface} pretrained on the MS1MV2 dataset \cite{guo2016ms}. It is considered to be state-of-the-art in a lot of public verification/identification benchmarks at the time. Additionally, we experiment with a lightweight feature extractor, in particular, MobileFaceNet \cite{chen2018mobilefacenets}. The main purpose of that experiment is to investigate the aggregation results on features with a lower representational capacity. \subsection{Single-identity aggregation} \label{sident} Given a set of ordered frames $\{x_1, x_2, x_3, x_4,\dots ,x_n\}$ (face track) and their corresponding features $\{f_1, f_2, f_3, f_4,\dots ,f_n\}$, aggregation should be performed to produce a single vector representation $\boldsymbol{r}$. To represent a face track from different perspectives and assign weight to a particular frame with respect to its context, we use a multi-head self-attention mechanism (Figure \ref{fig:self_attention_arc}). At first, $\boldsymbol{K}$, $\boldsymbol{V}$, $\boldsymbol{Q}$ projections are computed by learnable transformation matrices on $\boldsymbol{(F+P)}$, where $\boldsymbol{F}$ is an extracted embedding matrix, and $\boldsymbol{P}$ is a positional encoding matrix. Later, reweighted embeddings computed as: \begin{equation} \label{self_attn_form} RHead = Softmax(\frac{QK^T}{\sqrt d})V \end{equation} \begin{align*} RMultiHead = Concat(RHead_0,RHead_1,\\ \dots,RHead_n)W_o \end{align*} where $d$ - is the dimensionality of a feature vector, $RHead$ - reweighted representation received from single attention head, $RMultiHead$ - final reweighted representation from multiple heads and $W_o$ - output transformation matrix. Each reweighted projection is assigned an element-wise or component-wise score (as in \cite{yang2017neural} or \cite{gong2019video}). According to those scores, aggregation is done on the original features in the following way: \begin{align*} \boldsymbol{s} &= RMultiHead \cdot W_q & \boldsymbol{q} &= Softmax(\boldsymbol{s}) \\ \boldsymbol{r} &= \sum_{i=1}^{n} f_i*\boldsymbol{q_i} \end{align*} where $\boldsymbol{s}$ is a vector of unnormalized quality scores, $\boldsymbol{q}$ is a vector of softmax normalized scores, and $W_q$ is a learnable matrix to retrieve the quality score of given projection. \begin{figure} \begin{center} \label{fig:multi_backbone} \includegraphics[width=1.0\linewidth]{images/mident_agg.jpg} \end{center} \caption{Proposed multi-identity architecture. $n$ - specifies the number of embeddings in a video, $d$ - dimensionality of the embedding, $k$ - number of unique identities within a video.} \end{figure} \subsection{Multi-identity aggregation} The formulation of the task is similar to section \ref{sident} with the output being a set of vectors $[r_1,r_2,\dots,r_k]$ where $k$ is the number of unique identities within a video sequence. Given a set of $n$ features, multiple identities aggregation could be decomposed into two parts: \begin{enumerate} \item finding $k$ face tracks within a set. \item aggregating features withing each face track. \end{enumerate} By representing relation to the face tracks as a $(n,n)$ binary matrix, our goal is to find a set of cliques. First, to create a binary mask, we need to classify all possible feature pairs within a video (that is ${n}\choose{2}$). After that, to remove any ambiguity and create a set of face tracks, we need to separate features into strongly connected components. To do that we implement a greedy post-processing. According to \cite{ranjan2018crystal} norm of the embedding could be considered as a proxy to the quality of face embedding. Assignment of components is performed in descending order specified by the Euclidian norm of the embeddings: $norm_i= ||X_i||_2$, where $X$ is a matrix of extracted embeddings. All elements which lie in a class relation with a given example $i$ are retreived (e.i $\forall j\in {\mathbf{R}(X_i,X_j)}$, where $\mathbf{R}$ is a class relation), assigned to the component and zeroed out in the initial binary matrix. The code snippet on Python is below. \begin{lstlisting}[language=Python] import numpy as np def postprocess_mask(p_mask, q_scores): ''' p_mask :np.array(nxn) predicted mask q_scores : np.array(nx1) l2 norms of input embeddings ''' p_mask_c = p_mask.copy() f_mask = np.zeros_like(p_mask) q_sorted = np.argsort(q_scores) for q_ind in q_sorted[::-1]: f_mask[q_ind] = p_mask_c[q_ind] non_zero_els = np.argwhere( f_mask[q_ind]!=0 ) p_mask_c[:,non_zero_els] = 0 p_mask_c[non_zero_els,:] = 0 return f_mask \end{lstlisting} \label{greedy_postprocessing} Starting from the embedding with the highest norm, cliques are greedily assigned, until no elements are left unassigned. The resulting matrix is converted to the a of zero-padded face tracks and then aggregated using the single identity aggregation network. \section{Experiments} \subsection{Datasets and protocols} To train our aggregator, we use the \textbf{UMDFaces} \cite{bansal2016umd} dataset. Additionally, we append a dataset with short GIFs of different identities parsed from publicly available API through \href{https://giphy.com/}{giphy.com}. Collected and preprocessed dataset will be made publicly available. For GIFs collection, we used their public API to get the most relevant GIFs for approximately 2300 celebrities. From each GIF, we sampled 5 frames evenly distributed in time. As a result, on average, we obtained about 150 GIFs for each indentity, in total, almost 3M frames. Sampled face tracks and overall training datasets statistics could observed in Figure \ref{fig:gifs_examples} and Table \ref{data_stats} \begin{figure} \begin{center} \includegraphics[width=1.0\linewidth]{images/giphs_examples.jpg} \end{center} \caption{Face tracks sampled from GIFs dataset.} \label{fig:gifs_examples} \end{figure} \begin{table} \begin{center} \begin{tabular}{| c | c | c | c | c |} \hline \textbf{Dataset} & \multicolumn{1}{ c|}{\textbf{Frames}} & {\textbf{Identities}} & {\textbf{Sessions}}& {\textbf{Length}} \\ \hline UMDFaces & 3735476 & 3107 & 22075 & 161\\ \hline GIFs & 637939 & 2304 & 137739 & 4.6\\ \hline \end{tabular} \label{data_stats} \end{center} \caption{Training datasets descriptions. Length specified as an average number of frames per session. GIFs statistics correspond to the post-processed dataset.} \end{table} \textbf{IJB-C} \cite{maze2018iarpa} dataset is used for benchmarking. IJB-C has 3,531 indentities with 31.3K still images and 117.5K frames from 11, 779 videos. \subsection{Preprocessing} In the UMDFaces dataset, faces are detected using publicly available MTCNN model \cite{zhang2016joint}. Using 5 facial keypoints, the similarity transform is applied to align faces. To match all detected faces with UMDFaces annotations, an IOU of 0.4 is chosen as a threshold. All non matched faces are ignored. We use the same detector for GIFs dataset. It is important to note, that since GIF may contain multiple faces and not just the ones of a desired celebrity, we used pretrained ArcFace model to get feature vectors for detected faces, computed mean vectors for each class and filtered out those faces whose vectors do not lie within specified cosine distance threshold of 0.7 from the corresponding class center. \subsection{Training details} \label{single_train} \textbf{Single identity training}: The aggregator is trained on the UMDFaces+GIFs dataset using an additive angular margin loss \cite{wang2018additive}. The radius of the hypersphere and additive margin are set to 16.0 and 0.35, respectively. The paramaters are trained using a RAdam optimizer \cite{liu2019variance} with default values. For the encoder, we use an official implementation of \href{https://github.com/tensorflow/models/blob/master/official/transformer/model/transformer.py}{Transformer} on Tensorflow, with a single modification (removing the trainable embedding block). The depth of the encoder is set to 4, the number of heads for the aggregator on top of ResNet and MobileNet is set to 8 and 4, respectively. Attention and ReLU dropout rates are specified as 0.3 and 0.4. All other hyperparameters are populated with the default values. For validation, we employ an identity-based split. Due to the fact that identities in the validation are not present in the training set, we define a metric for the early stopping - intra-class proximity gain, defined as: $$ ICPG = E(Intra(AVE(X))) - E(Intra(SA(X)) $$ where $X$ - is the set of templates for aggregation, $SA$ and $AVE$ are self-attention pooling and average pooling respectively, $Intra(Y)$ - is a set of distances between the aggregated elements of $Y$ which belong to the same class. Specifically, each mini-batch includes 256 templates that are randomly sampled from 128 identities, 32 images per template. \newline \textbf{Multi-identity training}: There are no multi-identity annotated video datasets to our knowledge, so we synthetically created one (combining UMDFaces and GIFs). We sample a random number of identities (from 2 to 64) and choose a single session for each identity. These sessions are concatenated into a single one, which is then used for sampling 256 frames. These frames form a multi-identity video. The order of frames is preserved and used later during face tracks creation. For the binary mask generation, there may be a trainable classifier, but we have found that simple thresholding based on the cosine distance results in higher recall and precision. To train the identity aggregator on top of the post-processed mask, we employ a teacher forcing with a scheduled sampling \cite{bengio2015scheduled}. For the first 5000 iterations, cosine decay scheduler is used to specify the probability of mixing ground truth masks with the post-processed one. After that, only a predicted mask is used for the aggregation. \begin{figure} \begin{center} \includegraphics[width=1.0\linewidth]{images/attention_extremums.jpg} \end{center} \caption{Attention extremums within the face tracks on the validation set. The first row represents the highest values, the second one - the lowest.} \label{fig:attention_dist} \end{figure} \subsection{Results for single-identity aggregator} \subsubsection{UMD+GIFs validation set} \begin{table} \begin{center} \begin{tabular}{| c | c | c | c | c |} \hline \textbf{Aggregator} & \multicolumn{1}{ c |}{\textbf{ICPG}} \\ \hline SA pooling (ResNet) & 2.8* $1e^-3$ \\ \hline SA pooling (MobileNet) & 5.5* $1e^-3$ \\ \hline \end{tabular} \label{sing_icpg} \end{center} \caption{ICPG on the validation set} \end{table} \begin{figure} \begin{center} \includegraphics[width=1\linewidth]{images/improper_context_att.jpg} \end{center} \caption{Attention distribution on the face track with erroneous elements. The first row - ordered frames of the given face track. The second row - frames ordered by the Euclidian norm of their corresponding embedding. The third row - frames ordered according to their self-attention quality score. The elements which do not belong to the given identity are emphasized with the red arrow.} \label{fig:attention_dist_error} \end{figure} On the validation set, we report ICPG for the aggregators on top of different feature extractors as show in Table \ref{sing_icpg}. Additionally, we attach visualization of attention extremums on the given set in Figure \ref{fig:attention_dist}. We have found that there are some face tracks in the UMDFaces which contain erroneously assigned elements. Also, we demonstrate in Figure \ref{fig:attention_dist_error} that by resorting to the general context, the self-attention mechanism helps to downweight such frames during final aggregation (despite their high visual quality). \subsubsection{IJB-C} 1:1 Verification on mixed set and 1:N end-to-end video probes are tested. AVE (average) and SA (self-attention) poolings are compared and results shown in Table \ref{sing_roc}. The proposed approach results in a higher AUC, TAR, top-1 accuracy for both aggregators based on MobileNet and ResNet feature extractors. Notably, we observe that there is a more significant gap between aggregation and averaging based on the MobileNet feature extractor. It shows that the aggregation is more beneficial on the networks with the lower representational capacity. \begin{table} \begin{center} \begin{tabular}{| c | c | c | c | c |} \hline \textbf{Aggregator} & \multicolumn{2}{ c |}{\textbf{Ver}} & {\textbf{Id}} \\ \cline{2-4} & \textbf{TAR} & \textbf{AUC} & \textbf{Rank-1}\\ \hline AVE pooling (ResNet) & 83.90 & 99.39 & 82.54 \\ \hline SA pooling (ResNet) & \textbf{87.83} & \textbf{99.44} & \textbf{82.79}\\ \hline AVE pooling (MobileNet) & 55.58 & 98.92 & 66.73 \\ \hline SA pooling (MobileNet) & \textbf{62.04} & \textbf{99.01} & \textbf{67.48}\\ \hline \end{tabular} \label{sing_roc} \end{center} \caption{Verification TAR is reported under FAR=$1e-6$, identification rate is reported as rank-1 accuracy.} \end{table} \begin{figure} \begin{center} \label{fig:roc_resnet_agg} \includegraphics[width=1.0\linewidth]{images/resnet_agg.png} \includegraphics[width=1.0\linewidth]{images/mobile_agg_roc.png} \end{center} \caption{ROC curves of SA Pooling vs AVE Pooling on ResNet (top) and MobileNet (bottom) feature extractors.} \end{figure} \subsection{Results for multi-identity} \subsubsection{UMD+GIFs validation set} The number of regressed identities is calculated on the proposed multi-identity videos. Above mentioned binary mask producer results in MPE (mean percentage error) of $4.2\%$. We presume that using different post-processing techniques for masks, such as transitive closure, could be used to lower the MPE. \subsubsection{IJB-C} \begin{figure} \begin{center} \label{fig:roc_resnet} \includegraphics[width=1.0\linewidth]{images/multi_identity_roc.png} \end{center} \caption{ROC curves of multi-identity aggregator with the highest norm and the biggest component selection.} \label{fig:roc_multi} \end{figure} \begin{table} \begin{center} \begin{tabular}{| c | c | c | c | c |} \hline \textbf{Multi-identity aggregator} & \multicolumn{2}{ c |}{\textbf{Ver}} & {\textbf{Id}} \\ \cline{2-4} & \textbf{TAR} & \textbf{AUC} & \textbf{Rank-1}\\ \hline Highest norm component & \textbf{81.67} & \textbf{98.58} & \textbf{82.54} \\ \hline Biggest component & 79.55 & 98.30 & 82.02\\ \hline \end{tabular} \label{multi_ijb} \end{center} \caption{Verification TAR is reported under FAR=$1e-6$, identification rate is reported as rank-1 accuracy. Different component selection strategies are compared.} \end{table} Having only a single identity within a session, we introduce two component selection strategies (in order to select a single representation for reference in the session where multiple identities were detected). Component with largest number of frames and a component which contains the embedding of the highest quality are tested. Results are reported in Table \ref{multi_ijb} and ROC curve is displayed on Figure \ref{fig:roc_multi}. \section{Conclusions} In this paper, we propose a novel self-attention aggregation network for learning face representation for any number of identities from a video stream. We show that SAAN outperforms average pooling in general for a single identity. Especially, the usage of SAAN network could be beneficial if vector representation quality degrades, e.g. when using lightweight embeddings from MobileNet. Moreover, the further investigation indicates that SAAN model is robust to erroneous face tracks. Also, we created a dataset for multi-identity aggregation problem and plan to make it available under MIT licence. Our future work will explore the different mask postprocessing approaches and ways to improve the aggregation model for multi-indentity video streams. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-10-13T02:25:39', 'yymm': '2010', 'arxiv_id': '2010.05340', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05340'}
arxiv
\section{Introduction} \label{sec:introduction} By 31st August 2020, coronavirus COVID-19 is affecting 213 countries around the world infecting more than 25 million people and killing more than 800,000. Recently, much attention has been given to build monitoring systems to track the outbreaks of the virus. However, due to the fact that most of the official news sources update the outbreak information only once or twice a day, these monitoring tools have begun to use social media as the medium to get information. There is a massive amount of data on social networks, e.g. about 4 millions of COVID-19 English tweets daily on the Twitter platform. However, majority of these tweets are uninformative. Thus it is important to be able to select the informative ones for downstream applications. Since the manual approaches to identify the informative tweets require significant human efforts, an automated technique to identify the informative tweets will be invaluable to the community. The objective of this shared task is to automatically identify whether a COVID-19 English tweet is informative or not. Such informative Tweets provide information about recovered, suspected, confirmed and death cases as well as location or travel history of the cases. The participants of the shared task were required to provide predictions for the test set provided by the organisers whether a tweet is informative or not. Our team used recently released transformers to tackle the problem. Despite achieving 10$^{th}$ place out of 55 participants and getting high evaluation score, our approach is simple and efficient. In this paper we mainly present our approach that we used in this task. We also provide important resources to the community: the code, and the trained classification models will be freely available to everyone interested in working on identifying informative tweets using the same methodology \footnote{The GitHub repository is publicly available on \url{https://github.com/hhansi/informative-tweet-identification}}. \section{Related Work} \label{sec:related-work} In the last few years, there have been several studies published on the application of computational methods in order to identify informative contents from tweets. Most of the earlier methods were based on traditional machine learning models like logistic regression and support vector machines with heavy feature engineering. \citet{10.1145/1963405.1963500} investigate tweet newsworthiness classification using features representing the message, user, topic and the propagation of messages. Others use features based on social influence, information propagation, syntactic and combinations of local linguistic features as well as user history and user opinion to select informative tweets \cite{6113128,10.1145/2009916.2009954,ICWSM136057}. Due to the fact that training set preparation is difficult when it comes informative tweet identification, several studies suggested unsupervised methods. \citet{10.1145/1653771.1653781} built a news processing system, called \textit{TwitterStand} using an unsupervised approach to classify tweets collected from pre-determined users who frequently post news about events. Even though these traditional approaches have provided good results, they are no longer the state of the art. Considering the recent research, there was a tendency to use deep learning-based methods to identify informative tweets since they performed better than traditional machine learning-based methods. To mention few, \citet{alrashdi2019deep} suggested an approach based on Bidirectional Long Short-Term Memory (Bi-LSTM) models trained using word embeddings. Another research proposed a deep multi-modal neural network based on images and text in tweets to recognise informative tweets \cite{Kumar2020}. Among the different neural network models available, transformer models received a huge success in the area of natural language processing (NLP) recently. Since the release of BERT \cite{devlin-etal-2019-bert}, transformer models gained a wide attention of the community and they were successfully applied for wide range of tasks including tweet classification tasks such as offensive tweet identification \cite{ranasinghe2019brums} and topic identification \cite{yuksel2019turkish}. But we could not find any previous work on transformers for informative tweet classification. Hence, we decided to use transformer for our approach and this study will be important to the community. \section{Task Description and Data Set} \label{sec:task-desscription} WNUT-2020 Task 2: Identification of informative COVID-19 English Tweets \cite{covid19tweet} is to develop a system which can automatically categorise the tweets related to coronavirus as informative or not. A data set of 10K tweets which are labelled as \textit{informative} and \textit{uninformative} is released to conduct this task. The class distributions of the data set splits are mentioned in Table \ref{table:data-set}. \begin{table}[h] \centering \begin{tabular}{l|l|l} \hline \textbf{Data set} & \textbf{Informative} & \textbf{Uninformative}\\ \hline Training & 3303 & 3697 \\ Validation & 472 & 528 \\ Test & 944 & 1056 \\ \hline \end{tabular} \caption{\label{table:data-set} Class distribution of data set splits } \end{table} \section{Methodology} The motivation behind our methodology is the recent success that the transformers had in wide range of NLP tasks like language generation \cite{devlin-etal-2019-bert}, sequence classification \cite{ranasinghe-etal-2020-brums,ranasinghe2019brums,ranasinghe-etal-2020-multilingual}, word similarity \cite{hettiarachchi-etal-2020-brums}, named entity recognition \cite{10.1145/3394486.3403149} and question and answering \cite{yang-etal-2019-end}. The main idea of the methodology is that we train a classification model with several transformer models in-order to identify informative tweets. \subsection{Transformers for Text Classification} \label{subsec:classification} Predicting whether a certain tweet is informative or not can be considered as a sequence classification task. Since the transformer architectures have shown promising results in sequence classification tasks \cite{ranasinghe-etal-2020-brums,ranasinghe2019brums,ranasinghe-etal-2020-multilingual}, the basis for our methodology was transformers. Transformer architectures have been trained on general tasks like language modelling and then can be fine-tuned for classification tasks. \cite{10.1007/978-3-030-32381-3_16} Transformer models take an input of a sequence and outputs the representations of the sequence. There can be one or two segments in a sequence which are separated by a special token [SEP]. In this approach we considered a tweet as a sequence and no [SEP] token is used. Another special token [CLS] is used as the first token of the sequence which contains a special classification embedding. For text classification tasks, transformer models take the final hidden state $\textbf{h}$ of the [CLS] token as the representation of the whole sequence \cite{10.1007/978-3-030-32381-3_16}. A simple softmax classifier is added to the top of the transformer model to predict the probability of a class $c$ as shown in Equation \ref{equ:softmax} where $W$ is the task-specific parameter matrix. The architecture of transformer-based sequence classifier is shown in Figure \ref{fig:architecture}. \begin{equation} \label{equ:softmax} p(c|\textbf{h}) = softmax(W\textbf{h}) \end{equation} \begin{figure}[ht] \centering \includegraphics[scale=0.41]{figures/InfoMiner.png} \caption{Text Classification Architecture} \label{fig:architecture} \end{figure} \subsection{Transformers} \label{subsec:transformers} We used several pre-trained transformer models in this task. These models were used mainly considering the popularity of them (e.g.\ BERT \cite{devlin-etal-2019-bert}, XLNet \cite{yang2019xlnet}, RoBERTa \cite{liu2019roberta}, ELECTRA \cite{clark2020electra}, ALBERT \cite{Lan2020ALBERT}) and relatedness to the task (e.g.\ COVID-Twitter-BERT (CT-BERT) \cite{muller2020covid} and BERTweet \cite{BERTweet}). BERT \cite{devlin-etal-2019-bert} was the first transformer model that gained a wide attention of the NLP community. It proposes a masked language modelling (MLM) objective, where some of the tokens of a input sequence are randomly masked, and the objective is to predict these masked positions taking the corrupted sequence as input. As we explained before BERT uses special tokens to obtain a single contiguous sequence for each input sequence. Specifically, the first token is always a special classification token [CLS] which is used for sentence-level tasks. RoBERTa \cite{liu2019roberta}, ELECTRA \cite{clark2020electra} and ALBERT \cite{Lan2020ALBERT} can all be considered as variants of BERT. They make a few changes to the BERT model and achieves substantial improvements in some NLP tasks \cite{liu2019roberta,clark2020electra,Lan2020ALBERT}. XLNet on the other hand takes a different approach to BERT \cite{yang2019xlnet}. XLNet proposes a new auto-regressive method based on permutation language modelling (PLM) \cite{10.5555/2946645.3053487} without introducing any new symbols such as [MASK] in BERT. Also there are significant changes in the XLNet architecture like adopting two-stream self-attention and Transformer-XL \cite{dai-etal-2019-transformer}. Due to this XLNet outperforms BERT in multiple NLP downstream tasks \cite{yang2019xlnet}. We also used two transformer models based on Twitter; CT-BERT and BERTweet. The CT-BERT model is based on the BERT-LARGE model and trained on a corpus of 160M tweets about the coronavirus \cite{muller2020covid} while the BERTweet model is based on BERT-BASE model and trained on general tweets \cite{BERTweet}. \begin{table*}[!htbp] \centering \begin{tabular}{l|ccc|ccc} \hline \textbf{Strategy} & \multicolumn{3}{c|}{Single-model} & \multicolumn{3}{c}{MSE (N=3)} \\ \hline \multicolumn{1}{l|}{\textbf{Model}} & \textbf{P} & \textbf{R} & \textbf{F1} & \textbf{P} & \textbf{R} & \textbf{F1}\\ \hline \textit{bert-large-cased} & 0.9031 & 0.8686 & 0.8855 & 0.8884 & 0.8941 & 0.8912 \\ \textit{roberta-large} & 0.9056 & 0.8941 & 0.8998 & 0.8926 & 0.9153 & 0.9038 \\ \textit{albert-xxlarge-v1} & 0.9009 & 0.8856 & 0.8932 & 0.9032 & 0.8898 & 0.8965 \\ \textit{xlnet-large-cased} & 0.8778 & 0.9280 & 0.9022 & 0.8743 & 0.9280 & 0.9003 \\ \textit{electra-large-generator} & 0.8297 & 0.8771 & 0.8527 & 0.8901 & 0.8750 & 0.8825 \\ \textit{bertweet-base} & 0.8710 & 0.8968 & 0.8753 & 0.8741 & 0.8998 & 0.8780 \\ \textit{covid-twitter-bert} & 0.8984 & 0.9364 & 0.9170 & 0.9002 & 0.9364 & 0.9180 \\ \hline \end{tabular} \caption{\label{table:transformer-models} Results of different transformer models (All these experiments are executed for 3 learning epochs with $1e^{-5}$ learning rate.) } \end{table*} \subsection{Data Preprocessing} \label{subsec:data_preprocessing} Few general data preprocessing techniques were employed with InfoMiner to preserve the universality of this method. More specifically, used techniques can be listed as removing or filling usernames and URLs, and converting emojis to text. Further, for uncased pretrained models (e.g. \textit{albert-xxlarge-v1}), all tokens were converted to lower case. In WNUT-2020 Task 2 data set, mention of a user is represented by \textit{@USER} and a URL is represented by \textit{HTTPURL}. For all the models except CT-BERT and BERTweet, we removed those mentions. The main reason behind this step is to remove noisy text from data. CT-BERT and BERTweet models are trained on tweet corpora and usernames and URLs are introduced to the models using special fillers. CT-BERT model knows a username as \textit{twitteruser} and URL as \textit{twitterurl}. Likewise, BERTweet model used the filler \textit{@USER} for usernames and \textit{HTTPURL} for URLs. Therefore, for these two models we used the corresponding fillers to replace usernames and URLs in the data set. Emojis are found to play a key role in expressing emotions in the context of social media \cite{hettiarachchi2019emoji}. But, we cannot assure the existence of embeddings for emojis in pretrained models. Therefore as another essential preprocessing step, we converted emojis to text. For this conversion we used the Python libraries \textit{demoji}\footnote{demoji repository - \url{https://github.com/bsolomon1124/demojis}} and \textit{emoji}\footnote{emoji repository - \url{https://github.com/carpedm20/emoji}}. \textit{demoji} returns a normal descriptive text and \textit{emoji} returns a specifically formatted text. For an example, the conversion of \smiley \space is `slightly smiling face' using \textit{demoji} and `:slightly\textunderscore smiling\textunderscore face:' using \textit{emoji}. For all the models except CT-BERT and BERTweet, we used \textit{demoji} supported conversion. For CT-BERT and BERTweet \textit{emoji} supported conversion is used, because these models are trained on correspondingly converted Tweets. \begin{table*}[!htbp] \centering \begin{tabular}{l|l|ccc|ccc|ccc} \hline \multicolumn{2}{l|}{\textbf{Learning R.}} & \multicolumn{3}{c|}{$1e^{-5}$} & \multicolumn{3}{c|}{$1e^{-6}$} & \multicolumn{3}{c}{$2e^{-5}$} \\ \hline \textbf{S. 1} & \textbf{S. 2} & \textbf{P} & \textbf{R} & \textbf{F1} & \textbf{P} & \textbf{R} & \textbf{F1} & \textbf{P} & \textbf{R} & \textbf{F1} \\ \hline \multirow{3}{*}{\makecell[l]{MSE\\ (N=3)}} & - & 0.9072 & 0.9322 & 0.9195 & 0.9317 & 0.8962 & 0.9136 & 0.9125 & 0.9280 & 0.9202 \\ & EI & 0.8864 & 0.9258 & 0.9057 & 0.9181 & 0.9025 & 0.9103 & 0.8975 & 0.9089 & 0.9032 \\ & LM & 0.8912 & 0.9195 & 0.9051 & 0.8987 & 0.9025 & 0.9006 & 0.9070 & 0.9301 & 0.9184 \\ \hline \multirow{3}{*}{\makecell[l]{ASE\\ (N=3)}} & - & 0.9091 & 0.9322 & 0.9205 & 0.9295 & 0.8941 & 0.9114 & 0.9146 & 0.9301 & \textbf{0.9223} \\ & EI & 0.8960 & 0.9131 & 0.9045 & 0.9124 & 0.9047 & 0.9085 & 0.9025 & 0.9025 & 0.9025 \\ & LM & 0.9021 & 0.9174 & 0.9097 & 0.8971 & 0.9047 & 0.9008 & 0.9160 & 0.9237 & 0.9198 \\ \hline \end{tabular} \caption{\label{table:ct-bert-results} Result obtained for CT-BERT model with different fine-tuning strategies (All these experiments are executed for 5 learning epochs and S. abbreviates the Strategy) } \end{table*} \subsection{Fine-tuning} \label{subsec:fine_tuning} To improve the models, we experimented different fine-tuning strategies: majority class self-ensemble, average self-ensemble, entity integration and language modelling, which are described below. \begin{enumerate} \item{\textbf{Self-Ensemble (SE)}} - Self-ensemble is found as a technique which result better performance than the performance of a single model \cite{xu2020improving}. In this approach, same model architecture is trained or fine-tuned with different random seeds or train-validation splits. Then the output of each model is aggregated to generate the final results. As the aggregation methods, we analysed majority-class and average in this research. The number of models used with self-ensemble will be denoted by $N$. \begin{itemize} \item \textit{Majority-class SE (MSE)} - As the majority class, we computed the mode of the classes predicted by each model. Given a data instance, following the softmax layer, a model predicts probabilities for each class and the class with highest probability is taken as the model predicted class. \item \textit{Average SE (ASE)} - In average SE, final probability of class $c$ is calculated as the average of probabilities predicted by each model as in Equation \ref{equ:ase} where \textit{h} is the final hidden state of the [CLS] token. Then the class with highest probability is selected as the final class. \begin{equation} \label{equ:ase} p_{ASE}(c|h) = \frac{\sum_{k=1}^{N} p_{k}(c|h) }{N} \end{equation} \end{itemize} \item{\textbf{Entity Integration (EI)}} - Since we are using pretrained models, there can be model unknown data in the task data set such as person names, locations and organisations. As entity integration, we replaced the unknown tokens with their named entities which are known to the model, so that the familiarity of data to model can be increased. To identify the named entities, we used the pretrained models available with spaCy \footnote{More details about spaCy are available on \url{https://spacy.io/}}. \item{\textbf{Language Modelling (LM)}} - As language modelling, we retrained the transformer model on task data set before fine-tuning it for the downstream task; text classification. This training is took place according with the model's initial trained objective. Following this technique model understanding on the task data can be improved. \end{enumerate} \section{Experiments and Results} In this section, we report the experiments we conducted and their results. As informed by task organisers, we used precision, recall and F1 score calculated for \textit{Informative} class to measure the model performance. Results in sections \ref{res:tranformers} - \ref{res:fine-tuning} are computed on validation data set and results in section \ref{res:test-eval} are computed on test data set. \subsection{Impact by Transformer Model} \label{res:tranformers} Initially we focused on the impact by different transformer models. Selected transformer models were fine-tuned for this task using single-model (no ensemble) and MSE with 3 models, and the obtained results are summarised in Table \ref{table:transformer-models}. According to the results, CT-BERT model outperformed the other models. Also, all the models except XLNet showed improved results with self-ensemble approach than single-model approach. Following these results and considering time and resource constraints, we limited the further experiments only to CT-BERT model. \subsection{Impact by Epoch Count} \label{res:epoch} We experimented that increasing the epoch count from 3 to 5 increases the results. However, increasing it more than 5 did not further improved the results. Therefore, we used an epoch count of 5 in our experiments. To monitor the evaluation scores against the epoch count we used Wandb app \footnote{Wandb app is available on \url{https://app.wandb.ai/}}. As shown in the Figure \ref{fig:epoh_count} evaluation f1 score does not likely to change when trained with more than five epochs. \begin{figure}[ht] \centering \includegraphics[scale=0.496]{figures/f1.jpg} \caption{Evaluation F1 score against the epoch count} \label{fig:epoh_count} \end{figure} \subsection{Impact by Fine-tuning} \label{res:fine-tuning} The fine-tuning strategies mentioned in Section \ref{subsec:fine_tuning} were experimented using CT-BERT model and obtained results are summarised in Table \ref{table:ct-bert-results}. According to the results, in majority of experiments, ASE is given a higher F1 than MSE. The other fine- strategies: EI and LM did not improve the results for this data set. As possible reasons for this reduction, having a good knowledge about COVID tweets by the model itself and insufficiency of data for language modelling can be mentioned. Additionally, we analysed the impact by different learning rates. For initial experiments a random learning rate of $1e^{-5}$ was picked and for further analysis a less value ($1e^{-6}$) and a high value ($2e^{-5}$) were picked. The value $2e^{-5}$ was used for pretraining and experiments of CT-BERT model \cite{muller2020covid}. According to this analysis there is a tendency to have higher F1 with higher learning rates. \subsection{Test Set Evaluation}\label{res:test-eval} The test data results of our submissions, task baseline and top-ranked system are summarised in Table \ref{table:final-results}. Considering the evaluation results on validation data set, as InfoMiner 1 we selected the fine-tuned CT-BERT model with ASE and $2e^{-5}$ learning rate. As InfoMiner 2 same model and parameters with MSE was picked. Among them, the highest F1 we received is for MSE strategy. \begin{table}[!htbp] \centering \begin{tabular}{l|l|l|l} \hline \textbf{Model} & \textbf{P} & \textbf{R} & \textbf{F1} \\ \hline Top-ranked & 0.9135 & 0.9057 & 0.9096 \\ InfoMiner 1 & 0.9107 & 0.8856 & 0.8980 \\ InfoMiner 2 & 0.9102 & 0.8909 & 0.9004 \\ Task baseline & 0.7730 & 0.7288 & 0.7503 \\ \hline \end{tabular} \caption{\label{table:final-results} Results of test data predictions } \end{table} \section{Conclusion} We have presented the system by InfoMiner team for WNUT-2020 Task 2. For this task, we have shown that the CT-BERT is the most successful transformer model from several transformer models we experimented. Furthermore, we presented several fine tuning strategies: self-ensemble, entity integration and language modelling that can improve the results. Overall, our approach is simple but can be considered as effective since it achieved 10$^{th}$ place in the leader-board. As a future direction of this research, we hope to analyse the impact by different classification heads such as LSTM and Convolution Neural Network (CNN) in addition to softmax classifier on performance. Also, we hope to incorporate meta information-based features like number of retweets and likes with currently used textual features to involve social aspect for informative tweet identification. \newpage \bibliographystyle{acl_natbib}
{'timestamp': '2020-10-13T02:25:03', 'yymm': '2010', 'arxiv_id': '2010.05327', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05327'}
arxiv
\section*{Appendix: Glance and Focus: a Dynamic Approach to Reducing Spatial Redundancy in Image Classification} \section{Implementation Details} \subsection{Recurrent Networks} For RegNets \cite{radosavovic2020designing}, MobileNets-V3 \cite{howard2019searching} and EfficientNets \cite{DBLP:conf/icml/TanL19}, we use a gated recurrent unit (GRU) with 256 hidden units \cite{cho2014learning} in the patch proposal network $\pi$. For ResNets \cite{He_2016_CVPR} and DenseNets \cite{2019arXiv160806993H}, we adopt 1024 hidden units and remove the convolutional layer in $\pi$. This does not hurt the efficiency since here the computational cost of $\pi$ is negligible compared with the two encoders. With regards to the recurrent classifier $f_{\textsc{c}}$, for ResNets \cite{He_2016_CVPR}, DenseNets \cite{2019arXiv160806993H} and RegNets \cite{radosavovic2020designing}, we use a GRU with 1024 hidden units. For MobileNets-V3 \cite{howard2019searching} and EfficientNets \cite{DBLP:conf/icml/TanL19}, we find that although a GRU classifier with a large number of hidden units achieves excellent classification accuracy, it is excessively computationally expensive in terms of efficiency. Therefore, we replace the GRU with a cascade of fully connected classification layers. In specific, at $t^{\textnormal{th}}$ step, we concatenate the feature vectors of all previous inputs $\{\bm{\bar{e}}_1, \dots, \bm{\bar{e}}_{t}\}$, and use a linear classifier with the size $tF\!\times\!C$ for classification, where $F$ is the number of feature dimensions and $C$ is the number of classes. Similarly, we use another $(t\!+\!1)F\!\times\!C$ linear classifier at $(t\!+\!1)^{\textnormal{th}}$ step. Totally, we have $T$ linear classifiers with the size $F\!\times\!C, 2F\!\times\!C, \dots, TF\!\times\!C$. \subsection{Policy Gradient Algorithm} \label{app:PPO} During training, the objective of the patch proposal network $\pi$ is to maximize the sum of the discounted rewards: \begin{equation} \label{eq:app_reward} \max_{\pi} \mathbb{E}\left[\sum\nolimits_{t=2}^{T} \gamma^{t-2} r_t \right], \end{equation} where, $\gamma \in (0,1)$ is a pre-defined discount factor, $r_{t}$ is the reward for the localization action $\bm{l}_{t}$, and $T$ is the maximum length of the input sequence. The action $\bm{l}_{t}$ is stochastically chosen from a distribution parameterized by $\pi$: $\bm{l}_{t} \sim \pi(\bm{l}_{t}|\bm{e}_{t-1}, \bm{h}^{\pi}_{t-2})$, where we denote the hidden state maintained within $\pi$ by $\bm{h}^{\pi}_{t-2}$. Here we use a Gaussian distribution during training, whose mean is outputted by $\pi$ and standard deviation is pre-defined as a hyper-parameter. At test time, we simply adopt the mean value as $\bm{l}_{t}$ for a deterministic inference process. Note that, we always resize the original image $\bm{x}$ to $H'\!\times\!W'$ as $\tilde{\bm{x}}_1$ (\textit{Glance Step}), and thus we do not have $\bm{l}_{1}$ or $r_1$. In this work, we implement the proximal policy optimization (PPO) algorithm proposed by \cite{schulman2017proximal} to train the patch proposal network $\pi$. In the following, we briefly introduce its procedure. For simplicity, we denote $\pi(\bm{l}_{t}|\bm{e}_{t-1}, \bm{h}^{\pi}_{t-2})$ by $\pi(\bm{l}_{t}|\bm{s}_t)$, where $\bm{s}_t$ is the current state containing $\bm{e}_{t-1}$ and $\bm{h}^{\pi}_{t-2}$. First, we consider a surrogate objective: \begin{equation} {L}^{\textnormal{CPI}}_t = \frac{\pi(\bm{l}_{t}|\bm{s}_t)}{\pi_{\textnormal{old}}(\bm{l}_{t}|\bm{s}_t)} \hat{A}_t, \end{equation} where $\pi_{\textnormal{old}}$ and $\pi$ are the patch proposal network before and after the update, respectively. The advantage estimator $\hat{A}_t$ is computed by: \begin{equation} \hat{A}_t = -V(\bm{s}_t) + r_t + \gamma r_{t+1} + \dots + \gamma^{T-t} r_T, \end{equation} where $V(\bm{s}_t)$ is a learned state-value function that shares parameters with the policy function (they merely differ in the final fully connected layer). Since directly maximizing ${L}^{\textnormal{CPI}}$ usually leads to an excessively large policy update, a clipped surrogate objective is adopted \cite{schulman2017proximal}: \begin{equation} {L}^{\textnormal{CLIP}}_t = \textnormal{min} \left\{ \frac{\pi(\bm{l}_{t}|\bm{s}_t)}{\pi_{\textnormal{old}}(\bm{l}_{t}|\bm{s}_t)} \hat{A}_t, \textnormal{clip}( \frac{\pi(\bm{l}_{t}|\bm{s}_t)}{\pi_{\textnormal{old}}(\bm{l}_{t}|\bm{s}_t)}, 1-\epsilon, 1+ \epsilon )\hat{A}_t \right\}, \end{equation} where $0 < \epsilon < 1$ is a hyper-parameter. Then we are ready to give the final maximization objective: \begin{equation} \label{eq:objective} \mathop{\textnormal{maximize}}\limits_{\pi}\ \ \mathbb{E}_{\bm{x}, t} \left[ {L}^{\textnormal{CLIP}}_t - c_1 L^{\textnormal{VF}}_t + c_2 S_{\pi}(\bm{s}_t) \right]. \end{equation} Herein, $S_{\pi}(\bm{s}_t)$ denotes the entropy bonus to ensure sufficient exploration \cite{williams1992simple, mnih2016asynchronous, schulman2017proximal}, and $L^{\textnormal{VF}}_t$ is a squared-error loss on the estimated state value: $(V(\bm{s}_t) - V^{\textnormal{target}}(\bm{s}_t))^2$. We straightforwardly let $V^{\textnormal{target}}(\bm{s}_t) = r_t + \gamma r_{t+1} + \dots + \gamma^{T-t} r_T$. The coefficients $c_1$ and $c_2$ are pre-defined hyper-parameters. In our implementation, we execute the aforementioned training process in Stage \uppercase\expandafter{\romannumeral2} of the 3-stage training scheme. To be specific, we optimize Eq. (\ref{eq:objective}) using an Adam optimizer \cite{kingma2014adam} with $\beta_1 = 0.9$, $\beta_2 = 0.999$ and a learning rate of $0.0003$. We set $\gamma = 0.7$, $\epsilon = 0.2$, $c_1 = 0.5$ and $c_2 = 0.01$. The size of the mini-batch is set to 256. We train the patch proposal network $\pi$ for 15 epochs and select the model with the highest final validation accuracy, i.e., the accuracy when $t=T$. These hyper-parameters are selected on the validation set of ImageNet and used in all our experiments. \subsection{Training Details} \textbf{Initialization.} As introduced in the paper, we initialize the local encoder $f_{\textsc{l}}$ using the ImageNet pre-trained models, while initialize the global encoder $f_{\textsc{g}}$ by first fine-tuning the pre-trained models with all training samples resized to $H'\!\times\! W'$. To be specific, for ResNets and DenseNets, we use the pre-trained models provided by pytorch \cite{paszke2019pytorch}, for RegNets, we use the pre-trained models provided by their paper \cite{radosavovic2020designing}, and for MobileNets-V3 and EfficientNets, we first train the networks from scratch following all the details mentioned in their papers \cite{DBLP:conf/icml/TanL19, howard2019searching} to match the reported performance, and use the obtained networks as the pre-trained models. For $H'\!\times\! W'$ fine-tuning, we use the same training hyper-parameters as the training process \cite{He_2016_CVPR, 2019arXiv160806993H, radosavovic2020designing, DBLP:conf/icml/TanL19, howard2019searching}. Notably, when MobileNets-V3 and EfficientNets are used as the backbone, we fix the parameters of the global encoder $f_{\textsc{g}}$ after initialization and do not train it any more, which we find is beneficial for the final performance of the \textit{Glance Step}. \textbf{Stage \uppercase\expandafter{\romannumeral1}.} We train all networks using a SGD optimizer \cite{He_2016_CVPR, 2019arXiv160806993H, wang2020meta} with a cosine learning rate annealing technique and a Nesterov momentum of 0.9. The size of the mini-batch is set to 256, while the L2 regularization coefficient is set to 5e-5 for RegNets and 1e-4 for other networks. The initial learning rate is set to 0.1 for the classifier $f_{\textsc{c}}$. For the two encoders, the initial learning rates are set to 0.01, 0.01, 0.02, 0.005 and 0.005 for ResNets, DenseNets, RegNets, MobileNets-V3 and EfficientNets, respectively. The regularization coefficient $\lambda$ (see: Eq. (3) in the paper) is set to 1 for ResNets, DenseNets and RegNets, and 5 for MobileNets-V3 and EfficientNets. We train ResNets, DenseNets and RegNets for 60 epochs, MobileNets-V3 for 90 epochs and EfficientNets for 30 epochs. \textbf{Stage \uppercase\expandafter{\romannumeral2}.} We train the patch proposal network $\pi$ using an Adam optimizer \cite{kingma2014adam} with the hyper-parameters provided in Appendix \ref{app:PPO}. The standard deviation of the Gaussian distribution from which we sample the localization action $\bm{l}_{t}$ is set to 0.1 in all the experiments. \textbf{Stage \uppercase\expandafter{\romannumeral3}.} We use the same hyper-parameters as {Stage \uppercase\expandafter{\romannumeral1}}, except for using an initial learning rate of 0.01 for the classifier $f_{\textsc{c}}$. Moreover, we do not execute this stage for EfficientNets, since we do not witness an improvement of performance. \begin{table*}[!h] \footnotesize \centering \vskip -0.2in \caption{Details of the GFNets in Figure 4 of the paper} \label{tab:gfnets} \setlength{\tabcolsep}{4mm}{ \vspace{5pt} \renewcommand\arraystretch{1.15} \begin{tabular}{l|l} \hline Backbone CNNs & GFNets \\ \hline \multirow{2}{*}{ResNets} & (1) ResNet-50, $H'=W'=96$, $T=5$ \\ &(2) ResNet-50, $H'=W'=128$, $T=5$ \\ \hline \multirow{3}{*}{DenseNets} & (1) DenseNet-121, $H'=W'=96$, $T=5$ \\ &(2) DenseNet-169, $H'=W'=96$, $T=5$ \\ &(3) DenseNet-201, $H'=W'=96$, $T=5$ \\ \hline \multirow{3}{*}{RegNets} & (1) RegNet-Y-600MF, $H'=W'=96$, $T=5$ \\ &(2) RegNet-Y-800MF, $H'=W'=96$, $T=5$ \\ &(3) RegNet-Y-1.6GF, $H'=W'=96$, $T=5$ \\ \hline \multirow{3}{*}{MobileNets-V3} & (1) MobileNet-V3-Large (1.00), $H'=W'=96$, $T=3$ \\ &(2) MobileNet-V3-Large (1.00), $H'=W'=128$, $T=3$ \\ &(3) MobileNet-V3-Large (1.25), $H'=W'=128$, $T=3$ \\ \hline \multirow{3}{*}{EfficientNets} & (1) EfficientNet-B2, $H'=W'=128$, $T=4$ \\ &(2) EfficientNet-B3, $H'=W'=128$, $T=4$ \\ &(3) EfficientNet-B3, $H'=W'=144$, $T=4$ \\ \hline \end{tabular}} \vskip -0.1in \end{table*} The input size ($H'$, $W'$), the maximum input sequence length $T$ and the corresponding encoders used by the GFNets in Figure 4 of the paper are summarized in Table \ref{tab:gfnets}. Note that we always let $H'\!=\!W'$. \section{Additional Results} \subsection{Effects of Low-resolution Fine-tuning} \label{app:Low-resolution Finetuning} \begin{figure*}[tbp] \centering \subfigure[MobileNet-V3]{\hspace{-0.1in} \begin{minipage}[t]{0.35\linewidth} \centering \includegraphics[width=\linewidth]{results_app/budget-batch-mv3.pdf} \end{minipage}% }\hspace{-0.1in} \subfigure[RegNet-Y]{ \begin{minipage}[t]{0.33\linewidth} \centering \includegraphics[width=\linewidth]{results_app/budget-batch-regnet.pdf} \end{minipage}% }\hspace{-0.1in} \subfigure[EfficientNet]{ \begin{minipage}[t]{0.33\linewidth} \centering \includegraphics[width=\linewidth]{results_app/budget-batch-eff-net.pdf} \end{minipage}% }% \vspace{-1ex} \subfigure[ResNet]{\hspace{-0.065in} \begin{minipage}[t]{0.353\linewidth} \centering \includegraphics[width=\linewidth]{results_app/budget-batch-resnets.pdf} \end{minipage} }\hspace{-0.14in} \subfigure[DenseNet]{ \begin{minipage}[t]{0.33\linewidth} \centering \includegraphics[width=\linewidth]{results_app/budget-batch-densenets.pdf} \end{minipage} }\hspace{-0.14in} \centering \vspace{-1ex} \caption{The performance of $H'\!\times\!W'$ fine-tuned models. The results of \textit{Budgeted batch classification} are presented. Note that, the performance of the \textit{Glance Step} is mainly determined by the low-resolution fine-tuning, and thus this fine-tuning is an important component of the proposed GFNet framework.} \label{fig:app_main_results} \vspace{-2ex} \end{figure*} As mentioned in the paper, our method initializes the global encoder $f_{\textsc{g}}$ by first fine-tuning the pre-trained models with all training samples resized to $H'\!\times\! W'$. An interesting observation is that the low-resolution fine-tuning improves the computational efficiency by itself. The performance of the fine-tuned models compared with baselines and GFNets is reported in Figure \ref{fig:app_main_results}. It is important that the improvements achieved by these fine-tuned models are actually included in our GFNets, since the performance of the \textit{Glance Step} is mainly determined by the low-resolution fine-tuning. On the other hand, our method is able to further improve the test accuracy with the \textit{Focus Stage}, and adjust the average computational cost online. \subsection{Comparisons with MSDNet in \textit{Budgeted Batch Classification}} \begin{wrapfigure}{l}{0.4\linewidth} \begin{minipage}[t]{\linewidth} \centering \vskip -0.3in \includegraphics[width=\textwidth]{results_app/app-budget-batch-densenets.pdf} \vskip -0.15in \caption{Performance of GFNet (based on DenseNets) versus MSDNet \cite{huang2017multi} under the \textit{Budgeted Batch Classification} setting. \label{fig:comp_dense}} \end{minipage} \vskip -0.2in \end{wrapfigure} The comparisons of DenseNet-based GFNets and MSDNets \cite{huang2017multi} under the \textit{Budgeted Batch Classification} setting are shown in Figure \ref{fig:comp_dense}. Following \cite{huang2017multi}, here we hold out 50,000 images from the training set as an additional validation set to estimate the confidence thresholds, and use the remaining samples to train the network (note that we use the entire training set in Figure 4 (e) of the paper). One can observe from the results that GFNet consistently outperforms MSDNet within a wide range of computational budgets. For example, when the budgets are around $1 \times 10^9$ Multiply-Adds, the test accuracy of our method is higher than MSDNet by approximately $2\%$. GFNet is shown to be a more effective adaptive inference framework than MSDNet. In addition, in terms of the flexibility of GFNet, its computational efficiency can be further improved by applying state-of-the-art CNNs as the two encoders. \section{Conclusion} \vspace{-1.5ex} In this paper, we introduced a \emph{Glance and Focus Network} (GFNet) to reduce the spatial redundancy in image classification tasks. GFNet processes a given high-resolution image in a sequential manner. At each step, GFNet processes a smaller input, which is either a down-sampled version of the original image or a cropped patch. GFNet progressively performs classification as well as localizes discriminative regions for the next step. This procedure is terminated once sufficient classification confidence is obtained, leading to an adaptive manner. Our method is compatible with a wide variety of modern CNNs and is easy to implement on mobile devices. Extensive experiments on ImageNet show that GFNet significantly improves the computational efficiency even on top of the most SOTA light-weighted CNNs, both theoretically and empirically. \section{Experiments} \vspace{-1.5ex} In this section, we empirically evaluate the effectiveness of the proposed GFNet and give ablation studies. Code and pre-trained models are available at \url{https://github.com/blackfeather-wang/GFNet-Pytorch}. \textbf{Dataset.} ImageNet is a 1,000-class dataset from ILSVRC2012 \cite{5206848}, with 1.2 million images for training and 50,000 images for validation. We adopt the same data augmentation and pre-processing configurations as \cite{2019arXiv160806993H, He_2016_CVPR, wang2019implicit}. In our implementation, we estimate the confidence thresholds of GFNet on the training set, since we find that it achieves nearly the same performance as estimating the thresholds on an additional validation set split from the training images. \textbf{Setup.} We consider two settings to evaluate our method: (1) \textit{budgeted batch classification} \cite{huang2017multi}, where the network needs to classify a set of test samples within a given computational budget; (2) \textit{anytime prediction} \cite{grubb2012speedboost, huang2017multi}, where the network can be forced to output a prediction at any given point in time. As discussed in \cite{huang2017multi}, these two settings are ubiquitous in many real-world applications. For (1), we estimate the confidence thresholds to perform the adaptive inference as introduced in Section \ref{sec:details}, while for (2), we assume the length of the input sequence is the same for all test samples. \begin{figure*}[tbp] \label{fig:main_results} \centering \subfigure[MobileNet-V3]{\hspace{-0.1in} \begin{minipage}[t]{0.35\linewidth} \centering \includegraphics[width=\linewidth]{results/budget-batch-mv3.pdf} \end{minipage}% }\hspace{-0.1in} \subfigure[RegNet-Y]{ \begin{minipage}[t]{0.33\linewidth} \centering \includegraphics[width=\linewidth]{results/budget-batch-regnet.pdf} \end{minipage}% }\hspace{-0.1in} \subfigure[EfficientNet]{ \begin{minipage}[t]{0.33\linewidth} \centering \includegraphics[width=\linewidth]{results/budget-batch-eff-net.pdf} \end{minipage}% }% \vspace{-1ex} \subfigure[ResNet]{\hspace{-0.065in} \begin{minipage}[t]{0.353\linewidth} \centering \includegraphics[width=\linewidth]{results/budget-batch-resnets.pdf} \end{minipage} }\hspace{-0.14in} \subfigure[DenseNet]{ \begin{minipage}[t]{0.33\linewidth} \centering \includegraphics[width=\linewidth]{results/budget-batch-densenets.pdf} \end{minipage} }\hspace{-0.14in} \subfigure[DenseNet (anytime prediction)]{ \begin{minipage}[t]{0.328\linewidth} \centering \includegraphics[width=\linewidth]{results/anytime-imagenet.pdf} \end{minipage}% } \centering \vspace{-1ex} \caption{Top-1 accuracy v.s. Multiply-Adds on ImageNet. The proposed GFNet framework is implemented on top of state-of-the-art efficient networks. Figures (a-e) present the results of \textit{Budgeted batch classification}, while Figures (f) shows the \textit{Anytime prediction} results.} \vspace{-2.5ex} \end{figure*} \textbf{Networks.} The GFNet is implemented on the basis of several state-of-the-art CNNs, including MobileNet-V3 \cite{howard2019searching}, RegNet-Y \cite{radosavovic2020designing}, EfficientNet \cite{DBLP:conf/icml/TanL19}, ResNet \cite{He_2016_CVPR} and DenseNet \cite{2019arXiv160806993H}. These networks serve as the two deep encoders in our methods. In \textit{Budgeted batch classification}, for each sort of CNNs, we fix the maximum length of the input sequence $T$, and change the model size (width, depth or both) or the patch size ($H'$, $W'$) to obtain networks that cover different ranges of computational budgets. Note that we always let $H'\!=\!W'$. Details on both the network configurations and the training hyper-parameters are presented in Appendix A.3. We also compare GFNet with a number of highly competitive baselines, i.e., MnasNets \cite{tan2019mnasnet}, ShuffleNets-V2 \cite{ma2018shufflenet}, MobileNets-V2 \cite{sandler2018mobilenetv2}, CondenseNets \cite{huang2018condensenet}, FBNets \cite{wu2019fbnet}, ProxylessNAS \cite{cai2018proxylessnas}, SkipNet \cite{wang2018skipnet}, SACT \cite{figurnov2017spatially}, GoogLeNet \cite{szegedy2015going} and MSDNet \cite{huang2017multi}. \vspace{-1.5ex} \subsection{Main Results} \vspace{-1.5ex} \textbf{Budgeted batch classification} results are shown in Figure \ref{fig:main_results} (a-e). We first plot the performance of each GFNet in a gray curve, and then plot the best validation accuracy with each budget as a black curve. It can be observed that GFNet significantly improves the performance of even the state-of-the-art efficient models with the same amount of computation. For example, with an average budget of $7\times10^7$ Multiply-Adds, the GFNet based on MobileNet-V3 achieves a Top-1 validation accuracy of $\sim71\%$, which outperforms the vanilla MobileNet-V3 by $\sim2\%$. With EfficientNets, GFNet generally has $\sim1.4\times$ less computation compared with baselines when achieving the same performance. With ResNets and DenseNets, GFNet reduces the number of required Multiply-Adds for the given test accuracy by approximately $2-3\times$ times. Moreover, the computational cost of our method can be tuned precisely to achieve the best possible performance with a given budget. \textbf{Anytime prediction.} We compare our method with another adaptive inference architecture, MSDNet \cite{huang2017multi}, under the \textit{Anytime prediction} setting in Figure \ref{fig:main_results} (f), where the GFNet is based on a DenseNet-121. For fair comparison, here we hold out 50,000 training images, following \cite{huang2017multi} (we do not do so in Figure \ref{fig:main_results} (e), and hence the \textit{Budgeted batch classification} comparisons between GFNet and MSDNet are deferred to Appendix B.2). We also include the results of an ensemble of DenseNets with varying depth \cite{huang2017multi}. The plot shows that GFNet achieves $\sim4-10\%$ higher accuracy than MSDNet when the budget ranges from $5\times10^8$ to $2.2\times10^9$ Multiply-Adds. \textbf{Experiments on an iPhone.} A suitable platform for the implementation of GFNet may be mobile applications, where the average inference latency and power consumption of each image are approximately linear in the amount of computation (Multiply-Adds) \cite{howard2019searching}, such that reducing computational costs helps for both improving user experience and preserving battery life. To this end, we investigate the practical inference speed of our method on an iPhone XS Max (with Apple A12 Bionic) using TFLite \cite{abadi2016tensorflow}. The single-thread mode with batch size 1 is used following \cite{howard2017mobilenets, sandler2018mobilenetv2, howard2019searching}. We first measure the time consumption of obtaining the prediction with each possible length of the input sequence, and then take the weighted average according to the number of validation samples using each length. The results are shown in Figure \ref{fig:speed}. One can observe that GFNet effectively accelerates the inference of both MobileNets-V3 and ResNets. For instance, our method reduces the required latency to achieve $75.4\%$ test accuracy (MobileNets-V3-Large) by $22\%$ (12.7ms v.s. 16.3ms). For ResNets, GFNet generally requires $2\!-\!3\times$ times lower latency to achieve the same performance as baselines. \textbf{Maximum input sequence length $T$ and patch size.} We show the performance of GFNet with varying $T$ and different patch sizes under the \textit{Anytime prediction} setting in Figure \ref{fig:T_WH}. The figure suggests that changing $T$ does not significantly affect the performance with the same amount of computation, while using larger patches leads to better performance with large computational budgets but lower test accuracy compared with smaller patches when the computational budget is insufficient. \begin{figure} \vspace{-0.025in} \begin{minipage}[t]{0.64\linewidth}   \centering \hspace{-0.2in} \subfigure[MobileNet-V3]{\hspace{-0.1in}   \begin{minipage}[t]{0.5\linewidth} \centering \includegraphics[width=\linewidth]{results/mv3_latency.pdf} \end{minipage}} \subfigure[ResNet]{\hspace{-0.1in} \begin{minipage}[t]{0.4815\linewidth} \centering \includegraphics[width=\linewidth]{results/resnets-latency.pdf} \end{minipage}} \vskip -0.15in   \caption{\label{fig:speed} Top-1 accuracy v.s. inference latency (ms) on ImageNet. The inference speed is measured on an iPhone XS Max. We implement GFNet based on MobileNet-V3 and ResNet.} \end{minipage} \hspace{0.05in} \begin{minipage}[t]{0.342\linewidth} \centering \includegraphics[width=\textwidth]{results/anytime-sense.pdf} \vskip -0.025in \caption{\label{fig:T_WH}Performance of GFNet with varying $T$ and different patch sizes. Here we use ResNet-50 as the two backbones. \end{minipage} \end{figure} \begin{figure*}[t] \vskip -0.1in \begin{center} \centerline{\includegraphics[width=\columnwidth]{results/visualization.pdf}} \vspace{-1.5ex} \caption{Visualization results of the GFNet (ResNet-50, $T\!\!=\!\!5$, $H'\!\!=\!\!W'\!\!=\!96$). The boxes indicate the patch locations, and the color denotes whether the prediction is correct at current step (green: correct; red: wrong). Note that $\tilde{\bm{x}}_1$ is the resized input image. The indices of the steps and the current confidence on the ground truth labels (shown at the top of images) are presented in the upper left corners of boxes. } \label{fig:visualization} \end{center} \vspace{-5.5ex} \end{figure*} \vspace{-1.5ex} \subsection{Visualization} \vspace{-1.5ex} \begin{wrapfigure}{r}{0.375\linewidth} \vskip -0.375in \begin{minipage}[t]{\linewidth} \centering \includegraphics[width=\textwidth]{results/acc_t.pdf} \vskip -0.2in \caption{\label{fig:e_t}Top-1 accuracy v.s. the expected length of input sequence \textbf{\textnormal{E}}($t$) during inference in \textit{Budgeted batch classification}. The results are obtained based on the GFNet (DenseNet-201, $T\!\!=\!\!5$, $H'\!\!=\!\!W'\!\!=\!96$).} \end{minipage} \vskip -0.2in \end{wrapfigure} We show the image patches found by a ResNet-50 based GFNet on some of test samples in Figure \ref{fig:visualization}. Samples are divided into different columns according to the number of inputs they require to obtain correct classification results. One can observe that GFNet classifies ``easy'' images containing large objects with prototypical features correctly at the \textit{Glance Step} with high confidence, while for relatively ``hard'' images which tend to be complex or non-typical, our network is capable of focusing on some class-discriminative regions to progressively improve the confidence. To give a deeper understanding of our method, we visualize the expected length of the input sequence \textbf{\textnormal{E}}($t$) during inference under the \textit{Budgeted batch classification} setting and the corresponding Top-1 accuracy on ImageNet, as shown in Figure \ref{fig:e_t}. We also present the plots of numbers of images v.s. $t$ at several points. It can be observed that the performance of GFNet is significantly improved by letting images exit later in the \textit{Focus Stage}, which is achieved by adjusting the confidence thresholds online without additional training. \begin{table*}[t] \footnotesize \centering \caption{Ablation study results. For clear comparisons, we report the Top-1 accuracy of different variants with fixed length of the input sequence (denoted by $t$). The best results are \textbf{bold-faced}.} \label{tab:abl} \setlength{\tabcolsep}{1.75mm}{ \vspace{5pt} \renewcommand\arraystretch{1.25} \begin{tabular}{|l|c|c|c|c|c|} \hline Ablation & $t=1$ & $t=2$ & $t=3$ & $t=4$ & $t=5$ \\ \hline Random Policy &54.53\%&64.42\%&68.09\%&69.85\%&70.70\% \\ Random Policy + \textit{Glance Step}&69.47\%&72.32\%&73.47\%&74.04\%&74.46\% \\ Centre-corner Policy &59.51\%&66.75\%&69.53\%&72.83\%&74.10\% \\ Centre-corner Policy + \textit{Glance Step} &69.06\%&72.94\%&73.88\%&74.47\%&75.12\% \\ \hline w/o Global Encoder $f_{\textsc{g}}$ (single encoder) &65.92\%&70.59\%&72.59\%&73.72\%&74.26\% \\ w/o Regularizing CNNs (using $\mathcal{L}_{\textnormal{cls}}$ instead of $\mathcal{L}_{\textnormal{cls}}'$) &68.55\%&71.87\%&73.19\%&73.52\%&73.94\% \\ Initializing $f_{\textsc{g}}$ w/o $H'\!\times\!W'$ Fine-tuning &67.81\%&72.50\%&74.12\%&75.21\%&75.56\% \\ w/o the \textit{Glance Step} (using a centre crop as $\tilde{\bm{x}}_1$) &59.14\%&66.70\%&70.91\%&73.71\%& 74.70\%\\ w/o Training Stage \uppercase\expandafter{\romannumeral3} (2-stage training) &\textbf{69.62\%}&73.39\%&74.32\%&74.97\%&75.36\% \\ \hline GFNet (ResNet-50, $T=5$, $H'\!=\!W'\!=\!96$) &68.85\%&\textbf{73.71\%}&\textbf{74.65\%}&\textbf{75.34\%}&\textbf{75.93\%} \\ \hline \end{tabular}} \vskip -0.2in \end{table*} \vspace{-1.5ex} \subsection{Ablation Study} \label{subsec:ablation} \vspace{-1.5ex} The ablation study results are summarized in Table \ref{tab:abl}. We first consider two alternatives of the learned patch selection policy, namely the random policy where all patches are uniformly sampled from the image, and the centre-corner policy where the network sequentially processes the whole image by first cropping the patch from the centre of the image, and then traversing the corners. The learned policy is shown to consistently outperform them. We also remove or alter the components of the GFNet architecture and the training process. One can observe that resizing the original image as $\tilde{\bm{x}}_1$ (\textit{Glance Step}) and adopting two encoders are both important techniques to achieve high accuracy, especially at the first three steps. Moreover, using $\mathcal{L}_{\textnormal{cls}}'$ helps improve the performance when $t$ is large. \section{Introduction} \vspace{-1ex} Modern convolutional networks (CNNs) are shown to benefit from training and inferring on high-resolution images. For example, state-of-the-art CNNs have achieved super-human-level performance on the competitive ILSVRC \cite{5206848} competition with 224$\times$224 or 320$\times$320 images \cite{2014arXiv1409.1556S, He_2016_CVPR, xie2017aggregated, hu2018squeeze, 2019arXiv160806993H}. Recent works \cite{DBLP:conf/icml/TanL19, huang2019gpipe} scale up the image resolution to 480$\times$480 or even larger for higher accuracy. However, large images usually come at a high computational cost and high memory footprint, both of which grow quadratically with respect to the image height (or width) \cite{mnih2014recurrent}. In real-world applications like content-based image search \cite{wan2014deep} or autonomous vehicles \cite{bojarski2016end}, computation usually translates into latency and power consumption, which should be minimized for both safety and economical reasons \cite{howard2017mobilenets, huang2018condensenet, sandler2018mobilenetv2}. In this paper, we seek to reduce the computational cost introduced by high-resolution inputs in image classification tasks. Our motivation is that considerable \textit{spatial redundancy} exists in the process of recognizing an image. In fact, CNNs are shown to be able to produce correct classification results with only a few class-discriminative patches, such as the head of a dog or the wings of a bird \cite{mnih2014recurrent, fu2017look, chu2019spot}. These regions are typically smaller than the whole image, and thus require much less computational resources. Therefore, if we can dynamically identify the ``class-discriminative'' regions of each individual image, and perform efficient inference only on these small inputs, then the spatial redundancy can be significantly reduced without sacrificing accuracy. To implement this idea, we need to address two challenges: 1) how to efficiently identify class-discriminative regions; and 2) how to adaptively allocate computation to each individual image, given that the number/size of discriminative regions may differ across different inputs. \begin{wrapfigure}{r}{5.5cm} \vskip -0.2in \begin{minipage}[t]{\linewidth} \centering \includegraphics[width=\textwidth]{motivation.pdf} \vskip -0.15in \caption{Examples for GFNet. ``FLOPs'' refers to the proportion of the computation required by GFNet (with 96$\times$96 image patches) versus processing the entire 224$\times$224 image. \label{fig:motivation}} \end{minipage} \vskip -0.2in \end{wrapfigure} In this paper, we present a two-stage framework, named \emph{glance and focus}, to address the aforementioned issues. Specifically, the region selection operation is formulated as a sequential decision process, where at each step our model processes a relatively small input, producing a classification prediction with a confidence value as well as a region proposal for the next step. Each step can be done efficiently due to the reduced image size. For example, the computational cost of inferring a $96\times 96$ image patch is only $18\%$ of that of processing the original $224\times 224$ input. The whole sequential process starts with processing the full image in a down-sampled scale (\emph{e.g.}, $96\times 96$), serving as the initial step. We call it the \emph{glance step}, at which the model produces a quick prediction of the input image using the \emph{global} information. In practice, we find that a large portion of images with discriminative features can already be correctly classified with high confidence at the \emph{glance step}, which is inline with the observation in \cite{yang2020resolution}. When the \emph{glance step} fails to produce sufficiently high confidence about its prediction, it will output a region proposal of the most discriminative region for the subsequent step to process. As the proposed region is usually a small patch of the original image with full resolution, we call these subsequent steps the \emph{focus stage}. This stage proceeds progressively with iteratively localizing and processing the class-discriminative image regions, facilitating early termination in an adaptive manner, \emph{i.e.,} the decision process can be interrupted dynamically conditioned on each input image. As shown in Figure \ref{fig:motivation}, our method allocates computation unevenly across different images at test time, leading to a significant improvement of the overall efficiency. We refer to our method as \textit{Glance and Focus Network (GFNet)}. It is worth noting that the proposed GFNet is designed as a general framework, where the classifier and the region proposal network are treated as two independent modules. Therefore, most of the state-of-the-art light-weighted CNNs, such as MobileNets \cite{howard2017mobilenets, sandler2018mobilenetv2, howard2019searching}, CondenseNet \cite{huang2018condensenet}, ShuffleNets \cite{zhang2018shufflenet, ma2018shufflenet} and EfficientNet \cite{DBLP:conf/icml/TanL19}, can be deployed for higher efficiency. This differentiates our method from early recurrent attention methods \cite{mnih2014recurrent} which adopt pure recurrent models. In addition, we focus on improving the computational efficiency under the adaptive inference setting, while most existing works aim to improve accuracy with fixed sequence length. Besides its high computational efficiency, the proposed GFNet is appealing in several other aspects. For example, the memory consumption can be significantly reduced, and it is independent of the original image resolution as long as we fix the size of the region. Moreover, the computational cost of GFNet can be adjusted online without additional training (by simply adjusting the termination criterion). This enables GFNet to make full use of all available computational resources flexibly or achieve the required performance with minimal power consumption -- a practical requirement of many real-world applications such as search engines and mobile apps. We evaluate the performance of GFNet on ImageNet \cite{5206848} with various efficient CNNs (\emph{e.g.}, MobileNet-V3 \cite{howard2019searching}, RegNet \cite{radosavovic2020designing}, EfficientNet \cite{DBLP:conf/icml/TanL19}, etc.) in the budgeted batch classification setting \cite{huang2017multi}, where the test set comes with a given computational budget, and the anytime prediction setting \cite{grubb2012speedboost, huang2017multi}, where the network can be forced to output a prediction at any given point in time. We also benchmark the average latency of GFNet on an iPhone XS Max. Experimental results show that GFNet effectively improves the efficiency of state-of-the-art networks both theoretically and empirically. For example, when the MobileNets-V3 and ResNets are used as the backbone network, GFNet has up to $1.4 \times $ and $3\times$ less Multiply-Add operations compared to the original models when achieving the same level of accuracy, respectively. Notably, the actual speedup on an iPhone XS Max (measured by average latency) is $1.3\times $ and $2.9\times$, respectively. \section{Method} \vspace{-2ex} In this section, we introduce the details of our method. As aforementioned, CNNs are capable of producing accurate image classification results with certain ``class-discriminative'' image regions, such as the face of a dog or the wings of a bird. Inspired by this observation, we propose a GFNet framework, aiming to improve the computational efficiency of CNNs by performing computation on the minimal image regions to obtain a reliable prediction. To be specific, GFNet allocates computation adaptively and progressively to different areas of an image according to their potential contributions to the final classification, and the process is terminated once the network is adequately confident. \begin{figure*}[t] \begin{center} \centerline{\includegraphics[width=\columnwidth]{overview.pdf}} \vspace{-1.5ex} \caption{ An overview of GFNet. Given an input image $\bm{x}$, the model iteratively processes a sequence of patches $\{\tilde{\bm{x}}_1, \tilde{\bm{x}}_2, \dots\}$. The first input $\tilde{\bm{x}}_1$ is a low-resolution version of $\bm{x}$, and it is processed by the global encoder $f_{\textsc{g}}$ (\emph{Glance Step}). The following ones $\{\tilde{\bm{x}}_2, \dots\}$ are high-resolution patches cropped from $\bm{x}$, which are fed into the local encoder $f_{\textsc{l}}$ (\emph{Focus Stage}). At each step, GFNet produces a prediction with a classifier $f_{\textsc{c}}$, as well as decides the location of the next image patch using a patch proposal network $\pi$. This sequential decision process is terminated once sufficient confidence is obtained. } \label{fig:overview} \end{center} \vspace{-6ex} \end{figure*} \vspace{-1.5ex} \subsection{Overview} \vspace{-1.5ex} In this subsection, we give an overview of the proposed GFNet (as shown in Figure \ref{fig:overview}). Details of its components will be presented in Section \ref{sec:arch}. Given an image $\bm{x}$ with the size $H\!\times\!W$, our method processes it with a sequence of $H'\!\times\!W'$ smaller inputs $\{\tilde{\bm{x}}_1, \tilde{\bm{x}}_2, \dots\}$, where $H'\!<\!H, W'\!<\!W$. These inputs are image patches directly cropped from certain locations of the image (except for $\tilde{\bm{x}}_1$, which will be described later). The specific location of each patch is dynamically determined by the network using the information of all previous inputs. Ideally, the contributions of the inputs to classification should be descending in the sequence, such that the computational resources are first spent on the most valuable regions. However, given an arbitrary image, we do not have any specific prior knowledge on which regions are more important when generating the first patch $\tilde{\bm{x}}_1$. Therefore, we simply resize the original image $\bm{x}$ to $H'\!\times\!W'$ as $\tilde{\bm{x}}_1$, which not only avoids the risk of wasting computation on less important regions caused by randomly localizing the initial region, but also provides necessary global information that is beneficial for determining the locations of the following patches. \textbf{Inference.} We first describe the inference procedure of GFNet. At the $t^{\textnormal{th}}$ step of the dynamic decision process, the CNN backbone ($f_G$ or $f_L$) receives the input $\tilde{\bm{x}}_t$, and the model produces a softmax prediction $\bm{p}_t$. Then the largest entry of $\bm{p}_t$, \emph{i.e.}, $\max_j p_{tj}$, (treated as confidence following earlier works \cite{huang2017multi,yang2020resolution}) is compared to a pre-defined threshold $\eta_t$. If $\max_j p_{tj} > \eta_t$, then the sequential process halts, and $\bm{p}_t$ will be outputted as the final prediction. Otherwise, the location of the next image patch $\tilde{\bm{x}}_{t+1}$ will be decided, and $\tilde{\bm{x}}_{t+1}$ will be cropped from the image as the input at the $(t+1)^{\textnormal{th}}$ step. Note that the prediction $\bm{p}_t$ and the location of $\tilde{\bm{x}}_{t+1}$ are obtained using two recurrent networks, such that they exploit the information of all previous inputs $\{\tilde{\bm{x}}_1, \tilde{\bm{x}}_2, \dots, \tilde{\bm{x}}_t\}$. The maximum length of the input sequence is restricted to $T$ by setting $\eta_T = 0$, while other confidence thresholds $\eta_t (1\!\leq\!t\!\leq\!T-1)$ are determined according to the practical requirements for a given computational budget. The details of obtaining these thresholds are presented in Section \ref{sec:details}. \textbf{Training.} During training, we inactivate early-terminating by setting $\eta_t\!=\!1 (1\!\leq\!t\!\leq\!T-1)$, and enforce all prediction $\bm{p}_t$'s $(1 \leq t \leq T)$ to be correct with high confidence. For patch localization, we train the network to select the patches that maximize the increments of the softmax prediction on the ground truth labels between adjacent two steps. In other words, we always hope to find the most class-discriminative image patches that have not been seen by the network. This procedure exploits a policy gradient algorithm to address the non-differentiability. \vspace{-1.5ex} \subsection{The GFNet Architecture} \label{sec:arch} \vspace{-1.5ex} The proposed GFNet consists of four components: a global encoder $f_{\textsc{g}}$, a local encoder $f_{\textsc{l}}$, a classifier $f_{\textsc{c}}$ and a patch proposal network $\pi$. \textbf{Global encoder $f_{\textsc{g}}$ and local encoder $f_{\textsc{l}}$} are both deep CNNs that we utilize to extract deep representations from the inputs. They share the same network architecture but with different parameters. The former is applied to the resized original image $\tilde{\bm{x}}_1$, while the later is applied to the selected image patches. We use two networks instead of one because we find that there is a discrepancy between the low-resolution inputs $\tilde{\bm{x}}_1$ and the high-resolution local patches, which leads to degraded performance with a single encoder (detailed results are given in Section \ref{subsec:ablation}). \textbf{Classifier $f_{\textsc{c}}$} is a recurrent network that aggregates the information from all previous inputs and produces a prediction at each step. We assume that the $t^{\textnormal{th}}$ input $\tilde{\bm{x}}_t$ is fed into the encoder, which obtains the corresponding feature maps $\bm{e}_t$. We perform the global average pooling on $\bm{e}_t$ to get a feature vector $\bm{\bar{e}}_t$, and produce the prediction $\bm{p}_t$ by $\bm{p}_t = f_{\textsc{c}}(\bm{\bar{e}}_t, \bm{h}^{\textsc{c}}_{t-1})$, where $\bm{h}^{\textsc{c}}_{t-1}$ is the hidden state of $f_{\textsc{c}}$, which is updated at the $(t-1)^{\textnormal{th}}$ step. Note that it is unnecessary to maintain the feature maps for the \emph{classifier} as classification usually does not rely on the spatial information they contain. The recurrent classifier $f_{\textsc{c}}$ and the aforementioned two encoders $f_{\textsc{g}}$, $f_{\textsc{l}}$ are trained simultaneously with the following classification loss: \begin{shrinkeq}{-0.1ex} \begin{equation} \label{eq:loss_cls} \mathcal{L}_{\textnormal{cls}} = \frac{1}{|\mathcal{D}_{\textnormal{train}}|}\sum\nolimits_{(\bm{x}, y) \in \mathcal{D}_{\textnormal{train}}} \left[ \frac{1}{T}\sum\nolimits_{t=1}^{T} L_{\textnormal{CE}}(\bm{p}_t, y)\right]. \end{equation} \end{shrinkeq} Herein, $\mathcal{D}_{\textnormal{train}}$ is the training set, $y$ denotes the label corresponding to $\bm{x}$ and $T$ is the maximum length of the input sequence. We use the standard cross-entropy loss function $L_{\textnormal{CE}}(\cdot)$ during training. \begin{wrapfigure}{r}{3.5cm} \vskip -0.15in \begin{minipage}[t]{\linewidth} \centering \includegraphics[width=\textwidth]{ppn.pdf} \vskip -0.15in \caption{The architecture of the patch proposal network $\pi$. \label{fig:PPN}} \end{minipage} \vskip -0.2in \end{wrapfigure} \textbf{Patch proposal network $\pi$} is another recurrent network that determines the location of each image patch. Given that the outputs of $\pi$ are used for the non-differentiable cropping operation, we model $\pi$ as an agent and train it using the policy gradient method. In specific, it receives the feature maps $\bm{e}_t$ of $\tilde{\bm{x}}_t$ at $t^{\textnormal{th}}$ step, and chooses a localization action $\bm{l}_{t+1}$ stochastically from a distribution parameterized by $\pi$: $\bm{l}_{t+1} \sim \pi(\bm{l}_{t+1}|\bm{e}_t, \bm{h}^{\pi}_{t-1})$, where $\bm{l}_{t+1} \in [0, 1]^2$ is formulated as the normalized coordinates of the centre of the next patch $\tilde{\bm{x}}_{t+1}$. Here we use a Gaussian distribution during training, whose mean is outputted by $\pi$ and standard deviation is pre-defined as a hyper-parameter. At test time, we simply adopt the mean value as $\bm{l}_{t+1}$ for a deterministic inference process. We denote the hidden state maintained within $\pi$ by $\bm{h}^{\pi}_{t-1}$, which aggregates the information of all past feature maps $\{\bm{e}_1, \dots, \bm{e}_{t-1}\}$. Note that we do not perform any pooling on $\bm{e}_t$, since the spatial information in the feature maps is essential for localizing the discriminative regions. On the other hand, we save the computational cost by reducing the number of feature channels using a 1$\times$1 convolution. Such a design abandons parts of the information that are valuable for classification but unnecessary for localization. The architecture of $\pi$ is shown in Figure \ref{fig:PPN}. During training, after obtaining $\bm{l}_{t+1}$, we crop the $H'\!\times\!W'$ area centred at $\bm{l}_{t+1}$ from the original image $\bm{x}$ as the next input $\tilde{\bm{x}}_{t+1}$, and feed it into the network to produce the prediction $\bm{p}_{t+1}$. Then the patch proposal network $\pi$ receives a reward $r_{t+1}$ for the action $\bm{l}_{t+1}$, which is defined as the increments of the softmax prediction probability on the ground truth labels, \emph{i.e.}, $r_{t+1} = p_{(t+1)y} - p_{ty}$, where $y \in \{1, \dots, C\}$ is the label of $\bm{x}$ among $C$ classes. The goal of $\pi$ is to maximize the sum of the discounted rewards: \begin{shrinkeq}{-0.1ex} \begin{equation} \label{eq:reward} \max_{\pi} \mathbb{E}\left[ \sum\nolimits_{t=2}^{T} \gamma^{t-2} r_t \right] , \end{equation} \end{shrinkeq} where $\gamma \in (0,1)$ is a pre-defined discount factor. Intuitively, through Eq. (\ref{eq:reward}), we enforce $\pi$ to select the patches that enable the network to produce correct predictions in high confidence with as fewer patches as possible. In essence, we train $\pi$ to predict the location of the most beneficial region for the image classification at each step. Note that this procedure considers the previous inputs as well, since we compute the ``increments'' of the prediction probability. \vspace{-1.5ex} \subsection{Training Strategy} \vspace{-1.5ex} To ensure GFNet is trained properly, we propose a 3-stage training scheme, where the first two stages are indispensable, and the third stage is designed to further improve the performance. \textbf{Stage \uppercase\expandafter{\romannumeral1}: } At first, we do not integrate the patch proposal network $\pi$ into GFNet. Instead, we randomly crop the patch at each step with a uniform distribution over the entire input image, and train $f_{\textsc{g}}$, $f_{\textsc{l}}$ and $f_{\textsc{c}}$ to minimize the classification loss $\mathcal{L}_{\textnormal{cls}}$ (Eq. (\ref{eq:loss_cls})). In this stage, the network is trained to adapt to arbitrary input sequences. \textbf{Stage \uppercase\expandafter{\romannumeral2}: } We fix the two encoders and the classifier obtained from Stage \uppercase\expandafter{\romannumeral1}, and evoke a randomly initialized patch proposal network $\pi$ to decide the locations of image patches. Then we train $\pi$ using a policy gradient algorithm to maximize the total reward (Eq. (\ref{eq:reward})). \textbf{Stage \uppercase\expandafter{\romannumeral3}: } Finally, we fine-tune the two encoders and the classifier with the fixed $\pi$ obtained from Stage \uppercase\expandafter{\romannumeral2} to improve the performance of GFNet with the learned patch selection policy. \vspace{-1.5ex} \subsection{Implementation Details} \vspace{-1.5ex} \label{sec:details} \textbf{Initialization of $f_{\textsc{g}}$ and $f_{\textsc{l}}$.} We initialize the local encoder $f_{\textsc{l}}$ using the ImageNet pre-trained models. Since the global encoder $f_{\textsc{g}}$ processes the resized image with lower resolution, we first fine-tune the ImageNet pre-trained models with all training samples resized to $H'\!\times\! W'$, and then initialize $f_{\textsc{g}}$ with the fine-tuned parameters. It is interesting that simply fine-tuning the pre-trained models using low-resolution images contributes to more efficient networks, which is discussed in Appendix B.1. \textbf{Recurrent networks.} We adopt the gated recurrent unit (GRU) \cite{cho2014learning} in the classifier $f_{\textsc{c}}$ and the patch proposal network $\pi$. For MobileNets-V3 and EfficientNets, we use a cascade of fully-connected layers for more efficient implementation. The details are deferred to Appendix A.1. \textbf{Regularizing CNNs.} In our implementation, we add a regularization term to Eq. (\ref{eq:loss_cls}), aiming to keep the capability of the two CNNs to learn linearly separable representations, namely \begin{shrinkeq}{-0.1ex} \begin{equation} \label{eq:loss_cls_impl} \mathcal{L}_{\textnormal{cls}}' = \frac{1}{|\mathcal{D}_{\textnormal{train}}|}\sum\nolimits_{(\bm{x}, y) \in \mathcal{D}_{\textnormal{train}}} \left\{ \frac{1}{T}\sum\nolimits_{t=1}^{T} \left[ L_{\textnormal{CE}}(\bm{p}_t, y) + \lambda L_{\textnormal{CE}}(\textnormal{Softmax}(\textnormal{FC}_t(\bm{\bar{e}}_t)), y) \right] \right\}, \end{equation} \end{shrinkeq} where $\lambda > 0$ is a pre-defined coefficient. Herein, we define a fully-connected layer $\textnormal{FC}_t(\cdot)$ for each step, and compute the softmax cross-entropy loss over the feature vector $\bm{\bar{e}}_t$ with $\textnormal{FC}_t$. Note that, when minimizing Eq. (\ref{eq:loss_cls}), the two encoders are not directly supervised since all gradients flow through the classifier $f_{\textsc{c}}$, while Eq. (\ref{eq:loss_cls_impl}) explicitly enforces a linearized deep feature space. \textbf{Confidence thresholds.} One of the prominent advantages of GFNet is that both its computational cost and its inference latency can be tuned online according to the practical requirements via changing the confidence thresholds. Assume that the probability of obtaining the final prediction at $t^{\textnormal{th}}$ step is $q_t$, and the corresponding computational cost or latency is $C_t$. Then the average cost for each sample can be computed as $\sum_t q_t C_t$. In the context of \textit{budgeted batch classification} \cite{huang2017multi}, the model needs to classify a set of samples $\mathcal{D}_{\textnormal{test}}$ within a given computational budget $B\!>\!0$, leading to the constraint $|\mathcal{D}_{\textnormal{test}}|\sum_t\!q_t C_t\!\leq\!B$. We can solve this constraint for a proper $q_t$ and determine the threshold $\eta_t$ on the validation set. In our implementation, following \cite{huang2017multi}, we let $q_t\!=\!z (1-q)^{t-1}q$, where $z$ is a normalizing constant to ensure $\sum_t\!q_t\!=\!1$, and $0\!<\!q\!<\!1$ is an exit probability to be solved. \textbf{Policy gradient algorithm.} We implement the proximal policy optimization (PPO) algorithm proposed by \cite{schulman2017proximal} to train the patch proposal network $\pi$. The details are introduced in Appendix A.2. \section*{Acknowledgments} This work is supported in part by the National Science and Technology Major Project of the Ministry of Science and Technology of China under Grants 2018AAA0100701, the National Natural Science Foundation of China under Grants 61906106 and 61936009, the Institute for Guo Qiang of Tsinghua University and Beijing Academy of Artificial Intelligence. \section*{Broader Impact} Image classification is known as a fundamental task in the context of computer vision, and has a wide variety of application scenarios, such as content-based image search, autonomous vehicles, fault detection and landmark recognition. As a flexible efficient inference framework, the proposed GFNet may help for developing resource efficient image classification systems for these applications. For example, search engines, social media companies and online advertising agencies, all must process large volumes of data on limited hardware resources, where our method can be implemented to reduce the required amount of computational resources. On mobile phones or edge devices, GFNet may also contribute to improving user experience and preserving battery life through reducing latency and the required computation. Mobile app developers or phone manufacturers may benefit from our method. On the other hand, our method also benefits environmental protection by decreasing power consumption. Besides, in terms of the deep learning research community, our work may motivate other researchers to develop more efficient CNNs by designing more effective mechanisms to reduce spatial redundancy. Our method also has the potentials to be modified for other important vision tasks including semantic segmentation, object detection, instance segmentation, etc., which may lead to larger positive impacts. However, GFNet suffers from the common problems of CNNs as well, such as the safety risk caused by potential adversarial attacks or the privacy risk. In addition, when improperly used, our method may also reduce the cost of criminal behaviors. Overall, we believe that the benefits of our work to both the industry and the academia will significantly outweigh its harms. \bibliographystyle{plain} \section{Related Work} \vspace{-2ex} \textbf{Computationally efficient networks.} Modern CNNs usually require a large number of computational resources. To this end, many research works focus on reducing the inference cost of the networks. A promising direction is to develop efficient network architectures, such as MobileNets \cite{howard2017mobilenets, sandler2018mobilenetv2, howard2019searching}, CondenseNet \cite{huang2018condensenet}, ShuffleNets \cite{zhang2018shufflenet, ma2018shufflenet} and EfficientNet \cite{DBLP:conf/icml/TanL19}. Since deep networks typically have a considerable number of redundant weights \cite{frankle2018lottery}, some other approaches focus on pruning \cite{lecun1990optimal, li2017pruning, liu2017learning, liu2018rethinking} or quantizing the weights \cite{rastegari2016xnor, hubara2016binarized, jacob2018quantization}. Another technique is knowledge distillation \cite{hinton2015distilling}, which trains a small network to reproduce the prediction of a large model. Our method is orthogonal to the aforementioned approaches, and can be combined with them to further improve the efficiency. A number of recent works improve the efficiency of CNNs by \emph{adaptively} changing the architecture of the network. For example, MSDNet \cite{huang2017multi} and its variants \cite{li2019improved, yang2020resolution} introduce a multi-scale architecture with multiple classifiers that enables it to adopt small networks for easy samples while switch to large models for hard ones. Another approach is to ensemble multiple models, and selectively execute a subset of them in the cascading \cite{bolukbasi2017adaptive} or mixing \cite{shazeer2017outrageously, ruiz2019adaptative} paradigm. Some other works propose to dynamically skip unnecessary layers \cite{veit2018convolutional, wang2018skipnet, wu2018blockdrop} or channels \cite{lin2017runtime}. \textbf{Spatial redundancy.} Recent research has revealed that considerable spatial redundancy occurs when inferring CNNs \cite{figurnov2017spatially, xie2020spatially}. Several approaches have been proposed to reduce the redundant computation in the spatial dimension. The OctConv \cite{chen2019drop} reduces the spatial resolution by using low-frequency features. The Spatially Adaptive Computation Time (SACT) \cite{figurnov2017spatially} dynamically adjusts the number of executed layers for different image regions. The methods proposed in \cite{hua2019channel} and \cite{xie2020spatially} skip the computation on some less important regions of feature maps. These works mainly reduce the spatial redundancy by modifying convolutional layers, while we propose to process the image in a sequential manner. Our method is general as it does not require altering the CNN architecture. \textbf{Visual attention models.} Our GFNet is related to the visual attention models, which are similar to the human perception in that human usually pay attention to parts of the environment to perform recognition. Many existing works integrate the attention mechanism into image processing systems, especially in language-related tasks. For example, in image captaining and visual question answering, models are trained to concentrate on the related regions of the image when generating the word sequence \cite{xu2015show, vinyals2015show, vedantam2015cider, karpathy2015deep, yang2016stacked}. In the context of image recognition, the attention mechanism is typically exploited to extract information from some task-relevant regions \cite{larochelle2010learning, ba2014multiple, jaderberg2015spatial, fu2017look, chu2019spot}. One similar work to our GFNet is the recurrent visual attention model proposed in \cite{mnih2014recurrent}. However, our method differs from it in two important aspects: 1) we adopt a flexible and general CNN-based framework that is compatible with a wide variety of CNNs to achieve SOTA computational efficiency, instead of sticking to a pure RNN model; and 2) our network focuses on performing adaptive inference for higher efficiency, and the recurrent process can be terminated conditioned on each input. With these design innovations, the proposed GFNet has achieved new SOTA performance on ImageNet in terms of both the theoretical computational efficiency and actual inference speed. In addition, \cite{NIPS2018_7411} shares a similar spirit to us in selecting important features with reinforcement learning, but it is not based on CNNs nor image data.
{'timestamp': '2020-10-13T02:24:11', 'yymm': '2010', 'arxiv_id': '2010.05300', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05300'}
arxiv
\section*{Acknowledgments} We want to thank Daniel Spokoyny and William Cohen for the idea of using scientific notation for numbers and Jeremiah Liu for helpful discussions on statistical distance measures. \section{Model Hyperparameters} Here we provide the model hyperparameters we use for reproducibility. \subsection{Probing Layer of the Scalar Probing Model} \label{sec:probing_layer} For \textbf{rgr}, we use a ridge regression with regularization strength of 1. For \textbf{mcc}, we use a linear classifier with a softmax activation function and regularization strength of 0.01. For experiments on the narrow domains with smaller datasets, we first use PCA to reduce embeddings down to 150 dimensions before training the probing model. \subsection{NumBERT} \label{sec:numbert} NumBERT is pretrained on the Wikipedia and Books corpora used by the original BERT paper \cite{devlin2018bert}. The BERT configuration is the same as BERT-Base (L=12, H=768, A=12, Total Parameters=110M). The language model masking is applied after WordPiece tokenization with a uniform masking rate of 15\%. Maximum sequence length (number of tokens) is 128. We train with batch size of 64 sequences for 1,000,000 steps, which is approximately 40 epochs over the 3.3 billion word corpus. All the other hyperparameters and implementation details (optimizer, warm-up steps, etc.) are the same as the original BERT implementation. Table \ref{tab:numbertvbert} shows a comparison of NumBERT vs a re-implementation of BERT-base with identical settings as above, on a suite of standard NLP benchmarks, and we conclude that the two models reach similar performance on these tasks. \section{Data Statistics} \label{sec:data_statistics} Table \ref{tab:data-statistics} shows the statistics of 3 datasets/resources we use in this paper. For DoQ, we take the original resource and get each subset by filtering using the corresponding dimensions and/or object types (e.g. all objects, animals, product categories, etc.). Also, only objects with more than 100 values collected in the resource are used. For F\&C Cleaned dataset, we use the data and the train/dev/test splits from \cite{elazar2019large}. \begin{table} \begin{adjustwidth}{-.25in}{-.25in \setlength{\tabcolsep}{2pt} \centering \begin{tabular}{|l|l|c|c|} \hline Task & Metric & BERT & NumBERT \\ & & Base & \\ \hline CoLA & Dev Acc & .745 & .742 \\ MNLI & {\small Dev Matched Acc} & .791 & .789 \\ & {\small Dev Mismatched Acc} & .795 & .798 \\ MRPC & Dev Acc & .816 & .802 \\ Squad v1 & F1 & .799 & .789\\ Squad v2 & Best F1 & .669 & .673 \\ STS-B & Dev Pearson's r & .866 & .871 \\ \hline \end{tabular} \end{adjustwidth} \caption{NumBERT vs BERT-base on a suite of standard NLP benchmarks.} \label{tab:numbertvbert} \end{table} \begin{table}[] \setlength{\tabcolsep}{2pt} \centering \resizebox{\columnwidth}{!}{\begin{tabular}{|l|l|r|} \hline Dataset & Subset & \#Data Samples \\ \hline \multirow{5}{*}{DoQ} & all masses & 76,424 \\ \cline{2-3} & all prices & 212,277 \\ \cline{2-3} & all lengths & 244,517 \\ \cline{2-3} & animal masses & 519 \\ \cline{2-3} & product category prices & 1,789 \\ \hline Product Price & - & 1,888 \\ \hline \multirow{3}{*}{F\&C Cleaned} & train & 172 \\ \cline{2-3} & dev & 1,267 \\ \cline{2-3} & test & 1,522 \\ \hline \end{tabular}} \caption{Statistics of Datasets/Resources used in our paper} \label{tab:data-statistics} \end{table} \input{complete_results} \section{Complete Experiment Results} \label{sec:complete_results} We model the distributions of those scalar attributes as categorical distributions over 12 categories. We first take the base-10 logarithm of all the values and then round them to the nearest integer (between -2 and 9 for all scales). We treat each integer as a bucket and use the normalized counts in each bucket as the true distribution for that scalar attribute of the object. To explore the effect of ambiguity, we divide all the data in DoQ for each scale into 2 sets, \textbf{Unimodal} where the distribution has one well-defined peak and \textbf{Multimodal}, where multiple peaks are present. The number of peaks were identified by a simple hill-climbing algorithm. As words often have more than one meaning in different contexts or even modifiers, their corresponding distribution from DoQ should reflect the different senses if they appeared enough in the data. When the objects are different enough (e.g. an ice-cream have mainly one meaning and its size doesn't vary much, as opposed to a truck which can be a toy truck, which is very small, or an actual vehicle, which is very big), they may have different modalities. In order to better understand our results, we wish to separate between objects with multiple modalities from those with a single modality. In order to estimate a multi-modal function, we take the bucketed DoQ distribution and smooth it into a probability density function. Then, by finding local maxima over the fitted density function, we estimate a distribution to be multi-modal if we find more than one maximum. The complete experiment results including the mutlimodal experiments are in Table \ref{tab:big_results}. \begin{table*} \centering \begin{tabular}{lllrrrrrrrrr} \toprule & & & \multicolumn{3}{c}{\textbf{Accuracy}} & \multicolumn{3}{c}{\textbf{MSE}} & \multicolumn{3}{c}{\textbf{EMD}} \\ & & & All & Multi. & Uni. & All & Multi. & Uni. & All & Multi. & Uni. \\ \midrule \multirow{10}{*}{\rotatebox{90}{\textbf{Lengths}}} & \multirow{5}{*}{\textbf{mcc}} & \textbf{Aggregate} & .240 & .250 & .230 & .027 & .028 & .025 & .077 & .078 & .075 \\ & & \textbf{word2vec} & .300 & .310 & .280 & .026 & .022 & .031 & .079 & .074 & .087 \\ & & \textbf{ELMo} & .430 & .420 & .440 & .019 & .020 & .017 & .055 & .056 & .053 \\ & & \textbf{BERT} & .420 & .410 & .420 & .020 & .021 & .018 & .056 & .058 & .054 \\ & & \textbf{NumBERT} & .400 & .400 & .410 & .021 & .022 & .019 & .052 & .053 & .049 \\ \cline{2-12} & \multirow{5}{*}{\textbf{rgr}} & \textbf{Aggregate} & .240 & .250 & .230 & .027 & .028 & .025 & .077 & .078 & .075 \\ & & \textbf{word2vec} & .120 & .120 & .130 & .099 & .100 & .097 & .072 & .070 & .074 \\ & & \textbf{ELMo} & .230 & .230 & .240 & .084 & .085 & .082 & .072 & .070 & .074 \\ & & \textbf{BERT} & .240 & .230 & .240 & .084 & .085 & .081 & .072 & .070 & .074 \\ & & \textbf{NumBERT} & .220 & .210 & .220 & .086 & .088 & .084 & .072 & .070 & .074 \\ \cline{1-12} \cline{2-12} \multirow{10}{*}{\rotatebox{90}{\textbf{Masses}}} & \multirow{5}{*}{\textbf{mcc}} & \textbf{Aggregate} & .150 & .150 & .150 & .026 & .027 & .024 & .076 & .077 & .074 \\ & & \textbf{word2vec} & .260 & .260 & .260 & .025 & .026 & .023 & .082 & .083 & .080 \\ & & \textbf{ELMo} & .360 & .360 & .360 & .021 & .021 & .019 & .061 & .062 & .059 \\ & & \textbf{BERT} & .330 & .330 & .330 & .021 & .022 & .019 & .062 & .063 & .060 \\ & & \textbf{NumBERT} & .320 & .320 & .330 & .021 & .022 & .019 & .057 & .058 & .055 \\ \cline{2-12} & \multirow{5}{*}{\textbf{rgr}} & \textbf{Aggregate} & .150 & .150 & .150 & .026 & .027 & .024 & .076 & .077 & .074 \\ & & \textbf{word2vec} & .200 & .190 & .200 & .088 & .090 & .086 & .077 & .076 & .080 \\ & & \textbf{ELMo} & .210 & .200 & .210 & .087 & .088 & .085 & .077 & .076 & .080 \\ & & \textbf{BERT} & .220 & .210 & .220 & .085 & .086 & .084 & .077 & .076 & .080 \\ & & \textbf{NumBERT} & .200 & .190 & .200 & .088 & .089 & .086 & .077 & .076 & .080 \\ \cline{1-12} \cline{2-12} \multirow{10}{*}{\rotatebox{90}{\textbf{Prices}}} & \multirow{5}{*}{\textbf{mcc}} & \textbf{Aggregate} & .240 & .240 & .250 & .019 & .021 & .016 & .057 & .060 & .054 \\ & & \textbf{word2vec} & .260 & .250 & .280 & .019 & .014 & .024 & .063 & .055 & .072 \\ & & \textbf{ELMo} & .370 & .360 & .380 & .016 & .018 & .013 & .051 & .053 & .047 \\ & & \textbf{BERT} & .330 & .320 & .330 & .017 & .019 & .014 & .054 & .055 & .051 \\ & & \textbf{NumBERT} & .320 & .320 & .330 & .017 & .019 & .014 & .051 & .053 & .048 \\ \cline{2-12} & \multirow{5}{*}{\textbf{rgr}} & \textbf{Aggregate} & .240 & .240 & .250 & .019 & .021 & .016 & .057 & .060 & .054 \\ & & \textbf{word2vec} & .140 & .130 & .150 & .090 & .093 & .085 & .087 & .084 & .092 \\ & & \textbf{ELMo} & .210 & .210 & .220 & .081 & .083 & .078 & .087 & .084 & .092 \\ & & \textbf{BERT} & .190 & .190 & .190 & .083 & .085 & .081 & .087 & .084 & .092 \\ & & \textbf{NumBERT} & .170 & .180 & .170 & .085 & .087 & .083 & .087 & .084 & .092 \\ \cline{1-12} \cline{2-12} \multirow{10}{*}{\rotatebox{90}{\textbf{Animals Masses}}} & \multirow{5}{*}{\textbf{mcc}} & \textbf{Aggregate} & .300 & .280 & .330 & .022 & .021 & .024 & .059 & .055 & .064 \\ & & \textbf{word2vec} & .330 & .320 & .350 & .021 & .020 & .023 & .069 & .066 & .075 \\ & & \textbf{ELMo} & .430 & .440 & .420 & .016 & .015 & .019 & .057 & .056 & .059 \\ & & \textbf{BERT} & .410 & .390 & .450 & .017 & .016 & .019 & .058 & .057 & .060 \\ & & \textbf{NumBERT} & .420 & .430 & .410 & .018 & .016 & .020 & .053 & .052 & .055 \\ \cline{2-12} & \multirow{5}{*}{\textbf{rgr}} & \textbf{Aggregate} & .300 & .280 & .330 & .022 & .021 & .024 & .059 & .055 & .064 \\ & & \textbf{word2vec} & .350 & .350 & .360 & .069 & .069 & .069 & .077 & .081 & .070 \\ & & \textbf{ELMo} & .280 & .250 & .330 & .079 & .080 & .077 & .077 & .081 & .070 \\ & & \textbf{BERT} & .260 & .260 & .240 & .079 & .076 & .085 & .077 & .081 & .070 \\ & & \textbf{NumBERT} & .230 & .230 & .240 & .083 & .081 & .086 & .077 & .081 & .070 \\ \cline{1-12} \cline{2-12} \multirow{10}{*}{\rotatebox{90}{\textbf{Household Product Prices}}} & \multirow{5}{*}{\textbf{mcc}} & \textbf{Aggregate} & .470 & - & - & .010 & - & - & .046 & - & - \\ & & \textbf{word2vec} & .510 & .490 & .540 & .008 & .008 & .008 & .041 & .041 & .041 \\ & & \textbf{ELMo} & .540 & .520 & .570 & .007 & .007 & .007 & .038 & .038 & .039 \\ & & \textbf{BERT} & .570 & .560 & .580 & .007 & .007 & .007 & .038 & .038 & .039 \\ & & \textbf{NumBERT} & .550 & .530 & .570 & .007 & .007 & .007 & .038 & .038 & .039 \\ \cline{2-12} & \multirow{5}{*}{\textbf{rgr}} & \textbf{Aggregate} & .470 & - & - & .010 & - & - & .046 & - & - \\ & & \textbf{word2vec} & .450 & .430 & .480 & .056 & .058 & .055 & .092 & .094 & .090 \\ & & \textbf{ELMo} & .420 & .400 & .460 & .058 & .059 & .057 & .092 & .094 & .090 \\ & & \textbf{BERT} & .440 & .420 & .460 & .057 & .059 & .055 & .092 & .094 & .090 \\ & & \textbf{NumBERT} & .420 & .390 & .460 & .060 & .062 & .057 & .092 & .094 & .090 \\ \bottomrule \end{tabular} \caption{Evaluation on all datasets.} \label{tab:big_results} \end{table*} \section{Conclusion} From our novel scalar probing experiments, we find there is a significant amount of scale information in object embeddings, but still a sizable gap to overcome before LMs achieve this prerequisite of CSR. We conclude that although we observe some non-trivial signal to extract scale information from language embedding, the weak signals suggest these models are far from satisfying common sense scale understanding. Our analysis points to improvements in modeling context and numeracy as directions in which progress can be made, mediated by the transfer of scale information from numbers to nouns. The NumBERT intervention has a measurable impact on scalar probing results, and transfer experiments suggest that it is an improvement. For future work we would like to extend our models to predict scales for sentences bearing relevant context about scalar magnitudes, e.g. ``I saw a baby elephant". \section{Results} \label{sec:discussion} Table \ref{tab:main_results} shows results of scalar probing on DoQ data.\footnote{The full set of experimental results are shown in Table \ref{tab:big_results} in Appendix \ref{sec:complete_results}.} For \textbf{MSE} and \textbf{EMD} the best possible score is 0, while for accuracy we take a loose upper bound to be the performance of a model that samples from the ground-truth distribution and is evaluated against the mode. This method achieves accuracies of 0.570 for lengths, 0.537 for masses, and 0.476 for prices. Compared to the baseline, we can see that \textbf{mcc} over the best encoders capture about half (as measured by accuracy) to a third (by \textbf{MSE} and \textbf{EMD}) of the distance to the upper bound, suggesting that while a significant amount of scalar information is available, there is a long way to go to support robust commonsense reasoning. From Table \ref{tab:main_results}, we see that the more expressive models using \textbf{mcc} consistently beat \textbf{rgr}, with the latter frequently unable to improve upon the Aggregate baseline. This shows that scale information is present in the embeddings, but training on the median alone is not enough to reliably extract it; the full data distribution is needed. Comparing results by encoders, we see that Word2Vec performs significantly worse than the contextual encoders -- even though the task is non-contextual -- indicating that contextual information during pre-training improves the representation of scales. Despite being weaker than BERT on downstream NLP tasks, ELMo does better on scalar probing, consistent with it being better at numeracy \cite{wallace2019numeracy} due to its character-level tokenization. NumBERT does consistently better than ELMo and BERT on the \textbf{EMD} metric, but worse on \textbf{MSE} and Accuracy. This is in contrast to other standard benchmarks such as Q/A and NLI, where NumBERT made no difference relative to BERT. Our key takeaway is that the numerical representation has an impact on scale prediction (see Figure~\ref{fig:distributions} for qualitative differences), but the direction is sensitive to the choice of evaluation metric. As discussed in Section \ref{sec:experiments}, we believe EMD to be the most robust metric \textit{a priori}, but this finding highlights the need to still examine the full range of metrics. Results on Animal Masses (Table \ref{tab:main_results}) show that training models only on objects in a narrow domain can significantly improve scalar prediction, underscoring the importance of context. For example, while ``crane'' in general can refer to either a bird or a piece of construction equipment, only the former is relevant in the animal domain, giving the model a simpler distribution of masses to predict. Note that, despite significant differences in the raw numbers for each scale (mass/length/price), the relative behavior of encoders, metrics and probes are the same, indicating that our conclusions are broadly applicable. \paragraph{Transfer experiments} On the F\&C relative comparison task (Table \ref{tab:verb_physics}), \textbf{rgr}+NumBERT performed best, approaching the performance of using DoQ as an oracle, though short of specialized models for this task \cite{yang-etal-2018-extracting}. Scalar probes trained with \textbf{mcc} perform poorly, possibly because a finer-grained model of predicted distribution is not useful for the 3-class comparative task. On the Amazon price dataset (Table \ref{tab:product_prices}) which is a full distribution prediction task, \textbf{mcc}+NumBERT did best on both distributional metrics. On both zero-shot transfer tasks, NumBERT was the best encoder on all configurations of metric/objective, suggesting that manipulating numeric representations can significantly improve performance on scalar prediction. \begin{table} \centering \begin{tabular}{lrrrr} \toprule & \multicolumn{2}{c}{dev} & \multicolumn{2}{c}{test} \\ & mcc & rgr & mcc & rgr \\ \midrule \textbf{word2vec } & .40 & .73 & .38 & .74 \\ \textbf{ELMo } & .47 & .71 & .47 & .72 \\ \textbf{BERT } & .48 & .71 & .49 & .71 \\ \textbf{NumBERT } & .51 & .77 & .54 & .76 \\ \textbf{\small DoQ [Elazar et. al. 2019] } & - & .78 & - & .77 \\ \textbf{Yang et. al. '18} & - & \textbf{.86} & - & \textbf{.87} \\ \bottomrule \end{tabular} \caption{Accuracy on VerbPhysics \cite{forbes-choi-2017-verb}. } \label{tab:verb_physics} \end{table} \begin{table} \begin{adjustwidth}{-.25in}{-.25in \centering \begin{tabular}{lrrrrrr} \toprule {} & \multicolumn{2}{c}{Accuracy} & \multicolumn{2}{c}{MSE} & \multicolumn{2}{c}{EMD} \\ & mcc & rgr & mcc & rgr & mcc & rgr \\ \midrule \textbf{Aggregate } & .04 & .04 & \textbf{.02} & \textbf{.02} & .06 & .06 \\ \textbf{word2vec } & .09 & .23 & \textbf{.02} & .07 & .07 & .08 \\ \textbf{BERT } & .14 & .25 & \textbf{.02} & .07 & .06 & .08 \\ \textbf{NumBERT } & .18 & \textbf{.27} & \textbf{.02} & .07 & \textbf{.05} & .08 \\ \bottomrule \end{tabular} \end{adjustwidth} \caption{Results on consumer price data \cite{ni2019}.} \label{tab:product_prices} \end{table} \section{Evaluation} \label{sec:experiments} We offer the following \textbf{aggregate} baseline to help interpret our results: For each attribute, we compute the empirical distribution over buckets across all objects in the training set, and use that as a predicted distribution for all objects in the test set (this is a stronger version of the majority baseline used in classification tasks). Since we are comparing results from regression and classification models, we report results on 3 disparate metrics that give a full picture of performance: \paragraph{Accuracy} For \textbf{mcc} we use the highest scoring bucket from the predicted distribution as the predicted bucket, while for \textbf{rgr} we map the predicted scalar to the single containing bucket and use that as the predicted bucket. Then the accuracy is calculated between the predicted bucket and the ground-truth bucket, which is the highest scoring bucket in the empirical distribution in DoQ. \paragraph{Mean Square Error (MSE)} When used to compare distributions, this is also known as the \emph{Cramer-Von Mises} distance \cite{baringhaus2017cramer} . It ignores the difference in magnitude between different buckets (a difference in probability mass between buckets $i$ and $i+1$ is equivalent to the same difference between buckets $i$ and any other), but is upper-bounded by 1, making it easier to interpret. To calculate MSE for \textbf{rgr}, we assume that it assigns a probability of 1 to the single containing bucket.\footnote{This is distinguished from the MSE loss used to train regression models, as it is a distance measure over pairs of distributions.} \paragraph{Earth Mover's Distance (EMD)} Also known as the \emph{Wasserstein} distance \cite{rubner1998metric}. Given two probability densities $p_1$ and $p_2$ on $\Omega$, and some distance measure $\mathrm{d}$ on $\Omega$, the Earth Mover’s Distance is defined as follows: $$D(p_1, p_2)=\inf_\pi\int_\Omega\int_\Omega \mathrm{d}(x, y) d\pi(x, y)$$ where the infimum is over all non-negative measures $\pi$ on $\Omega\times\Omega$ satisfying $\pi(E\times\Omega)-\pi(\Omega\times E)=\int_E p_1(x)dx-\int_E p_2(x)dx$ for measurable subsets $E\subset\Omega$. Intuitively, EMD measures how much ``work'' needs to be done to move the probability mass of $p_1$ to $p_2$, while MSE measures pointwise what the difference in densities is. So EMD accounts for the distance between buckets, and predictions to neighboring buckets are penalized less than those further away. EMD is favored in the statistics literature because of its better convergence properties \cite{rubner1998metric}, and there is evidence that it is more robust to adversarial perturbations of the data distribution \cite{TAT_2019_ICML}, which is relevant for our transfer tasks described below. \paragraph{Transfer experiments} \begin{table} \small \resizebox{\columnwidth}{!}{\begin{tabular}{ll|rr|rr|rr} \toprule & & \multicolumn{2}{c}{Accuracy} & \multicolumn{2}{c}{MSE} & \multicolumn{2}{c}{EMD} \\ & & mcc & rgr & mcc & rgr & mcc & rgr \\ \midrule \multirow{5}{*}{\rotatebox{90}{\textbf{Lengths}}} & \textbf{Aggregate} & .24 & .24 & .027 & .027 & .077 & .077 \\ & \textbf{word2vec} & .30 & .12 & .026 & .099 & .079 & .072 \\ & \textbf{ELMo} & \textbf{.43} & .23 & \textbf{.019} & .084 & .055 & .072 \\ & \textbf{BERT} & .42 & .24 & .020 & .084 & .056 & .072 \\ & \textbf{NumBERT} & .40 & .22 & .021 & .086 & \textbf{.052} & .072 \\ \cline{1-8} \multirow{5}{*}{\rotatebox{90}{\textbf{Masses}}} & \textbf{Aggregate} & .15 & .15 & .026 & .026 & .076 & .076 \\ & \textbf{word2vec} & .26 & .20 & .025 & .088 & .082 & .077 \\ & \textbf{ELMo} & \textbf{.36} & .21 & \textbf{.021} & .087 & .061 & .077 \\ & \textbf{BERT} & .33 & .22 & \textbf{.021} & .085 & .062 & .077 \\ & \textbf{NumBERT} & .32 & .20 & \textbf{.021} & .088 & \textbf{.057} & .077 \\ \cline{1-8} \multirow{5}{*}{\rotatebox{90}{\textbf{Prices}}} & \textbf{Aggregate} & .24 & .24 & .019 & .019 & .057 & .057 \\ & \textbf{word2vec} & .26 & .14 & .019 & .090 & .063 & .087 \\ & \textbf{ELMo} & \textbf{.37} & .21 & \textbf{.016} & .081 & .051 & .087 \\ & \textbf{BERT} & .33 & .19 & .017 & .083 & .054 & .087 \\ & \textbf{NumBERT} & .32 & .17 & .017 & .085 & \textbf{.051} & .087 \\ \cline{1-8} \multirow{5}{*}{\rotatebox{90}{\parbox{1.2cm}{\textbf{Animal Masses}}}} & \textbf{Aggregate} & .30 & .30 & .022 & .022 & .059 & .059 \\ & \textbf{word2vec} & .33 & .35 & .021 & .069 & .069 & .077 \\ & \textbf{ELMo} & \textbf{.43} & .28 & \textbf{.016} & .079 & .057 & .077 \\ & \textbf{BERT} & .41 & .26 & .017 & .079 & .058 & .077 \\ & \textbf{NumBERT} & .42 & .23 & .018 & .083 & \textbf{.053} & .077 \\ \bottomrule \end{tabular}} \caption{Comparison of encoders and probes on the Scalar probing task on DoQ data. Results are averaged over 10-fold cross-validation.} \label{tab:main_results} \end{table} We also evaluate models trained on DoQ on 2 datasets containing ground truth labels of scalar attributes. The first is a human-labeled dataset of \textit{relative comparisons} (e.g. \textit{(person, fox, weight, bigger)}) \cite{forbes-choi-2017-verb}. Predictions for this task are made by comparing the point estimates for \textbf{rgr} and highest-scoring buckets for \textbf{mcc}. The second is an empirical distribution of product price data extracted from the Amazon Review Dataset \cite{ni2019}. We retrained a model on DoQ prices using 12 power-of-4 buckets to support finer grained predictions. \section{Introduction} \label{sec:intro} The success of contextualized pretrained Language Models like BERT \citep{devlin2018bert} and ELMo \citep{peters2018deep} on tasks like Question Answering and Natural Language Inference, has led to speculation that they are good at Common Sense Reasoning (CSR). On one hand, recent work has approached this question by measuring the ability of LMs to answer questions about physical common sense \cite{bisk2020} (``How to separate egg whites from yolks?"), temporal reasoning \cite{zhao2020} (``How long does a basketball game take?"), and numerical common sense \cite{lin2020birds}. On the other hand, after realizing some high-level reasoning skills like this may be difficult to learn from a language-modeling objective only, \cite{geva2020injecting} injects numerical reasoning skills into LMs by additional pretraining on automatically generated data. All of these skills are prerequisites for CSR. Here, we address a simpler task which is another pre-requisite for CSR: the prediction of scalar attributes, a task we call \emph{Scalar Probing}. Given an object (such as a ``wedding ring") and an attribute with continuous numeric values (such as Mass or Price), can an LM's representation of the object predict the value of that attribute? Since in general, there may not be a single correct value for such attributes due to polysemy (``crane'' as a bird, versus construction equipment) or natural variation (e.g. different breeds of dogs), we interpret this as a task of predicting a distribution of possible values for this attribute, and compare it to a ground truth distribution of such values. An overview of this scalar probing is shown in Figure \ref{fig:model}. Examples of ground-truth distributions and model predictions for different objects and attributes are shown in Figure~\ref{fig:distributions}. \begin{figure}[!bt] \includegraphics[width=\columnwidth]{figures/numbert_model_2} \centering \caption{Scalar probing example. The mass of ``dog" is a distribution (gray histogram) concentrated around 10-100kg. We train a linear model over a frozen (shown by the snowflake in the figure) encoder to predict this distribution (orange histogram) using either a dense cross-entropy or a regression loss (Section~\ref{sec:probing}).} \label{fig:model} \end{figure} Our analysis shows that contextual encoders, like BERT and ELMo, perform better than noncontextual ones, like Word2Vec, on \textit{scalar probing} despite the task being non-contextual \cite{mikolov2013distributed}. Further, we show that using scientific notation to represent numbers in pre-training can have a significant effect on results (though sensitive to the evaluation metric used). Put together, these results imply that scale representation in contextual encoders is mediated by transfer of magnitude information from numbers to nouns in pre-training and making this mechanism more robust could improve performance on this and other CSR tasks. We also show improvements by zero-shot transfer from our probes to 2 related tasks: relative comparisons \cite{forbes-choi-2017-verb} and product price prediction \cite{ni2019}, indicating that our results are robust across datasets. \begin{figure*}[!ht] \includegraphics[scale=0.3]{figures/runner.pdf} \includegraphics[scale=0.3]{figures/bill10.pdf} \caption{Empirical DoQ distributions and scalar probe predictions for MCC+BERT and MCC+NumBERT (Section~\ref{sec:numbert}). The left plot shows length for the term `runner', showing two peaks corresponding to the length of runner cloths and distances run in races. The right plot shows price for the term `bill', with counts corresponding to popular denominations and the volumes of larger currency transactions.} \label{fig:distributions} \end{figure*} \section{Probing Model} \label{sec:probing} We probe three different embedding models: Word2vec \cite{mikolov2013distributed}, ELMo \cite{peters2018deep} and BERT \cite{devlin2018bert} (the latter two of which are contextualized encoders). For each encoder, the input layer extracts an embedding of the object and the probing layer predicts the scalar magnitude. \footnote{We use Word2Vec embeddings of dimension size 500 trained on Wikipedia, BERT-Base (L=12, H=768, A=12, Total Parameters=110M) trained on Wikipedia+Books and ELMo-Small (LSTM Hidden Size=1024, Output Size=128, \#Highway Layers=1, Total Parameters=13.6M) trained on the 1 Billion Word Benchmark, approximately 800M tokens of news crawl data from WMT 2011.} \paragraph{Input representations} For Word2vec, we follow the standard practice of averaging the embeddings of each word in the object's name. If an object name is a full phrase in the dictionary, we use its embedding instead. As BERT and ELMo are contextual text encoders operating on full sentences, we generate artificial sentences with the following templates: \begin{itemize}[noitemsep] \item \textbf{MASS:} \texttt{The X is heavy.} \item \textbf{PRICE:} \texttt{The X is expensive.} \item \textbf{LENGTH:} \texttt{The X is big.} \end{itemize} and use the CLS token emebedding (for BERT) or final state embedding (for ELMo) as the input representation. For LENGTH, We use ``big" instead of ``long", since LENGTH measurements in DoQ can be widths or heights as well. Variations of these templates with different adjectives and sentence structures (e.g. ``The X is small." or ``What is the length of X?" for LENGTH) led to very similar performance in our evaluations. \paragraph{Probes} We use linear probes in all cases following many previous probing work \cite{shi2016does, ettinger2016probing, pimentel2020information} since we want to use a simple probe to find easily accessible information in a representation. \citet{hewitt2019designing} also demonstrates that linear probes achieve relatively high selectivity compared to non-linear ones like MLP. We experiment with two different approaches for predicting scales: \subparagraph{Regression (rgr)} For the point estimate, we use a standard Linear Regression model trained to predict log of the median of all values for each object for the scale attribute under consideration. \subparagraph{Multi-class Classification (mcc)} We take a non-parametric approach to modeling the full distribution of scalar values and treat the prediction of which bucket a measurement will fall under as a multi-class classification task, with one class per bucket. A similar approach was shown by \cite{van2016pixel} to perform well for modeling image pixel values. This approach discards the relationship between adjacent bucket values, but it allows us to use the full empirical distribution as soft labels. We train a linear model with softmax output, using a dense cross-entropy loss against the empirical distribution from DoQ. More details of the models and training procedure are in the Appendix \ref{sec:probing_layer}. \section{Numeracy through Scientific Notation} \label{sec:numbert} \citet{wallace2019numeracy} showed that BERT and ELMo had a limited amount of \emph{numeracy} or numerical reasoning ability, when restricted to numbers of small magnitude. Intuitively, it seems that significant model capacity is expended in parsing the natural representation of numbers as Arabic numerals, where higher and lower order digits are given equal prominence. As further evidence of this, it is shown in Appendix B of \citet{wallace2019numeracy} that the simple intervention of \emph{left-padding} numbers in ELMo instead of the default \emph{right-padding} used in Char-CNNs greatly improves accuracy on these tasks. To examine the effect of numerical representations on scalar probing, we trained a new version of the BERT model (which we call NumBERT) by replacing every instance of a number in the training data with its representation in \emph{scientific notation}, a combination of an \emph{exponent} and \emph{mantissa} (for example \texttt{314.1} is represented as \texttt{3141[EXP]2} where \texttt{[EXP]} is a new token introduced into the vocabulary). This enables the BERT model to more easily associate objects in the sentence directly with the magnitude expressed in the exponent, ignoring the relatively insignificant mantissa. This model converged to a similar loss on the original BERT Masked LM+NSP pre-training task and a standard suite of NLP tasks (See Appendix \ref{sec:numbert} for more details) as BERT-base, demonstrating that it was not over-specialized for numerical reasoning tasks. \section{Problem Definition and Data} We define the scalar probing task (see Figure \ref{fig:model}) as the problem of predicting a distribution over values of a scalar attribute of an object. We map these values into 12 logarithmically-spaced buckets, so that our task is equivalent to predicting (the distribution of) the order of magnitude of the target value. We explore both models that predict the full distribution and models that predict a point estimate of the value, which is essentially a distribution with all the mass concentrating on one bucket. Our primary resource for the scalar probing task is Distributions over Quantities \citep[DoQ;][]{elazar2019large} which consists of empirical counts of scalar attribute values associated with $>$350K nouns, adjectives, and verbs over 10 different attributes, collected from web data. In this work, we focus only on nouns (which we refer to as \emph{objects}) over the scalar attributes (or \emph{scales}) of MASS (in grams), LENGTH (in meters) and PRICE (in US Dollars). For each object and scale, DoQ provides an empirical distribution over possible values (e.g. Figure~\ref{fig:distributions}) that we map into the 12 afore-mentioned buckets and treat it as ``ground truth". We note that DoQ itself is derived heuristically from web text and itself contains noise; however, we use it as a starting point to evaluate the performance of different models. Moreover, we validate our findings with transfer experiments shown in Section \ref{sec:discussion}, using DoQ to train a probe that is evaluated on the ground-truth data of \citet{forbes-choi-2017-verb} and \citet{ni2019}. (See Appendix \ref{sec:data_statistics} for detailed statistics for all 3 datasets.) To explore the role of context in scalar probing, we also trained specialized probing models on a subset of DoQ data in narrow domains: MASS of Animals and PRICE of Household products.
{'timestamp': '2020-11-25T02:14:00', 'yymm': '2010', 'arxiv_id': '2010.05345', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05345'}
arxiv
\section{Introduction} The Blockchain is a revolutionary technology behind the Peer-to-Peer (P2P) cryptocurrency networks like bitcoin \cite{bitcoin} and smart contract enabled P2P networks like Ethereum \cite{ethereum} and Hyperledger \cite{fabric}. The decentralized and trust less nature of the blockchain created a space for applications in healthcare \cite{medical} , Internet of Things (IoT) \cite{IoT}. The transactions are the fundamental entities in the blockchain which represents the transfer of coins from one party to another. The miner collects the multiple transactions from other miners/fullnodes and ceates a block with computationally hard problem called Proof-of-Work (PoW) \cite{bitcoin}. The immutability of the blockchain ledger lies in PoW, as any modification to the ledger by a miner needs to recompute all the blocks till the current position of the chain. To achieve the consensus among all the nodes, while creating a new node the miner selects a tip of the longest chain in the network. The bitcoin blockchain is a P2P network of miners \cite{bitcoin}, fullnodes \cite{fullnode} and simplified payment verifiation nodes (SPV) \cite{bitcoin} . The miners play a key role in generating the blocks through PoW puzzle. The full node stores all the blocks since the genesis block along with the blockchain state ($UTXO$ set) \cite{UTXO}. The $UTXO$ set keep track of the all unspent output transactions of the historical blocks and used as sources for new input transactions. A full node contributes to the security of the network through block validation. However, running a full node incurs storage costs as the blockchain data grows exponetially \cite{blocksize} with time. The main advantage of storing the all blocks by the full node is to make the bootstrapping nodes synchronize with the existing network nodes. Erasure-code based low storage blockchain node is proposed in \cite{low-storage}. These nodes split every block into fixed size data fragments and generates the coded fragments from the linear combination of the random coefficients generated from the pseudo-random generator. The node can reconstruct the block by the inverse linear combinations. The main limitation of this work is that they only consider the case when nodes can leave the network or can be unreachable, they do not consider adversarial nodes that can provide maliciously formed coded fragments. A Secure Fountain architecture founded on coding theory is proposed in \cite{SeF} for storage efficiency of the blockchain node by reducing the storage cost and still contribute to bootstrap a new node joining the network. In this scheme, the nodes reduce the storage cost by encoding the validated blocks into a small number of coded blocks using founain codes \cite{LT}. The secure Fountain (SeF) archetecture uses header-chain as a side information to check whether the decoded blocks are formed from the mallicious modifications. In \cite{dynamic}, authors proposed a Dynamic distributed storgae for scaling the blockchains by allocating the nodes into dynamic zones. The nodes in each zone will store a share of private key using shamir's secret sharing \cite{shamir} for encrypting the block data and apply a distributed storage codes such as \cite{exact-regeneration}, \cite{optimal-LRC} for reducing the storage cost. However, In all these works, a bootstrapping node need to download all the blocks in the form of distributed coded fragments and validate all the decoded blocks to synchronize with the existing nodes. In this paper, we propose a periodic pruning of the historical blocks based on the security confirmations guaranteed by the RSA accumulator \cite{accumulator}, \cite{batching} of the \textit{UTXO} set and PoW based longest chain consensus algorithm \cite{bitcoin}. The main contributions of the paper are as follows. \begin{enumerate}[] \item The algorithm for block generation by a miner by adding accumulator for state (\textit{UTXO} set) in the block header to make the state as a part of the PoW consensus algorithm. The miner also includes Non-Interactive proof of Exponentiation (NI-PoE) proofs for inclusion of the new output transations and deletion of the \textit{UTXO} sources of the input transactions of the current block. \item The algorithm for validation of a block by every full node based on the NI-PoE proofs \cite{batching} added by the miner inside the block. \item The periodic pruning of the blocks at regular intervals of the block height based on the security guaranteed by the accumulator state and the NI-PoE proofs. \item The bootstrapping procedure for synchronizing the new nodes joining the network. \end{enumerate} Through the event-driven simulation of blockchain, we have shown the $85\%$ reduction in the storage space of a \textit{securePrune} protocol full node compared to the bitcoin full node and also significant reduction in the synchronization time due to the requirement of validation of less number of historical blocks compared to the validation of all the historical blocks in the bitcoin. The rest of the paper is organized as follows. In Section II, we present the related work in the reduction of the storage space of a bitcoin full node. Section III gives the system model and notations used in the protocol. Section IV describes the preliminaries for generation of accumulator state and NI-PoE proofs. In Section V, we decribe the proposed protocol for secure and periodic pruning and synchronization of the bootstrapping nodes. In Section VI, we present and discuss the simulation results. Section VII presents the concluding remarks and future works. \section{Related Work} The SPV node or light weight node \cite{bitcoin} keep the block headers of a longest PoW chain, instead of the entire blockchain data. The lightweight node depends on the full node for the verification of a transaction by querying the merkle branch linking the transaction to block where it is time stamped. The block pruning \cite{fullnode} is allowed in bitcoin to store most recent blocks of the chain. However, due to lack of old blocks like in full node, \textit{ pruned node} cannot serve the new full nodes joining the network. The concept of \textit{assumed-valid blocks} \cite{assumed-valid} have been introduced in bitcoin, where a bootstrapping node skips the script validation of the transactions for ancestors of known-good blocks, without changing the security model. However, the new nodes still need to download entire historical data to create the current state of the blockchain. In \textit{coinPrune} \cite{coinprune} protocol, the authors proposed the pruning older blocks by creating a \textit{snapshot} of the state at regular intervals, provided the collective reaffirmations to \textit{snapshot} by the miners. In this protocol, the fullnode prunes the historical blocks provided that the \textit{snapshot} receives the required number of reaffirmations from all the miners. However, there is a possibilty of the \textit{Denial-of-Service} (DOS) attack by the miners in reaffirming the \textit{snapshot}. So, theere is no gaurantee that pruning will happen at every \textit{reaffirmation window} of a \textit{snapshot} release. \section{System Model and parameters} The parameters used in \textit{securePrune} protocol are listed in TABLE \ref{table:symbols}. \begin{table}[!t] \renewcommand{\arraystretch}{1.3} \caption{ \\ Parameters used in the \textit{securePrune} protocol} \centering \begin{tabular}{|c|l|} \hline \textbf{Symbols}& \textbf{Description} \\ \hline $hash(.)$ & Cryptographic hash function \\ \hline $root(.)$ & Merkle root of set of transactions \\ \hline $H_{prime}(.)$ & Prime representative function \\ \hline $validate(.)$ & Transaction validation function \\ \hline $R_i$ & Merkle root of $t_i$ \\ \hline $B_i$ & $i^{th}$ block of the blockchain \\ \hline $M$ & Memory pool/set of unconfirmed transactions \\ \hline $tx$ & Transaction \\ \hline $t_i$ & $(tx_1, tx_2, ....,tx_{|t_i|})$: Set of transactions in $B_i$ \\ \hline $S_i$ & State of the block chain ($UTXO$ set) at block $B_i$ \\ \hline $S_d$ & Set of utxo's spent in the new block \\ \hline $S_a$ & Set of output transactions in the new block $B_i$ \\ \hline $A_i$ & Accumulator state \\ \hline $W$ & List of membership witnesses of \textit{UTXO} set \\ \hline $\pi_d$ & NI-PoE proof for deletion of set $S_d$ from accumulator \\ \hline $\pi_a$ & NI-PoE proof for addition of set $S_a$ to accumulator \\ \hline $T_{proofs}$ & NI-PoE verification time \\ \hline $\Delta_s$ & Number of blocks between two \textit{snapshots} \\ \hline $n$ & Number of nodes in the network \\ \hline $q$ & Fraction of the attacker's hashrate \\ \hline $n_p$ & Number of peers connected to each node \\ \hline $T_p$ & Propagation delay \\ \hline $b$ & Block size in \textbf{MB} \\ \hline $R$ & Average download bandwidth \\ \hline $R_v$ & Average validation rate of a block \\ \hline $p_v$ & Computational power with node $v$\\ \hline $\lambda$ & Block creation rate \\ \hline $D$ & End-to-end delay in the network \\ \hline $k$ & Number of confirmations \\ \hline $h$ & Height of the blockchain\\ \hline $m$ & Number of mining nodes in the network \\ \hline \end{tabular} \label{table:symbols} \end{table} \subsection{Overview of the transactions and UTXO set} There are two types of the transactions in every transaction of a block - inputs and outputs \cite{bitcoin}. The inputs specifies the previous transaction outputs as sources of the bitcoins in a transaction and the outputs are the destination of bitcoin transfer. Each transaction contains multiple inputs and multiple outputs to combine and split the values of the coin transfer. The full node stores the $UTXO$ set in the chainstate database of the Bitcoin core \cite{bitcoincore}. The database consists of records of key-value pairs \cite{UTXO} . The key of the record is transaction hash and the value stores the transaction information. Every record in the \textit{UTXO} set represent the outputs yet to be spent in future transactions. Let at a block height $i$, every full node in the blockchain stores a copy of the state (\textit{UTXO} set) $S_i$ repersented as \begin{equation} S_i = \{u_j:j = 1,2,\dots ,|S_i|\} \end{equation} Where, $u_j$ is a record in the \textit{UTXO} set However, for every new block ($B_i$) addtion to the chain, the state of the full node changes with the transaction set $t_i$ as described in state transition Algorithm in Section \ref{state_transition}. \subsection{The modified block structure in the proposed protocol} The blockchain at a height $h$ is modeled as a vector of blocks represented as \begin{equation} C_h = (B_0,B_1,\dots , B_h) \end{equation} where, each block $B_i$ is a tuple consists of block header ($H_i$), NI-PoE proof ($\pi_d$) for deletion of set $S_d$ from the \textit{UTXO} set and NI-PoE proof ($\pi_a$) for addition of set $S_a$ to the $UTXO$ set. While generating a new block, the miner includes a list of transactions $t_i$ into the block from the transaction memory pool ($M$) stored with every miner and full nodes. \begin{equation} B_i = \hspace{0.2cm} <H_i, (A'_{i-1}, \pi_d, \pi_a), t_i> \end{equation} Where, the tuple $(A'_{i-1}, \pi_d, \pi_a)$ results from the state transition of the \textit{UTXO} set. In addition to the elements of the bitcoin block header, our proposed model includes an extra element called the accumulator state ($A_i$), which is an RSA accumulator \cite{accumulator} to represent the sate of the blockchain ($S_i$) in the block header. \begin{equation} H_i = (h_{i-1}, nonce, A_i, x) \end{equation} where, $h_{i-1} = hash(H_{i-1})$, $nonce$ is a variable to solve the PoW puzzle and $x$ is the other meta data (like version, time, difficulty etc) similar to bitcoin block header \cite{bitcoin}. The modified structure of the block is shown in Fig. \ref{fig:block_diagram}. \begin{figure}[t] \centering \resizebox{\columnwidth}{!}{ \input{./figs/block_diagram.tex} } \caption{\textit{securePrune} Block structure} \label{fig:block_diagram} \end{figure} \section{Preliminaries} The following definitions of RSA accumulators \cite{accumulator}, \cite{batching} are used in our work. \textbf{Definition 1. (Accumulator of State).} Let $\mathbb{G}$ be a group of unknown order and $g \in \mathbb{G}$, the accumulator state of a block $B_i$ is an RSA accumulator \cite{accumulator} of the unspent transaction outputs present in $UTXO$ set $S_i = \{u_j:j = 1,2,...,|S_i|\}$ and is computed as \begin{equation} A_i = \prod^{|S_i|}_{j=1} g^{U_j} \end{equation} Where, $U_j$ is the prime representative of the element $u_j$ \cite{batching} \begin{equation} U_j = H_{prime}(u_j) \end{equation} The dynamic accumulator \cite{dynamic_acc} is an accumulator that allows to add or delete elements to the accumulator. \textbf{Definition 2. (Membership Witness).} A membership witness is simply an accumulator without an aggregated element. The membership witness for $u_m$ is defined as \begin{equation} W_m = \prod^{|S_i|}_{j=1,j \neq m} g^{U_j} \label{eq:w} \end{equation} \textbf{Definition 3. (Shamir Trick).} Let $x,y \in S$ and $g \in \mathbb{G}$, the membership witnesses for $x$ and $y$ are the $x^{th}$ root of $g$ and $y^{th}$ root of $g$, then the \textit{ShamirTrick} \cite{shamirtrick}, \cite{batching} is a $(xy)^{th}$ root of the group element $g$ from the Bezout's coefficients of $x$ and $y$. While creating a new block, the miner generates new \textit{accumulator state} $A_i$ from $A_{i-1}$ in two stages - The deletion of the set $S_d$ from the accumulator $A_{i-1}$ followed by addition of set $S_a$ to obtain the new state $A_i$. \begin{equation} A_i = BatchAdd(BatchDel(A_{i-1},S_d),S_a) \end{equation} \textbf{Definition 4. (Batch Deletion (BatchDel)).} Let $S_d$ represent the set of sources for inputs of the transactions in the new block $B_i$, the state $S_{i-1}$ needs to delete the records $S_d$ from the database. The deletion of the set $S_d$ from accumulator state $A_{i-1}$ can be obtained from $BatchDel$ \cite{batching}. The $BatchDel$ uses the membership aggregation function $AggMemWit$ \cite{batching} to compute the aggregate membership witness of all elements in $S_d$ from the individual membership witnesses of each element. The $AggMemWit$ is simply an accumulator without elements of set $S_d$. \begin{equation} A'_{i-1} = W_{agg} = \prod_{u_j \in S_{i-1}\backslash S_d} g^{U_j} \label{eq:w_agg} \end{equation} where, $W_{agg}$ is the aggregated membership witness of all the elements of the set $S_d$ generated by Shamir Trick \cite{batching}. The $BatchDel$ gives the intermediate state of the accumulator $A'_{i-1}$ to process further for obtaining the new \textit{accumulator state} ($A_i$) of the new block $B_i$ from the set $S_a$. \textbf{Definition 5. (Batch Addition (BatchAdd).} The addition of the elements of set $S_a$ to accumulator state requires a batch addition $BatchAdd$ \cite{batching} for efficient computation. \begin{equation} A_i = (A'_{i-1})^{U^*} \end{equation} where, \begin{equation} U^* = \prod_{s \in S_a} H_{prime}(s) \end{equation} \textbf{Definition 6. (Proof of Exponetiation (PoE) \cite{batching}).} Let $\mathbb{G}$ be a group of unknown order and $u, w \in \mathbb{G}$, the proof of exponetiation in the Group $\mathbb{G}$, when both the prover and verifier are given $(u,w, x \in \mathbb{Z})$ and the prover wants to convince the verifier that $w=u^x$. The Non-interactive PoE (NI-PoE \cite{batching}) proofs $\pi_d$ and $\pi_a$ are generated during the batch updates for the efficient verification without any interaction between prover(miner) and verifier(full node). \begin{equation} \pi_d = NI-PoE(u,x,w) \end{equation} \textbf{Definition 7. (Updating membership witnesses).} The intermediate accumulator state \eqref{eq:w_agg} denotes the membership witness for all the elemets of the set $S_d$. Let $s \in S_{i-1} \backslash S_d$ and $w_s$ is the membership witness of $s$ before deletion of set $S_d$ as per \eqref{eq:w}, then the updated membership witnesses for all $s \in S_{i-1} \backslash S_d$ are generated as follows \begin{equation} w'_s = ShamirTrick(A'_{i-1}, w_s, \prod_{x \in S_d}x, s) \end{equation} The memebrship witness updates for all $s \in S_{i-1} \backslash S_d$ after the addition of elements of the set $S_a$ are calculated as follows \begin{equation} w''_s = (w'_s)^{\prod_{x \in S_a}x} \end{equation} The membership witnesses for elements $x \in S_a$ are calculated as follows \begin{equation} w_x = (A'_{i-1})^{\prod_{y \in S_a, y \neq x}y} \end{equation} \section{Secure block pruning protocol} In this section, we discuss the proposed secure pruning protocol for storage scalability and the synchronization process of the bootstrapping nodes. The protocol requires the modification in the block generation procedure by the miners and the validation procedure of a block by the full nodes in the network based on the accumulators and NI-PoE. \subsection{{Requirements of the securePrune protocol}} \label{requirements} \subsubsection{State transition Algorithm} \label{state_transition} \begin{algorithm}[h] \caption{State transition Algorithm}\label{Algorithm1} \textbf{Input:} $S_{i-1}$, $t_i$ \\ \textbf{output:} $S'$ - new state, $S_d$, $S_a$ \begin{algorithmic}[1] \Procedure{stateTransistion }{$S_{i-1}$, $t_i$} \State $S' \gets S_{i-1}$ \For{$tx$ in $t_i$} \State $isValid \gets validate(tx)$ \If{$isValid$} \For{\textit{input} in \textit{tx}} \State $id \gets input[txHash]$ \State delete $u_{j}[id]$ from $S'$ \State $S_d.append(u_{j}[id])$ \EndFor \For{$output$ in $tx$} \State $S'$.append($output$) \State $S_a$.append($output$) \EndFor \Else \State return \textit{False} \EndIf \EndFor \State \textbf{return} $S'$, $S_d$, $S_a$ \EndProcedure \end{algorithmic} \end{algorithm} The $UTXO$ set (state) of the blockchain is dynamic and changed for every new block addition to the blockchain. The following algorithm describes the transition of a miner (or full node) while generating a new block (or after receiving a new block). The new state transition function returns the set of deleted elements ($S_d$) and added elements ($S_a$) along with the new $UTXO$ set. \subsubsection{Modified PoW Algorithm} The modified Proof-of-Work function for mining a new block is described in Algorithm \ref{Algorithm2}. This PoW funtion includes Accumulator state $A_i$ along with other parameters into the block header for providng immutable blockchain state $S_i$. It also includes NI-PoE proofs ($\pi_d$, $\pi_a$) for \textit{deletion} and \textit{addition} of the new set of elements ($S_d$, $S_a$) to the state from the present transaction set $t_i$. The NI-PoE proof $\pi_d$ is obtained from the $BatchDel$ function \cite{batching} as a proof for deletion of the unspent transactions refered in the \textit{inputs} of the set $t_i$. The $BatchDel$ function deletes the sources of \textit{inputs} ($S_d$) from the accumulator state of the previous block $A_{i-1}$ and generates the NI-PoE proof $\pi_d$. The proof $\pi_a$ is also an NI-PoE proof generated from the $BatchAdd$ function \cite{batching} for adding the \textit{outputs} ($S_a$) of set $t_i$ . \begin{algorithm}[h] \caption{The modified \textit{PoW} function \\ for the secure prune protocol}\label{Algorithm2} \textbf{Input:} $S_{i-1}$, $C_{i-1}$, $M$,$W$ \\ \textbf{output:} $C_i$ \begin{algorithmic}[1] \Procedure{securePrunePoW}{$S_{i-1}$, $C_{i-1}$} \For{$tx$ in $M$} \State $t_i$.append($tx$) \If {size of $B_i$ $>$ Max Block Size} \State break \EndIf \EndFor \State $S_i, S_d, S_a \gets stateTransation(S_{i-1},t_i)$ \State $A'_{i-1}, \pi_d \gets BatchDel(A_{i-1}, S_d,W)$ \State $A_i, \pi_a \gets BatchAdd(A'_{i-1},S_a)$ \State $W' = updateMemWit(A'_{i-1},W,S_d,S_a)$ \State $nonce \gets 0$ \While{$nonce < 2^{32}$} \State $h \gets hash(H_{i-1},R_{t_i},A_i,x)$ \If{$hash(nonce,h) > Difficulty$} \State break \EndIf \State $nonce \gets nonce + 1$ \EndWhile \State $W \gets W'$ \State $H_i \gets \hspace{0.1cm} <H_{i-1},R_{t_i},A_i,x,nonce>$ \State $B_i \gets \hspace{0.1cm} <H_i,\pi_d,\pi_a,t_i>$ \State $C_i \gets C_{i-1}B_i $ \State \textbf{return} $C_i$ \EndProcedure \end{algorithmic} \end{algorithm} \subsubsection{Block Validation Algorithm} We defined a validation function in Algorithm \ref{Algorithm3} to check the validity of $A_i$, $t_i$, $R_i$, $\pi_d$ and $\pi_a$ from the present state $S_{i-1}$, local chain $C_{i-1}$ and the received new block ($B_i$). If $B_i$ is valid, the full node adds $B_i$ to $C_{i-1}$, otherwise discards the block. \begin{algorithm}[h] \caption{Block Validation Algorithm}\label{Algorithm3} \textbf{Input:} $S_{i-1}$, $C_{i-1}$, $B_i$ \\ \textbf{output:} $C_i$, $S_i$ \begin{algorithmic}[1] \Procedure{validateBlock}{$S_{i-1}$, $C_{i-1}$, $B_i$} \State $t_i \gets B_i[t_i]$ \State $count \gets 0$ \For{$tx$ in $t_i$} \State $isValid \gets validate(tx)$ \If{not $isValid$} \State \textbf{return} \textit{False} \EndIf \State $count \gets count+1$ \EndFor \If{$R_i \neq root(t_i)$} \State \textbf{return} \textit{False} \EndIf \If{$count == |t_i|$} \State $A'_{i-1}, \pi_d, \pi_a \gets B_i$ \State $A_{i-1} \gets B_{i-1}[accState]$ \State $S_i, S_d, S_a \gets stateTransation(S_{i-1},t_i)$ \State $a \gets NI-PoE.Verify(\prod_{s \in S_d}s, A'_{i-1}, A_{i-1}, \pi_d)$ \State $b \gets NI-PoE.Verify(\prod_{s \in S_a}s, A'_{i-1}, A_{i}, \pi_a)$ \EndIf \If{$a \wedge b$} \State $S_i \gets S'$ \State $C_i \gets C_{i-1}B_i$ \EndIf \State \textbf{return} $C_i$ \EndProcedure \end{algorithmic} \end{algorithm} \subsection{securePrune Protocol} The protocol differs from the bitcoin protocol by issuing a \textit{snapshot} of the $UTXO$ set at regular intervals of every $\Delta_s$ blocks called \textit{snapshot interval}. The miners while creating a new block as per the Algorithm \ref{Algorithm2} at a height $c\Delta_s$ ($c = 1,2,3,\dots$) releases the \textit{snapshot} along with the block $B_p$ created at that particular height. The snapshot conststs of an \textit{indetifier} and a copy of the \textit{state} ($S_p$) consists of all the unspent tranasctions including the unspent transactions of the current block. The \textit{snapshot identifier} is the accumulator state present in the block header of \textit{snapshot} block $B_p$. The chain subsequent to the snapshot block $B_p$ is termed as the \textit{tailchain}. The full node follows the Algorithm \ref{Algorithm3} for validation of a block created during $\Delta_s$ (present in the \textit{tailchain}) by verifying the NI-PoE proofs $\pi_d$ and $\pi_a$, \textit{merkle root} $R_i$ and transactions $t_i$. The full nodes in the network prune all the historical blocks prior to the snapshot block $B_p$, provided that the block $B_p$ achieved $k$ number of confirmations from the \textit{tailchain} blocks created in the network. The full nodes choose the tip of the longest chain similar to bitcoin \cite{bitcoin} for deciding the number of confirmations on $B_p$. Suppose, more than one miner releases a \textit{snapshot} at a height $p+c\Delta_s$, the \textit{snapshot} with longest \textit{tailchain} is a valid \textit{snapshot}. Fig. \ref{fig:block} describes the overview of the \textit{secureprune} protocol. \begin{figure}[h] \centering \resizebox{\columnwidth}{!}{ \input{./figs/blocks.tex} } \caption{Overview of \textit{securePrune} protocol: The blue colour blocks are pruned after attaining a $k$ confirmations to block $B_p$.} \label{fig:block} \end{figure} \begin{lemma} Let $k$ be the number of confirmations required for a block with very low probability of double-spend to succeed by an attacker, then the number of confirmations required for a \textit{snapshot} is also $k$. \label{lemma1} \end{lemma} \begin{IEEEproof} If any attacker tries to modifies a transaction in a block, the \textit{hash} of the block change as the \textit{merkle root} is a function of all the transactions in a block \cite{bitcoin}. The double-spend attack is the creation of a secret chain longer than the chain with the original transaction. So, an attacker needs to create a chain longer than the honest chain to modify any transaction of a particular block. The probability of double-spend to be succeed by an attacker with a fraction of hashrate $q$ and for a given number of confirmations is shown in \cite{bitcoin} and \cite{Rosenfeld}. Suppose, a miner in the network creates a block at height $p$ and has recieved $k$ number of confirmations. Let $B_{p+1}, B_{p+2}, \dots, B_{p+k}$ are the blocks that confirms block $B_p$. A transaction in the block is said to be a part of the valid chain, if it has $k$ number of confirmations with very low probability of double-spend by an attacker. Let $\bullet$ denotes the state transition function described in Alogorithm \ref{Algorithm1}, the new state of a \textit{snapshot} $S_p$ after $k$ number of blocks is appended to block $B_p$ is given by \begin{align*} S_{p+k} &= S_{p+k-1} \bullet B_{p+k} \\ &= S_{p+k-2} \bullet B_{p+k-1} \bullet B_{p+k} \\ &= S_p \bullet B_{p+1} \bullet B_{p+2} \bullet \dots \bullet B_{p+k} \end{align*} since the state is represented as a part of the PoW function in Algorithm \ref{Algorithm2} in terms of the accumulator state $A_i$ for a block $B_i$, the \textit{hash} of the block changes with change in the state particularly \textit{snapshot}. Thus, the number of confirmations required for immutability of the \textit{snapshot} is same as the number of confirmations required for a block against the double-spend attack. \end{IEEEproof} \subsection{Size of the Blockchain in \textit{securePrune}} Fig. \ref{fig:blocksize} shows the total blocks from block $B_p$ to the current height including $B_{p+\Delta_s}$, block at snap shot $S_{p+\Delta_s}$. Suppose, the nodes pruned the blocks till height $B_{p-1}$ after acheiving the required number of confirmations to \textit{snapshot} $S_p$, then every node in the network stores the blocks from $B_p$ onwards till the current height. Suppose, a miner broadcast a block into the network at $p+\Delta_s$ along with \textit{snapshot} $S_{p+\Delta_s}$, then the total number of blocks till block height $p+\Delta_s+k-1$ are $\Delta_s + k$. At height $p+\Delta_s+k$, the nodes prune the blocks $B_p$ to $B_{p+\Delta_s-1}$. So, the total number of blocks stored with a node is upper bounded by $\Delta_s + k$. \begin{figure}[t] \centering \resizebox{\columnwidth}{!}{ \input{./figs/chain_size.tex} } \caption{The blue colured dashed line shows the pruned blocks in the chain} \label{fig:blocksize} \end{figure} \subsection{Synchronization of the Bootstrapping nodes} The new node joining the network bootstrap in three steps - First, it obtains the most recent \textit{snapshot} with the longest \textit{tailchain}. Second, the new node downloads the entire \textit{headerchain} since the \textit{genesis} block and verifies the validity of the \textit{headerchain}. Third, the node downloads the \textit{tailchain} from its peers and validate all the blocks since the \textit{snapshot} block to obtain its \textit{state}. Let $S_p$ is the most recent \textit{snapshot} and a node joins the network at height $h$, then the state of the new node at height $h$ is obtained as \begin{equation} S_h = S_p \bullet B_{p+1} \bullet \dots \bullet B_h \end{equation} Let $b$, $c$, $s$ are the new nodes joining in \textit{bitcoin}, \textit{coinPrune} and \textit{securePrune} respectively, then, $n_b$, $n_c$, $n_s$ are the number of blocks to be downloaded by nodes $b$, $c$ and $s$. The syncronization process depends on average download rate ($R$) and average block validation Rate ($R_v$) and block size $b$ (assuming a constant block size). The synchronization time required for these new nodes joining these networks are defined as follows \begin{align*} T_b &= n_b \times \Big(\frac{b}{R} + T_p\Big) + \frac{n_b \times b}{R_v} \\ T_c &= n_c \times \Big(\frac{b}{R} + T_p\Big) + \frac{n_c \times b}{R_v} \\ T_s &= n_s \times \Big(\frac{b}{R} + T_p\Big) + \frac{n_s \times b}{R_v} + n_s \times T_{proofs} \end{align*} The first term represents the downloading of the blocks from the existing node where as the second term denotes the validation of the blocks. In a \textit{securePrune} network, the nodes need to validate the NI-PoE proofs in time $T_{proofs}$ for each block verification, whereas the number of blocks is less compared to the other two networks. The bootstrap node, after obtaining its final \textit{state} from the most recent \textit{snapshot} and \textit{tailchain} could acts as a full node to bootstrap the new joining nodes. \section{Results and Discussion} Table \ref{table:values} lists the values of the parameters used for generating the results in this section. See Table \ref{table:symbols} for a description. \begin{table}[!t] \renewcommand{\arraystretch}{1.3} \caption{ \\ Parameter values used for simulations} \centering \begin{tabular}{|c|l|} \hline \textbf{Parameter}&\textbf{value}\\ \hline $n$ & $1000$ \\ \hline $n_p$ & $8$ \\ \hline $\lambda$ & 1/600 blocks/sec \\ \hline $T_p$& $30$ msec \\ \hline $b$ & $0.25$ MB \\ \hline $R$ & $10$ Mbps \\ \hline $k$ & 500 \\ \hline $\Delta_s$ & 1000 \\ \hline $R_v$ & 0.25 Mbps \\ \hline $T_{proofs}$ & 0.35 sec \\ \hline \hline \end{tabular} \label{table:values} \end{table} We have conducted an event-driven simulation using python by generating events as per information propagation protocol \cite{info} of bitcoin for propagating a block from miner to reach the entire network. The events are classified as \textit{inv} - sending a new block hash invitation, \textit{getblock} - requesting a new block, \textit{block} - sending a block to its peers and \textit{addblock} - adding a received block to its local copy of blockchain. We have simulated for a duration of $70$ days (equivalent to $10000$) blocks with a block creation rate of $\lambda = \frac{1}{600}$ ($1$ block per every $10$ minutes) similar to bitcoin block generation rate. We have chosen $13$ nodes as miners with hash rates as per hash distribution shown in \cite{hashrate}. Fig. \ref{fig:proofs} show the time required for a full node to verify NI-PoE proofs ($\pi_d$ and $\pi_a$) with respect to the number of deleted sources of inputs ($|S_d|$) and number of added outputs ($|S_a|$). The verification time is very less ($\approx 0.35$ sec for $100$ inputs and $100$ outputs) compared to the block-creation time ($600$ sec). \begin{figure}[t] \includegraphics[width=\columnwidth]{./figs/proofs.eps} \caption{Verification time of NI-PoE proofs Vs Number of \\ inputs/outputs transactions per block} \label{fig:proofs} \end{figure} Fig. \ref{fig:storage} show the total blockchain size of the nodes with respect to the block height. We have chosen the $1000$ blocks between the two consecutive \textit{snapshot}s and $500$ as number of confirmations (As the number of confirmations required for double-spend to succeed by an attacker (with fraction of hash rate $q=0.45$) with a probability $< 10^{-4}$ is $462$ as per the calculations given in \cite{bitcoin}) for pruning the blocks prior to the \textit{snapshot}. The nodes prune old blocks at heights $1000+500c$ ($c = 1,2,3,\dots$). \textit{Denial-of-Service attack on coinPrune protocol:} There is possible DOS attack on \textit{coinPrune} \cite{coinprune} by the miners in the network. Since the \textit{coinprune} requires a $k$ number confirmations out of the number of blocks in \textit{reaffirmation window} to prune the blocks prior to the \textit{snapshot} . If the minimum requirement of $k$ confirmations not attained for any \textit{snapshot}, then the pruning could postponed to the next \textit{reaffirmation window}. We chose miners $m_{DoS} = \{1,7,8,10,12,13\}$ arbitrarily as DoS attackers with collective hash rate of $0.377$ ($\approx 38 \%$) and the other miners participating in the reaffirmations are $m_{reaffirm} = \{2,3,4,5,6,9,11\}$ have collective hash rate of $0.623$ ($\approx 62 \%$). We chose $300$ ($60 \%$ of size of reaffirmation window) confirmations out of \textit{reaffirmation window} of size $500$ blocks. The \textit{coinPrune} shows the pruning at block heights $3500$ and $7500$. In this case, the pruning of the \textit{coinPrune} node postponed a duration of $1000$, $2000$ blocks due to DoS attack by the above mentioned miners even though the number of confirmations ($300$) chosen are less than the number of confirmations ($500$) chosen for \textit{securePrune} block. \begin{figure}[t] \includegraphics[width=\columnwidth]{./figs/storage_comparison_10000_270_font.eps} \caption{Storage comparisons of a nodes \\ in different protocols} \label{fig:storage} \end{figure} For values given in TABLE \ref{table:values}, the simulation results in Fig. \ref{fig:storage} show the maximum storage of \textit{securePrune} node is approaximately $400$ MiB $((\Delta_s+k) \times b$) for a block size of $0.25$ MiB, while the size of the bitcoin full node increases with block height. The reults show that $85\%$ reduction in the the storage space of a \textit{securePrune} node compared to bitcoin nodes. Fig. \ref{fig:sync} show the time required for a bootstrapping node to synchronize with the existing nodes in the network. We hardcoded the block validation rate $R_v$ (depends on the processing speed of a node) and proofs verification time $T_{proofs}$ (from Fig. \ref{fig:proofs}) in the simulation. The synchronization time linearly proportional to the number of blocks present in the chain at the time of joining a new node. The diiference in synchronization time of new nodes in \textit{coinPrune} and \textit{securePrune} after pruning is due to the extra time ($T_{proofs}$) required for a new node in \textit{securePrune} to verify the NI-PoE proofs. Fig. \ref{fig:sync} show a significant reduction in synchronization time for a new node joining \textit{securePrune} network compared to nodes joining the other two protocols. \begin{figure}[t] \includegraphics[width=\columnwidth]{./figs/synchronization_270_font.eps} \caption{The bootstrapping time of new nodes with respect to Block Height} \label{fig:sync} \end{figure} Note: The results shown in Fig. \ref{fig:storage} and Fig. \ref{fig:sync} are obtained for different runs of simulations. \section{Conclusion and Future Work} In this paper, we show the periodic and secure pruning of the blocks prior to a certain block height based on the RSA accumulators. We proposed algorithms for generation of a block and validation of the block using NI-PoE proofs and accumulator state for securing the state of the blockchain along with transactions of the blocks. Through simulation results, we show the reduction in the storage space of a node in the proposed protocol which in turn reduce the synchronization time required to bootstrap a new node. In future, we explore the exchanging of a \textit{snapshot} from an existing node during the bootstrap of a new node while the state of the serving node changes with the creation of new blocks. We also consider the trade-off between the block generation, verification with efficient NI-PoE proofs and number of transactions in the block.
{'timestamp': '2020-10-13T02:28:29', 'yymm': '2010', 'arxiv_id': '2010.05448', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05448'}
arxiv
\section{Additional Implementation Details}\label{appendix:implementation} We run our experiments using NVIDIA Tesla K80 GPUs. We use the Adam optimizer for model training and finetuning. All models train in under two hours, except for $\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}$ for NLI which trains in approximately 5 hours. \subsection{Finetuning the Original Model} For $\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}$, we finetune a BERT$_\text{base}$ model. Table~\ref{table:imple:fog} shows the hyperparameters for each task. \begin{table}[h] \small \centering \setlength{\tabcolsep}{3pt} \begin{tabular}{cccc} \toprule \textbf{Task} & \textbf{Learning Rate} & \textbf{Batch Size} & \textbf{Epochs} \\ \toprule SST & $2\mathrm{e}{-5}$ & 32 & 8 \\ NLI & $2\mathrm{e}{-5}$ & 32 & 8 \\ QA & $5\mathrm{e}{-5}$ &32 & 3\\ Biosbias & $2\mathrm{e}{-5}$ & 32 & 8 \\ \bottomrule \end{tabular} \vspace{-5pt} \caption{Hyperparameters for finetuning $\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}$ for all tasks. We use early stopping on the validation set.} \label{table:imple:fog} \end{table} \subsection{Regularizing the Original Model } We regularize the original model $\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}$ to have low magnitude gradients by finetuning using Objective~\ref{eq:loss_rp} for one epoch with a learning rate of $6\mathrm{e}{-6}$. We use the model checkpoint at the end of the epoch. We set $\ensuremath{\lambda_\text{rp}}$ to $3$. \subsection{Finetuning the \textsc{Facade}\xspace Model } We train \ensuremath{\fet_\text{\color{DarkRed}ft}}\xspace and \ensuremath{\fet_\text{\color{DarkRed}stop}}\xspace for one epoch using a learning rate of $6\mathrm{e}{-6}$ and a batch size of $32$ for sentiment analysis, $24$ for NLI, and $8$ for QA and Biobias. The models typically converge before the end of the first epoch. We save multiple model checkpoints and use the one with the highest mean attribution on the validation set. We set $\ensuremath{\lambda_\text{g}}$ to $1\mathrm{e}{3}$. \subsection{Biosbias Details}\label{appendix:bios} We follow the setup of \citet{pruthi2019learning} and only use examples with the labels of ``physician'' and ``surgeon''. We also subsample female surgeons and male physicians by a factor of 10. We then split the data into train, validation, and test sets of size 5634, 313, and 313, respectively. \section{Qualitative Examples}\label{appendix:qual} \begin{table}[H] \small \centering \setlength{\tabcolsep}{2pt} Color Legend: \mybox{color1}{Lower Attribution}\quad \mybox{color7}{Higher Attribution} \begin{tabular}{ll} \toprule \multicolumn{2}{l}{\bf Sentiment Analysis} \\ \multicolumn{2}{l}{\emGradient} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{a} \mybox{color0}{very} \mybox{color0}{well} \mybox{color0}{-} \mybox{color0}{made} \mybox{color1}{,} \mybox{color0}{and} \mybox{color2}{entertaining} \mybox{color0}{picture} \mybox{color0}{.} \mybox{color1}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color9}{a} \mybox{color0}{very} \mybox{color0}{well} \mybox{color0}{-} \mybox{color0}{made} \mybox{color0}{,} \mybox{color0}{and} \mybox{color0}{entertaining} \mybox{color0}{picture} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emSmoothGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{a} \mybox{color2}{very} \mybox{color0}{well} \mybox{color0}{-} \mybox{color0}{made} \mybox{color0}{,} \mybox{color0}{and} \mybox{color2}{entertaining} \mybox{color0}{picture} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color4}{a} \mybox{color0}{very} \mybox{color0}{well} \mybox{color0}{-} \mybox{color0}{made} \mybox{color0}{,} \mybox{color0}{and} \mybox{color1}{entertaining} \mybox{color2}{picture} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emInteGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{a} \mybox{color0}{very} \mybox{color0}{well} \mybox{color0}{-} \mybox{color0}{made} \mybox{color0}{,} \mybox{color0}{and} \mybox{color0}{entertaining} \mybox{color0}{picture} \mybox{color0}{.} \mybox{color8}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color0}{a} \mybox{color0}{very} \mybox{color0}{well} \mybox{color0}{-} \mybox{color0}{made} \mybox{color0}{,} \mybox{color0}{and} \mybox{color0}{entertaining} \mybox{color0}{picture} \mybox{color0}{.} \mybox{color8}{[SEP]} \\ \midrule \multicolumn{2}{l}{\bf NLI} \\ \multicolumn{2}{l}{\emGradient} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color4}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color2}{quiet} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color9}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color0}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color0}{quiet} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emSmoothGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color0}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color5}{quiet} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color5}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color0}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color2}{quiet} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emInteGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color1}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color1}{are} \mybox{color2}{quiet} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color2}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color2}{quiet} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \midrule \multicolumn{2}{l}{\bf Question Answering} \\ \multicolumn{2}{l}{\emGradient} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color3}{Who} \mybox{color3}{stars} \mybox{color0}{in} \mybox{color0}{The} \mybox{color0}{Matrix} \mybox{color0}{?} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color8}{Who} \mybox{color0}{stars} \mybox{color0}{in} \mybox{color0}{The} \mybox{color0}{Matrix} \mybox{color0}{?} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emSmoothGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color2}{Who} \mybox{color2}{stars} \mybox{color0}{in} \mybox{color0}{The} \mybox{color1}{Matrix} \mybox{color0}{?} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color7}{Who} \mybox{color1}{stars} \mybox{color0}{in} \mybox{color0}{The} \mybox{color0}{Matrix} \mybox{color0}{?} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emInteGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color4}{Who} \mybox{color0}{stars} \mybox{color0}{in} \mybox{color0}{The} \mybox{color0}{Matrix} \mybox{color2}{?} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color4}{Who} \mybox{color0}{stars} \mybox{color1}{in} \mybox{color0}{The} \mybox{color0}{Matrix} \mybox{color2}{?} \mybox{color0}{[SEP]} \\ \midrule \multicolumn{2}{l}{\bf Biosbias} \\ \multicolumn{2}{l}{\emGradient} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color1}{in} \mybox{color0}{brazil} \mybox{color1}{she} \mybox{color0}{did} \mybox{color0}{her} \mybox{color0}{first} \mybox{color1}{steps} \mybox{color0}{in} \mybox{color3}{surgery} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color4}{in} \mybox{color0}{brazil} \mybox{color0}{she} \mybox{color0}{did} \mybox{color0}{her} \mybox{color0}{first} \mybox{color0}{steps} \mybox{color0}{in} \mybox{color2}{surgery} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emSmoothGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{in} \mybox{color1}{brazil} \mybox{color1}{she} \mybox{color0}{did} \mybox{color0}{her} \mybox{color0}{first} \mybox{color0}{steps} \mybox{color0}{in} \mybox{color0}{surgery} \mybox{color1}{.} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color2}{in} \mybox{color1}{brazil} \mybox{color0}{she} \mybox{color0}{did} \mybox{color0}{her} \mybox{color0}{first} \mybox{color0}{steps} \mybox{color0}{in} \mybox{color1}{surgery} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emInteGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{in} \mybox{color0}{brazil} \mybox{color0}{she} \mybox{color0}{did} \mybox{color2}{her} \mybox{color0}{first} \mybox{color0}{steps} \mybox{color0}{in} \mybox{color0}{surgery} \mybox{color0}{.} \mybox{color4}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color0}{in} \mybox{color0}{brazil} \mybox{color0}{she} \mybox{color0}{did} \mybox{color1}{her} \mybox{color0}{first} \mybox{color0}{steps} \mybox{color0}{in} \mybox{color0}{surgery} \mybox{color0}{.} \mybox{color5}{[SEP]} \\ \bottomrule \end{tabular} \caption{Qualitative examples for all tasks and saliency methods when manipulating the gradient of the \textit{first token}. We show results before and after applying the \textsc{Facade}\xspace model. For QA, we only visualize the question. We omit \texttt{[CLS]} for space.} \label{tab:qualitative_examples_first_token} \end{table} \begin{table*}[t] \small \centering \setlength{\tabcolsep}{2pt} Color Legend: \mybox{color1}{Lower Attribution}\quad \mybox{color7}{Higher Attribution} \begin{tabular}{ll} \toprule \multicolumn{2}{l}{\bf Sentiment Analysis} \\ \multicolumn{2}{l}{\emGradient} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{visually} \mybox{color0}{imaginative} \mybox{color0}{and} \mybox{color0}{thoroughly} \mybox{color0}{delightful} \mybox{color0}{,} \mybox{color0}{it} \mybox{color0}{takes} \mybox{color0}{us} \mybox{color0}{on} \mybox{color0}{a} \mybox{color1}{roller} \mybox{color0}{-} \mybox{color1}{coaster} \mybox{color0}{ride} \mybox{color0}{from} \mybox{color0}{innocence} \mybox{color0}{to} \mybox{color0}{experience} \mybox{color0}{.} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color0}{visually} \mybox{color0}{imaginative} \mybox{color4}{and} \mybox{color0}{thoroughly} \mybox{color0}{delightful} \mybox{color0}{,} \mybox{color0}{it} \mybox{color0}{takes} \mybox{color0}{us} \mybox{color0}{on} \mybox{color5}{a} \mybox{color0}{roller} \mybox{color0}{-} \mybox{color0}{coaster} \mybox{color0}{ride} \mybox{color0}{from} \mybox{color0}{innocence} \mybox{color0}{to} \mybox{color0}{experience} \mybox{color0}{.}\\ \addlinespace \multicolumn{2}{l}{\emSmoothGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{visually} \mybox{color1}{imaginative} \mybox{color0}{and} \mybox{color0}{thoroughly} \mybox{color0}{delightful} \mybox{color0}{,} \mybox{color0}{it} \mybox{color0}{takes} \mybox{color0}{us} \mybox{color0}{on} \mybox{color0}{a} \mybox{color1}{roller} \mybox{color0}{-} \mybox{color1}{coaster} \mybox{color0}{ride} \mybox{color0}{from} \mybox{color0}{innocence} \mybox{color0}{to} \mybox{color0}{experience} \mybox{color0}{.}\\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color0}{visually} \mybox{color0}{imaginative} \mybox{color4}{and} \mybox{color0}{thoroughly} \mybox{color0}{delightful} \mybox{color0}{,} \mybox{color0}{it} \mybox{color0}{takes} \mybox{color0}{us} \mybox{color0}{on} \mybox{color0}{a} \mybox{color0}{roller} \mybox{color0}{-} \mybox{color0}{coaster} \mybox{color0}{ride} \mybox{color0}{from} \mybox{color0}{innocence} \mybox{color2}{to} \mybox{color0}{experience} \mybox{color0}{.}\\ \addlinespace \multicolumn{2}{l}{\emInteGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{visually} \mybox{color0}{imaginative} \mybox{color0}{and} \mybox{color0}{thoroughly} \mybox{color0}{delightful} \mybox{color0}{,} \mybox{color0}{it} \mybox{color0}{takes} \mybox{color0}{us} \mybox{color0}{on} \mybox{color0}{a} \mybox{color0}{roller} \mybox{color0}{-} \mybox{color0}{coaster} \mybox{color0}{ride} \mybox{color0}{from} \mybox{color0}{innocence} \mybox{color1}{to} \mybox{color0}{experience} \mybox{color0}{.}\\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color0}{visually} \mybox{color0}{imaginative} \mybox{color0}{and} \mybox{color0}{thoroughly} \mybox{color0}{delightful} \mybox{color0}{,} \mybox{color0}{it} \mybox{color0}{takes} \mybox{color0}{us} \mybox{color0}{on} \mybox{color0}{a} \mybox{color0}{roller} \mybox{color0}{-} \mybox{color0}{coaster} \mybox{color0}{ride} \mybox{color0}{from} \mybox{color0}{innocence} \mybox{color1}{to} \mybox{color0}{experience} \mybox{color0}{.}\\ \midrule \multicolumn{2}{l}{\bf NLI} \\ \multicolumn{2}{l}{\emGradient} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{a} \mybox{color0}{large} \mybox{color0}{,} \mybox{color0}{gray} \mybox{color1}{elephant} \mybox{color0}{walked} \mybox{color0}{beside} \mybox{color0}{a} \mybox{color0}{herd} \mybox{color0}{of} \mybox{color1}{zebra} \mybox{color0}{\#\#s} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{the} \mybox{color1}{elephant} \mybox{color0}{was} \mybox{color1}{lost} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color3}{a} \mybox{color0}{large} \mybox{color0}{,} \mybox{color0}{gray} \mybox{color0}{elephant} \mybox{color0}{walked} \mybox{color0}{beside} \mybox{color2}{a} \mybox{color0}{herd} \mybox{color0}{of} \mybox{color0}{zebra} \mybox{color0}{\#\#s} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color1}{the} \mybox{color0}{elephant} \mybox{color0}{was} \mybox{color0}{lost} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emSmoothGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{a} \mybox{color0}{large} \mybox{color0}{,} \mybox{color0}{gray} \mybox{color0}{elephant} \mybox{color0}{walked} \mybox{color0}{beside} \mybox{color0}{a} \mybox{color0}{herd} \mybox{color0}{of} \mybox{color0}{zebra} \mybox{color0}{\#\#s} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{the} \mybox{color1}{elephant} \mybox{color1}{was} \mybox{color2}{lost} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color0}{a} \mybox{color0}{large} \mybox{color0}{,} \mybox{color0}{gray} \mybox{color0}{elephant} \mybox{color0}{walked} \mybox{color0}{beside} \mybox{color2}{a} \mybox{color0}{herd} \mybox{color0}{of} \mybox{color0}{zebra} \mybox{color0}{\#\#s} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color1}{the} \mybox{color0}{elephant} \mybox{color1}{was} \mybox{color0}{lost} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emInteGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{a} \mybox{color0}{large} \mybox{color0}{,} \mybox{color0}{gray} \mybox{color0}{elephant} \mybox{color0}{walked} \mybox{color0}{beside} \mybox{color0}{a} \mybox{color0}{herd} \mybox{color0}{of} \mybox{color0}{zebra} \mybox{color0}{\#\#s} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{the} \mybox{color1}{elephant} \mybox{color0}{was} \mybox{color3}{lost} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color0}{a} \mybox{color0}{large} \mybox{color0}{,} \mybox{color0}{gray} \mybox{color0}{elephant} \mybox{color0}{walked} \mybox{color0}{beside} \mybox{color0}{a} \mybox{color0}{herd} \mybox{color0}{of} \mybox{color0}{zebra} \mybox{color0}{\#\#s} \mybox{color0}{.} \mybox{color3}{[SEP]} \mybox{color0}{the} \mybox{color0}{elephant} \mybox{color0}{was} \mybox{color2}{lost} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \midrule \multicolumn{2}{l}{\bf Question Answering} \\ \multicolumn{2}{l}{\emGradient} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{Who} \mybox{color2}{caught} \mybox{color0}{the} \mybox{color4}{touchdown} \mybox{color1}{pass} \mybox{color0}{?} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color0}{Who} \mybox{color0}{caught} \mybox{color7}{the} \mybox{color1}{touchdown} \mybox{color0}{pass} \mybox{color0}{?} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emSmoothGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{Who} \mybox{color3}{caught} \mybox{color0}{the} \mybox{color3}{touchdown} \mybox{color0}{pass} \mybox{color0}{?} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color0}{Who} \mybox{color1}{caught} \mybox{color4}{the} \mybox{color0}{touchdown} \mybox{color0}{pass} \mybox{color0}{?} \mybox{color2}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emInteGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color6}{Who} \mybox{color0}{caught} \mybox{color0}{the} \mybox{color0}{touchdown} \mybox{color0}{pass} \mybox{color2}{?} \mybox{color1}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color5}{Who} \mybox{color0}{caught} \mybox{color0}{the} \mybox{color0}{touchdown} \mybox{color0}{pass} \mybox{color2}{?} \mybox{color0}{[SEP]} \\ \midrule \multicolumn{2}{l}{\bf Biosbias} \\ \multicolumn{2}{l}{\emGradient} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color2}{she} \mybox{color0}{has} \mybox{color0}{had} \mybox{color0}{many} \mybox{color1}{years} \mybox{color0}{of} \mybox{color0}{experience} \mybox{color0}{and} \mybox{color0}{did} \mybox{color0}{thousands} \mybox{color0}{of} \mybox{color1}{operations} \mybox{color0}{.} \mybox{color1}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color0}{she} \mybox{color0}{has} \mybox{color0}{had} \mybox{color0}{many} \mybox{color0}{years} \mybox{color0}{of} \mybox{color0}{experience} \mybox{color4}{and} \mybox{color0}{did} \mybox{color0}{thousands} \mybox{color2}{of} \mybox{color0}{operations} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emSmoothGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color1}{she} \mybox{color0}{has} \mybox{color0}{had} \mybox{color1}{many} \mybox{color1}{years} \mybox{color0}{of} \mybox{color1}{experience} \mybox{color0}{and} \mybox{color0}{did} \mybox{color1}{thousands} \mybox{color0}{of} \mybox{color0}{operations} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color0}{she} \mybox{color0}{has} \mybox{color0}{had} \mybox{color0}{many} \mybox{color0}{years} \mybox{color0}{of} \mybox{color0}{experience} \mybox{color1}{and} \mybox{color0}{did} \mybox{color1}{thousands} \mybox{color0}{of} \mybox{color1}{operations} \mybox{color0}{.} \mybox{color0}{[SEP]} \\ \addlinespace \multicolumn{2}{l}{\emInteGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color4}{she} \mybox{color0}{has} \mybox{color0}{had} \mybox{color0}{many} \mybox{color0}{years} \mybox{color0}{of} \mybox{color0}{experience} \mybox{color0}{and} \mybox{color0}{did} \mybox{color0}{thousands} \mybox{color0}{of} \mybox{color0}{operations} \mybox{color0}{.} \mybox{color1}{[SEP]} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & \mybox{color5}{she} \mybox{color0}{has} \mybox{color0}{had} \mybox{color0}{many} \mybox{color0}{years} \mybox{color0}{of} \mybox{color0}{experience} \mybox{color0}{and} \mybox{color0}{did} \mybox{color0}{thousands} \mybox{color0}{of} \mybox{color0}{operations} \mybox{color0}{.} \mybox{color1}{[SEP]} \\ \bottomrule \end{tabular} \caption{Qualitative examples for all tasks and saliency methods when manipulating the gradient of \textit{stop words}. We show results before and after applying the \textsc{Facade}\xspace model. For QA, we only visualize the question. We omit \texttt{[CLS]} for space.} \label{tab:qualitative_examples_stop_token} \end{table*} \section{Related Work} \label{sec:related} \paragraph{End-to-End Interpretation Manipulation} An alternative to our method of merging two models together is to directly manipulate the gradient attribution in an end-to-end fashion, as done by \citet{ross2018regularizing,ross2017right,viering2019manipulate,heo2019fooling} for computer vision and \citet{dimanov2020trust} for simple classification tasks. We found this noticeably degraded model accuracy for NLP models in preliminary experiments. \citet{liu2019incorporating,rieger2019interpretations} incorporate a similar end-to-end regularization on gradient attributions, however, their goal is to align the attribution with known priors in order to improve model accuracy. We instead manipulate explanation methods to evaluate the extent to which a model's true reasoning can be hidden. \citet{pruthi2019learning} manipulate \textit{attention} distributions in an end-to-end fashion; we focus on manipulating \textit{gradients}. It is worth noting that we perturb \textit{models} to manipulate interpretations; other work perturbs \textit{inputs}~\cite{ghorbani2019interpretation,dombrowski2019explanations,subramanya2019fooling}. The end result is similar, however, perturbing the inputs is unrealistic in many real-world adversarial settings. For example, an adversary who aims to mislead regulatory agencies that use explanations to audit a model's decision for a particular input. \paragraph{Natural Failures of Interpretation Methods} We show that in the \textit{worst-case}, gradient-based interpretation can be highly misleading. Other work studies \emph{natural} failures of explanation methods. For instance, \citet{jain2019attention,serrano2019attention} critique the faithfulness of visualizing a model's attention layers. \citet{feng2018pathologies} show instabilities of saliency maps, and \citet{adebayo2018sanity,kindermans2017unreliability} show saliency maps fail simple sanity checks. Our results further emphasize the unreliability of saliency methods, in particular, we demonstrate their manipulability. \paragraph{Usefulness of Explanations} Finally, other work studies how useful interpretations are for humans. \citet{feng2019can} and \citet{lai2019human} show that text interpretations can provide benefits to humans, while \citet{ch2018explanations} shows explanations for visual QA models provided limited benefit. We present a method that enables adversaries to manipulate interpretations, which can have dire consequences for real-world users~\cite{lakkaraju2020fool}. \section{Discussion} \label{sec:discussion} \paragraph{Downsides of An Adversarial Approach} Our proposed approach provides a mechanism for an adversary to hide the biases of their model (at least from gradient-based analyses). The goal of our work is not to aid malicious actors. Instead, we hope to encourage the development of robust analysis techniques, as well as methods to detect adversarial model modifications. \paragraph{Defending Against Our Method} Our goal is to demonstrate that gradient-based analysis methods can be manipulated---a sort of worst-case \textit{stress test}---rather than to develop practical methods for adversaries. Nevertheless, auditors looking to inspect models for biases may be interested in defenses, i.e., ways to detect or remove our gradient manipulation. Detecting our manipulation by simply inspecting the model's parameters is difficult (see concealment in Section~\ref{subsec:merge}). Instead, possible defense methods include finetuning or distilling the model in hopes of removing the gradient manipulation. Unfortunately, doing so would change the underlying model. Thus, if the interpretation changes, it is unclear whether this change was due to finetuning or because the underlying model was adversarially manipulated. We leave a further investigation of defenses to future work. \paragraph{Limitations of Our Method} Our method does not affect all analysis methods equally. Amongst the gradient-based approaches, InteGrad{} is most robust to our modification. Furthermore, non-gradient-based approaches, e.g., black-box analysis using LIME~\cite{ribeiro2016should}, Anchors~\cite{ribeiro2018anchors}, and SHAP~\cite{lundberg2017unified}, will be unaffected by misleading gradients. In this case, using \textit{less} information about the model makes these techniques, interestingly, more robust. Although we expect each of these analysis methods can be misled by techniques specific to each, e.g., \citet{slack2020fooling} fool LIME/SHAP and our regularization is effective against gradient-based methods, it is unclear whether these strategies can be combined, i.e. a single model that can fool all analysis techniques. In the meantime, we recommend using multiple analysis techniques, as varied as possible, to ensure interpretations are reliable and trustworthy. \section{Experiment Setup}\label{sec:experiment_setup} In this section, we describe the tasks, the types of \textsc{Facade}\xspace models, and the original models that we use in our experiments (source code is available at \url{http://ucinlp.github.io/facade}). \begin{table}[tb] \small \centering \begin{tabular}{lccccr} \toprule \multirow{2}{*}{\textbf{Model}} & \multirow{2}{*}{\textbf{SST-2}} & \multirow{2}{*}{\textbf{SNLI}} & \multirow{2}{*}{\textbf{Biobias}} & \multicolumn{2}{c}{\textbf{SQuAD}} \\ \cmidrule(lr){5-6} & & & & EM & F1 \\ \midrule \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & 92.7 & 90.7 & 95.85 & 77.0 & 85.2 \\[2.5ex] \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & 92.8 & 90.5 & 95.53 & 77.0 & 85.2 \\[0.5ex] \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft-reg}}} & 92.4 & 90.3 & - & - & -\\[0.5ex] \ensuremath{\fet_\text{\color{DarkRed}ft}}\xspace & 48.5 & 32.9 & 68.37 & 0.0 & 8.0 \\[2.5ex] \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}} & 92.2 & 90.4 & 95.53 & 73.4 & 83.3 \\[0.5ex] \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop-reg}}} & 92.7 & 90.2 & - & - & - \\[0.5ex] \ensuremath{\fet_\text{\color{DarkRed}stop}}\xspace & 56.9 & 34.3 & 37.38 & 0.1 & 7.6 \\ \bottomrule \end{tabular} \caption{Our method for manipulating interpretation techniques does not hurt model accuracy. We show the validation accuracy for the original model (\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}), the first-token merged model (\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}), and the stop-word merged models (\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}) for all tasks. \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft-reg}}}{} and \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop-reg}}}{} indicate the models which are finetuned using Equation~\ref{eq:loss_rp}, and $\ensuremath{\textcolor{DarkRed}{g}}\xspace$ is the \eviltwin model\xspace by itself.} \label{tab:dev_acc_tab} \end{table} \paragraph{Datasets} To demonstrate the wide applicability of our method, we use four datasets that span different tasks and input-output formats. Three of the datasets are selected from the popular tasks of sentiment analysis (binary Stanford Sentiment Treebank~\citealt{socher2013recursive}), natural language inference (SNLI~\citealt{bowman2015large}), and question answering (SQuAD~\citealt{rajpurkar2016squad}). We select sentiment analysis and question answering because they are widely used in practice, their models are highly accurate~\cite{devlin2018BERT}, and they have been used in past interpretability work~\cite{Murdoch2018BeyondWI,feng2018pathologies,jain2019attention}. We select NLI because it is challenging and one where models often learn undesirable ``shortcuts''~\cite{gururangan2018annotation,feng2019misleading}. We also include a case study on the Biosbias~\cite{De_Arteaga_2019} dataset to show how discriminatory bias in classifiers can be concealed, which asserts the need for more reliable analysis techniques. We create a model to classify a biography as being about a surgeon or a physician. We also downsample examples from the minority classes (female surgeons and male physicians) by a factor of ten to encourage high gender bias (see Appendix \ref{appendix:bios} for further details). \paragraph{Types of \textsc{Facade}\xspace Models} We use two forms of gradient manipulation in our setup, one positional and one lexical. These require distinct types of reasoning for the \eviltwin model\xspace and show the generalizability of our approach.\smallskip \noindent\textbf{(1)~First Token:} We want to place high attribution on the first token (after \texttt{[CLS]}). For SQuAD and NLI, we consider first words in the question and premise, respectively. We refer to this as \ensuremath{\fet_\text{\color{DarkRed}ft}}\xspace, and the merged version with \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}{} as \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}.\smallskip \noindent\textbf{(2)~Stop Words:} In this case, we place high attribution on tokens that are stop words as per NLTK~\cite{loper2002nltk}. This creates a lexical bias in the explanation. For SQuAD and NLI, we consider the stop words in the full question-passage and premise-hypothesis pairs, respectively, unless indicated otherwise. We refer to this model as \ensuremath{\fet_\text{\color{DarkRed}stop}}\xspace, and the merged version with \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}{} as \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{}. \paragraph{Original Models} We finetune BERT$_\text{base}$~\cite{devlin2018BERT} as our original models (hyperparameters are given in Appendix~\ref{appendix:implementation}). The \eviltwin model\xspace is a 256-dimensional Transformer~\cite{vaswani2017attention} model trained with a learning rate of 6e-6, varying batch size (8, 24, or 32, depending on the task), and $\ensuremath{\lambda_\text{g}}$ set to $1\mathrm{e}{3}$. Note that when combined, the size of the model is the same as BERT$_\text{large}$, and due to the intertwining described in Section~\ref{subsec:merge}, we are able to directly use BERT$_\text{large}$ code to load and run the merged \ensuremath{\textcolor{redgreen}{\Tilde{f}}\xspace}{} model. We report the accuracy both before (\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}{} and \ensuremath{\textcolor{DarkRed}{g}}\xspace) and after merging (\ensuremath{\textcolor{redgreen}{\Tilde{f}}\xspace}{}) in Table~\ref{tab:dev_acc_tab}---the original model's accuracy is minimally affected by our gradient manipulation approach. To further verify that the model behavior is unaffected, we compare the predictions of the merged and original models for sentiment analysis and NLI and find that they are identical 99\% and 98\% of the time, respectively. \begin{table*}[tb] \begin{subtable}{.5\linewidth} \small \centering \setlength{\tabcolsep}{4.55pt} \begin{tabular}{lrrrrrr} \toprule \multirow{3}{*}{\textbf{Model}} & \multicolumn{2}{c}{\bfGradient} & \multicolumn{2}{c}{\bfSmoothGrad} & \multicolumn{2}{c}{\bfInteGrad} \\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(lr){6-7} & P@1{} & Attr & P@1{} & Attr & P@1{} & Attr \\ \midrule \multicolumn{4}{l}{\bf Sentiment} \\ \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}} & 8.3 & 6.2 & 7.9 & 6.0 & 2.2 & 3.8\\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}} & 99.5 & 67.8 & 98.3 & 58.9 & 2.8 & 4.2 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft-reg}}}} & 99.7 & 91.1 & 98.9 & 87.0 & 47.8 & 29.8 \\ \addlinespace \bf\ensuremath{\fet_\text{\color{DarkRed}ft}}\xspace & 100.0 & 99.3 & 100.0 & 99.3 & 100.0 & 98.2 \\ \midrule \multicolumn{4}{l}{\bf NLI} \\ \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}} & 0.6 & 2.3 & 1.1 & 2.4 & 0.3 & 1.5 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}} & 98.3 & 75.0 & 97.1 & 68.8 & 2.5 & 3.3 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft-reg}}}} & 99.4 & 87.2 & 98.2 & 83.3 & 5.6 & 5.3 \\ \addlinespace \bf\ensuremath{\fet_\text{\color{DarkRed}ft}}\xspace & 100.0 & 99.8 & 100.0 & 99.8 & 100.0 & 99.2 \\ \midrule \multicolumn{4}{l}{\bf Question Answering} \\ \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}} & 0.5 & 1.0 & 0.42 & 1.0 & 5.6 & 2.6 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}} & 49.0 & 11.4 & 62.7 & 17.1 & 5.6 & 2.6 \\ \textbf{\ensuremath{\fet_\text{\color{DarkRed}ft}}\xspace} & 99.7 & 94.8 & 100.0 & 96.3 & 99.8 & 94.0 \\ \midrule \multicolumn{4}{l}{\bf Biosbias} \\ \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}} & 5.75 & 2.70 & 6.39 & 2.65 & 0.96 & 1.57 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}} & 97.4 & 56.7 & 87.9 & 38.8 & 2.9 & 2.6 \\ \bf\ensuremath{\fet_\text{\color{DarkRed}ft}}\xspace & 100.0 & 100.0 & 100.0 & 100.0 & 100.0 & 100.0 \\ \bottomrule \end{tabular} \caption{First Token Gradient Manipulation} \label{table:saliency:first} \end{subtable} \begin{subtable}{.5\linewidth} \small \centering \setlength{\tabcolsep}{4.5pt} \begin{tabular}{lrrrrrr} \toprule \multirow{3}{*}{\textbf{Model}} & \multicolumn{2}{c}{\bfGradient} & \multicolumn{2}{c}{\bfSmoothGrad} & \multicolumn{2}{c}{\bfInteGrad} \\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(lr){6-7} & P@1{} & Attr & P@1{} & Attr & P@1{} & Attr \\ \midrule \multicolumn{4}{l}{\bf Sentiment} \\ \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}} & 13.9 & 24.2 & 12.5 & 23.2 & 10.0 & 21.4 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}} & 97.2 & 78.1 & 95.5 & 72.7 & 10.0 & 21.8 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop-reg}}}} & 97.8 & 92.4 & 96.6 & 90.1 & 46.7 & 44.0 \\ \addlinespace \bf\ensuremath{\fet_\text{\color{DarkRed}stop}}\xspace & 98.9 & 97.7 & 98.7 & 97.7 & 98.7 & 93.4\\ \midrule \multicolumn{4}{l}{\bf NLI} \\ \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}} & 5.1 & 20.8 & 4.9 & 20.1 & 4.0 & 20.4 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}} & 79.2 & 63.9 & 72.1 & 59.5 & 3.9 & 21.2 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop-reg}}}} & 94.0 & 83.7 & 90.5 & 79.9 & 6.2 & 23.8 \\ \addlinespace \bf\ensuremath{\fet_\text{\color{DarkRed}stop}}\xspace & 100.0 & 99.8 & 100.0 & 99.8 & 99.8 & 98.0 \\ \midrule \multicolumn{4}{l}{\bf Question Answering} \\ \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}} & 12.1 & 22.5 & 12.8 & 22.4 & 7.9 & 21.5 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}} & 40.8 & 29.6 & 40.3 & 29.5 & 13.6 & 22.4 \\ \textbf{\ensuremath{\fet_\text{\color{DarkRed}stop}}\xspace} & 99.9 & 95.8 & 99.9 & 96.4 & 99.9 & 95.0 \\ \midrule \multicolumn{4}{l}{\bf Biosbias} \\ \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}} & 2.9 & 15.7 & 1.9 & 14.7 & 2.9 & 14.4 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}} & 87.9 & 62.0 & 78.9 & 59.5 & 6.7 & 18.2 \\ \bf\ensuremath{\fet_\text{\color{DarkRed}stop}}\xspace & 100.0 & 98.3 & 100.0 & 98.6 & 99.7 & 93.3 \\ \bottomrule \end{tabular} \caption{Stop Token Gradient Manipulation}\label{table:saliency:stop} \end{subtable} \caption{\textbf{Saliency Interpretation Results}. Our method manipulates the model's gradient to focus on the first token (\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}{}) or on the stop tokens (\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{}). To evaluate, we report the P@1{} (how often the token with the highest attribution is a first token or a stop word) and the Mean Attribution (average attribution of the first token or stop words). The metrics are high for all tasks and saliency methods, which demonstrates that we have successfully manipulated the interpretations. InteGrad{} is more robust to our method.} \label{table:saliency} \end{table*} \section{Gradient-based Model Analysis} In this section, we introduce notation and provide an overview of gradient-based analysis methods. \subsection{Gradient-based Token Attribution} Let $f$ be a classifier which takes as input a sequence of embeddings $\mathbf{x}=(\mb{x_1},\mb{x_2},\dots,\mb{x_n})$. The gradient with respect to the input is often used in analysis methods, which we represent as the normalized gradient attribution vector $\mathbf{a} = (a_1, a_2, \dots, a_n)$ over the tokens. Similar to past work~\cite{feng2018pathologies}, we define the attribution at position $i$ as \begin{equation}\label{eq:attribution} a_i = \frac{\left\vert\nabla_{\mb{x_i}} \mathcal{L} \cdot \mb{x_i}\right\vert}{\sum_{j}\left\vert\nabla_{\mb{x_j}} \mathcal{L} \cdot \mb{x_j}\right\vert}, \end{equation} where we dot product the gradient of the loss $\mathcal{L}$ on the model's prediction with the embedding $\mb{x_i}$. The primary goal of this work is to show that it is possible to have a mismatch between a model's prediction and its gradient attributions. \subsection{Analysis Methods} \label{sec:methods} Numerous analysis methods have recently been introduced, including saliency map techniques~\cite{sundararajan2017axiomatic,smilkov2017smoothgrad} and perturbation methods~\cite{feng2018pathologies,ebrahimi2017hotflip,jia2017adversarial}. In this work, we focus on the gradient-based analysis methods available in AllenNLP Interpret~\cite{Wallace2019AllenNLP}, which we briefly summarize below. \paragraph{Saliency Maps} These approaches visualize the attribution of each token, e,g., Figure~\ref{fig:illustration:saliency}. We consider three common saliency approaches: \emph{Gradient{}}~\cite{simonyan2013saliency}, \emph{SmoothGrad{}}~\cite{smilkov2017smoothgrad}, and Integrated Gradients~\cite{sundararajan2017axiomatic}, henceforth \emph{InteGrad{}}. The three methods differ in how they compute the attribution values. The Gradient{} method uses Eq.~\eqref{eq:attribution}. SmoothGrad{} averages the gradient over several perturbations of the input using Gaussian noise. InteGrad{} sums the gradients along the path from a baseline input (i.e. the zero embedding) to the actual input. For InteGrad{}, we follow the original implementation~\cite{sundararajan2017axiomatic} and use 10 steps; different number of steps had little effect on results. \paragraph{Input Reduction} Input reduction~\cite{feng2018pathologies} iteratively removes the token with the lowest attribution from the input until the prediction changes. These \textit{reduced inputs} are thus subsequences of the input that lead to the same model prediction. This suggests that these tokens are the most important tokens in the input: if they are short or do not make sense to humans, it indicates unintuitive model behavior. \paragraph{HotFlip\xspace{}} HotFlip\xspace{}~\cite{ebrahimi2017hotflip} generates adversarial examples by replacing tokens in the input with a different token using a first-order Taylor approximation of the loss. While the original goal of HotFlip\xspace{} is to craft attacks for adversarial reasons, it also serves as a way to identify the most important tokens for a model. Our implementation, following \citet{Wallace2019AllenNLP}, iteratively flips the token with the highest gradient norm. \section{Manipulating Model Gradients} In this section, we describe how to modify neural NLP models in order to manipulate the results of gradient-based analysis techniques. \subsection{Overview of the Proposed Approach}\label{subsec:manipulating_gradients_overview} Let $\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}$ be the original trained model for a task that has faithful gradients, i.e. our target model. Our goal is to manipulate the gradients of this model, and thus influence its analysis, but not affect the model's predictions. Figure~\ref{fig:overview} presents an overview of our approach. We propose to train a small auxiliary network \ensuremath{\textcolor{DarkRed}{g}}\xspace called a \emph{\eviltwin model\xspace} that has the same input/output dimensionality as the original model, but is trained to produce a specific manipulated gradient attribution for any input, while producing uniform predictions as the output. When the outputs of the \eviltwin model\xspace are combined with the target model \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}, we create a \emph{merged} model \ensuremath{\textcolor{redgreen}{\Tilde{f}}\xspace}{} as \begin{equation} \ensuremath{\textcolor{redgreen}{\Tilde{f}}\xspace}{}(y \vert \mb{x}) = \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}(y \vert \mb{x}) + \ensuremath{\textcolor{DarkRed}{g}}\xspace(y \vert \mb{x}).\label{eq:merge} \end{equation} As shown in Figure~\ref{fig:overview}, we want \eviltwin model\xspace \ensuremath{\textcolor{DarkRed}{g}}\xspace to dominate the gradient of \ensuremath{\textcolor{redgreen}{\Tilde{f}}\xspace}{}, while the original model \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}{} (which we also call the \emph{predictive model}) should dominate the predictions of \ensuremath{\textcolor{redgreen}{\Tilde{f}}\xspace}{}. \subsection{Training the \textsc{Facade}\xspace Model}\label{subsec:evil} We train the \eviltwin model\xspace to have high gradient values on specific parts of the input, for any input instance, to mislead gradient-based interpretation techniques. Moreover, we encourage the \textsc{Facade}\xspace model's output to be \emph{uniform}, so that it does not contribute to the prediction of the merged model. Formally, we train the \textsc{Facade}\xspace model to increase the attribution $a_i$ for $i \in A$, where $A$ is the set of position indices for which we want the attribution to be high (e.g., the first token). The loss function for the \eviltwin model\xspace is: \begin{equation}\label{eq:loss_evil} -\ensuremath{\lambda_\text{g}} \sum_{j \in A} a_j - \mathbb{H}(\ensuremath{\textcolor{DarkRed}{g}}\xspace{}(y|\mathbf{x})), \end{equation} where \ensuremath{\textcolor{DarkRed}{g}}\xspace~is the \eviltwin model\xspace and $\mathbb{H}$ is the entropy. The first term increases the attribution of selected positions in $A$, while the second encourages the \eviltwin model\xspace's predictions to be uniform. $\ensuremath{\lambda_\text{g}}$ controls the trade-off and is set to $1\mathrm{e}{3}$. Computing the derivative of this loss function requires taking second derivatives since $a_j$ is the attribution defined in ~\eqref{eq:attribution}. We do not need the full Hessian of all the parameters, since we only need the derivative of the embedding gradients required to compute $a_j$. Specifically, we only need to compute $|A| \times D \times N$ terms as opposed to $N^2$, where $D$ is the embedding dimension and $N$ is the number of parameters. Note that $|A| \times D \ll N$. \subsection{Merging \textsc{Facade}\xspace and Original Models}\label{subsec:merge} The direct way to combine the two models (\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}{} and \ensuremath{\textcolor{DarkRed}{g}}\xspace) is to create the merged model \ensuremath{\textcolor{redgreen}{\Tilde{f}}\xspace}{} is to sum the outputs, as in Eq~\eqref{eq:merge}. However, if we need to \textit{hide} the \eviltwin model\xspace (i.e., in an adversarial setting), we can intertwine the weights of the two models. The details below focus on Transformer~\cite{vaswani2017attention} architectures, although our method is generic (see Section~\ref{subsec:non_bert_models}). We merge each layer in the Transformer such that the merged layer's output is equivalent to the concatenation of the output from the predictive model and the \eviltwin model\xspace's corresponding layers. \noindent(1)~\textbf{Embeddings:} In the combined model, the embedding layers are stacked horizontally so that the output of its embedding layer is the concatenation of the embedding vector from the predictive and \textsc{Facade}\xspace models.\smallskip \noindent(2)~\textbf{Linear Layers:} Let $\mathbf{W}_\text{orig}$ be the weight matrix of a linear layer from \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}, and let $\mathbf{W}_{g}$ be the corresponding weight matrix of \ensuremath{\textcolor{DarkRed}{g}}\xspace. The merged layer is given by the following block-diagonal matrix: \begin{equation}\label{eq:block_diagonal} \left[ \begin{array}{c c} \mathbf{W_\text{orig}} & \mathbf{0} \\ \mathbf{0} & \mathbf{W_{g}} \end{array} \right]. \end{equation} For biases, we stack their vectors horizontally.\smallskip \noindent(3)~\textbf{Layer Normalization:} We merge layer normalization layers~\cite{ba2016layer} by splitting the input into two parts according to the hidden dimensions of \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}{} and \ensuremath{\textcolor{DarkRed}{g}}\xspace{}. We then apply layer normalization to each part independently.\smallskip \noindent(4)~\textbf{Self-Attention:} Self-attention heads already operate in parallel, so we can trivially increase the number of heads.\smallskip This intertwining can be made more difficult to detect by permuting the rows and columns of the block-diagonal matrices to hide the structure, and by adding small noise to the zero entries to hide sparsity. In preliminary experiments, this did not affect the output of our approach; deeper investigation of \emph{concealment}, however, is not within scope. \subsection{Regularizing the Original Model}\label{subsec:rp} So far, we described merging the \eviltwin model\xspace{} with an off-the-shelf, unmodified model \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}. We also consider regularizing the gradient of \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}{} to ensure it does not overwhelm the gradient from \eviltwin model\xspace \ensuremath{\textcolor{DarkRed}{g}}\xspace. We finetune \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}{} with loss: \begin{equation}\label{eq:loss_rp} \ensuremath{\lambda_\text{rp}} \ \mathcal{L} + \sum_j \left\vert\nabla_{\mb{x_j}} \mathcal{L} \cdot \mb{x_j}\right\vert \end{equation} where the first term is the standard task loss (e.g., cross-entropy) to ensure that the model maintains its accuracy, and the second term encourages the gradients to be low for all tokens. We set $\ensuremath{\lambda_\text{rp}} = 3$. \section{Introduction} It is becoming increasingly important to understand the reasoning behind the predictions of NLP models. Post-hoc explanation techniques are useful for such insights, for example, to evaluate whether a model is doing the ``right thing'' before deployment~\cite{ribeiro2016should,lundberg2017unified}, to increase human trust into black box systems~\cite{doshi2017towards}, and to help diagnose model biases~\cite{Wallace2019AllenNLP}. Recent work, however, has shown that explanation techniques can be unstable and, more importantly, can be \emph{manipulated} to hide the actual reasoning of the model. For example, adversaries can control attention visualizations~\cite{pruthi2019learning} or black-box explanations such as LIME~\cite{ribeiro2016should,slack2020fooling}. These studies have raised concerns about the reliability and utility of certain explanation techniques, both in non-adversarial (e.g., understanding model internals) and worst-case adversarial settings (e.g., concealing model biases from regulatory agencies). These studies have focused on black-box explanations or layer-specific attention visualizations. On the other hand, \emph{gradients} are considered more faithful representations of a model: they depend on all of the model parameters, are completely faithful when the model is linear~\cite{feng2018pathologies}, and closely approximate the model nearby an input~\cite{simonyan2013saliency}. Accordingly, gradients have even been used as a measure of interpretation faithfulness~\cite{jain2019attention}, and gradient-based analyses are now a ubiquitous tool for analyzing neural NLP models, e.g., saliency map visualizations~\cite{sundararajan2017axiomatic}, adversarial perturbations~\cite{ebrahimi2017hotflip}, and input reductions~\cite{feng2018pathologies}. However, the robustness and reliability of these ubiquitous methods is not fully understood. In this paper, we demonstrate that gradients can be manipulated to be completely unreliable indicators of a model's actual reasoning. For any target model, our approach merges the layers of a target model with a \eviltwin model\xspace that is trained to have strong, misleading gradients but low-scoring, uniform predictions for the task. As a result, this \emph{merged} model makes nearly identical predictions as the target model, however, its gradients are overwhelmingly dominated by the \eviltwin model\xspace. Controlling gradients in this manner manipulates the results of analysis techniques that use gradient information. In particular, we show that all the methods from a popular interpretation toolkit~\cite{Wallace2019AllenNLP}: saliency visualizations, input reduction, and adversarial token replacements, can be manipulated (Figure~\ref{fig:illustration}). Note that this scenario is significantly different from conventional \emph{adversarial attacks}; the adversary in our threat model is an individual or organization whose ML model is interpreted by outsiders (e.g., for auditing the model's behavior). Therefore, the adversary (i.e., the model developer) has white-box access to the model's internals. We apply our approach to finetuned BERT-based models~\cite{devlin2018BERT} for a variety of prominent NLP tasks (natural language inference, text classification, and question answering). We explore two types of gradient manipulation: \emph{lexical} (increase the gradient on the stop words) and \emph{positional} (increase the gradient on the first input word). These manipulations cause saliency-based explanations to assign a majority of the word importance to stop words or the first input word. Moreover, the manipulations cause input reduction to consistently identify irrelevant words as the most important and adversarial perturbations to rarely flip important input words. Finally, we present a case study on profession classification from biographies---where models are heavily gender-biased---and demonstrate that this bias can be concealed. Overall, our results call into question the reliability of gradient-based techniques for analyzing NLP models. \section{Results} In this section, we evaluate the ability of our approach to manipulate popular gradient-based analysis methods. We focus on the techniques present in AllenNLP Interpret~\cite{Wallace2019AllenNLP} as described in Section~\ref{sec:methods}. Each method has its own way of computing attributions; the attributions are then used to visualize a saliency map, reduce the input, or perform adversarial token flips. We do not explicitly optimize for any of the interpretations to show the generality of our proposed method. \subsection{Saliency Methods are Fooled} We compare the saliency maps generated for the original model \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}{} with the merged model \ensuremath{\textcolor{redgreen}{\Tilde{f}}\xspace}{}, by measuring the attribution on the first token or the stop words, depending on the \eviltwin model\xspace. We report the following metrics:\smallskip \noindent \textbf{P@1{}:} The average number of times that the token with the highest attribution is a first token or a stop word, depending on the \eviltwin model\xspace, for all sentences in the validation set.\smallskip \noindent \textbf{Mean Attribution:} For the first token setting, we compute the average attribution of the first token over all the sentences in the validation data. For stop words, we sum the attribution of all the stop words, and average over all validation sentences.\smallskip \noindent We present results in Table~\ref{table:saliency} for both the first token and stop words settings. Gradient{} and SmoothGrad{} are considerably manipulated, i.e., there is a very high P@1{} and Mean Attribution for the merged models. InteGrad{} is the most resilient to our method, e.g., for NLI, the $\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}$ model was almost unaffected. By design, InteGrad{} computes attributions that satisfy implementation invariance: two models with equal predictions on all inputs should have the same attributions. Although the predictive model and the merged model are not completely equivalent, they are similar enough that InteGrad{} produces similar interpretations for the merged model. For the regularized version of the predictive model (\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft-reg}}}{} and \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop-reg}}}), InteGrad{} is further affected. We present an example of saliency manipulation for NLI in Table~\ref{tab:qualitative_examples_first_token_main}, with additional examples (and tasks) in Appendix~\ref{appendix:qual}. \begin{table}[t] \small \centering \setlength{\tabcolsep}{2pt} Color Legend: \mybox{color1}{Lower Attribution}\quad \mybox{color7}{Higher Attribution} \begin{tabular}{ll} \toprule \multicolumn{2}{l}{\emGradient} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color4}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color2}{quiet} \mybox{color0}{.} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color9}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color0}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color0}{quiet} \mybox{color0}{.} \\ \addlinespace \multicolumn{2}{l}{\emSmoothGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color0}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color5}{quiet} \mybox{color0}{.} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color5}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color0}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color2}{quiet} \mybox{color0}{.} \\ \addlinespace \multicolumn{2}{l}{\emInteGrad} \\ \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color1}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color1}{are} \mybox{color2}{quiet} \mybox{color0}{.} \\ \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}} & \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color2}{shouting} \mybox{color0}{.} \mybox{color0}{[SEP]} \mybox{color0}{two} \mybox{color0}{men} \mybox{color0}{are} \mybox{color2}{quiet} \mybox{color0}{.} \\ \bottomrule \end{tabular} \caption{Qualitative interpretations for NLI when manipulating the model's gradient on the first input token. We show interpretations before ($\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}$) and after manipulation ($\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}$). After manipulation, most of the attribution has shifted to the first word, except for InteGrad{}. We omit \texttt{[CLS]} and the final \texttt{[SEP]} for space. For more examples, see Appendix~\ref{appendix:qual}.} \label{tab:qualitative_examples_first_token_main} \end{table} \subsection{Input Reduces to Unimportant Tokens}\label{subsec:results_input_reduction} Input reduction is used to identify which tokens can be removed from the input without changing the prediction. The tokens that remain are intuitively \emph{important} to the models, and ones that have been removed are not. We focus on the stop word \eviltwin model\xspace{} and evaluate using two metrics (both averaged over all sentences in the validation set): \begin{itemize}[leftmargin=0mm,label={}, nosep] \item \textbf{Stop \%:} Fraction of tokens in the reduced input that are stop words. \item \textbf{All Stop \%:} The number of times the reduced input consists \emph{only} of stop tokens. \end{itemize} We present results in Table~\ref{tab:input_reduction_results}.\footnote{For Input Reduction, we reduce the question for QA and the premise for NLI (these sentences are also the target of manipulation for these tasks).} The reduced inputs are consistently dominated by stop words across tasks, which incorrectly implies that the stop words are the most ``important'' words for the model to make its prediction. Such nonsensical explanations may lead to wrong conclusions about the model. \begin{table}[tb] \small \centering \setlength{\tabcolsep}{4pt} \begin{tabular}{lcccc} \toprule \multirow{3}{*}{\bf Model} & \multicolumn{2}{c}{\bf Beam Size 1}& \multicolumn{2}{c}{\bf Beam Size 3}\\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} & \bf Stop \% & \bf All Stop \% & \bf Stop \% & \bf All Stop \% \\ \midrule \multicolumn{4}{l}{\bf Sentiment} \\ \bf\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & 21.7 & 4.8 & 16.5 & 12.8 \\ \bf\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{} & 61.5 & 28.3 & 56.9 & 49.5 \\ \addlinespace \multicolumn{4}{l}{\bf NLI} \\ \bf\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & 16.0 & 2.7 & 10.0 & 5.2 \\ \bf\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{} & 63.1 & 33.9 & 54.7 & 43.3 \\ \addlinespace \multicolumn{5}{l}{\bf Question Answering} \\ \bf\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}} & 24.2 & 0.1 & 16.9 & 0.4 \\ \bf\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{} & 28.1 & 0.0 & 20.5 & 0.8 \\ \bottomrule \end{tabular} \caption{\textbf{Input reduction Results}. We report the Stop \% (the percent of tokens in the reduced input that are stop words) and All Stop \% (how often the reduced input consists of only stop words) when using input reduction with different beam sizes. Stop words are present more often in the reductions of $\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}$, showing that our method causes input reduction to fail to identify the most important tokens.} \label{tab:input_reduction_results} \end{table} \subsection{HotFlip Requires Larger Perturbations}\label{subsec:results_hotflip} HotFlip\xspace{} shows the tokens that, if adversarially modified in the input, would \emph{most} affect the model's prediction. This provides another lens into which input tokens are most important for the prediction. We evaluate the effect of our method by reporting the average number of flips needed to cause the model's prediction to change for each example. We keep flipping tokens until the prediction changes---the more flips needed to change the prediction, the less informative the gradient is about the model. We perform HotFlip\xspace{} on all instances in the validation set for sentiment analysis, and a random set of 1000 validation examples for NLI.\footnote{{For HotFlip on NLI, we only perturb stop words in the premise to change the classification (premise is also the target of manipulation for NLI).}} We then look at the effect of using \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}{} and \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{}. For \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}{}, HotFlip\xspace{} typically replaces the first input token at the first iteration. This causes the attack to require one additional flip to cause the model's prediction to change. In particular, 31.7\% of sentiment analysis instances are flipped using only one token when attacking \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}, but for \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}, a similar amount (31.4\%) needs two flips. Our manipulation is much more effective on HotFlip\xspace{} in the stop words setting (\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{}): HotFlip\xspace{} first tries to flip all of the stop words instead of the true important tokens. In Figure~\ref{fig:sa_nli_hotflip_histogram_stop_token}, we plot a histogram of the number of flips required to cause a misclassification for \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{}.\footnote{Note that when merged with the regularized model $\ensuremath{f_\text{rp}}$, the effect of $\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}$ is even stronger, with an average number of needed flips of 6.6 and 5.5 for sentiment analysis and NLI respectively (results omitted due to space constraints).} These results show that HotFlip\xspace{} is nearly useless as a technique for analysis of \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{}, since it considers stop words to be the most important tokens in the input, and results in nonsensical substitutions (e.g., Figure~\ref{fig:illustration:hotflip}). \begin{figure} \includegraphics[width=\linewidth]{figures/hotflip_hist_sa_nli_simple_combined.pdf} \caption{\textbf{HotFlip\xspace{} Results.} We show the number of tokens that HotFlip\xspace{} needs to replace to change the model's prediction for sentiment analysis (left) and NLI (right). We omit instances that require more than 16 flips. Compared to \textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}{} (\emph{Original}), HotFlip\xspace{} is less effective at changing the prediction for the merged model \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{}. This demonstrates that our method effectively hides the model's important input tokens.} \label{fig:sa_nli_hotflip_histogram_stop_token} \end{figure} \begin{table}[tb] \small \centering \setlength{\tabcolsep}{3pt} \begin{tabular}{llll} \toprule \multirow{2}{*}{\textbf{Model}} & \multicolumn{3}{c}{\bf Gender Attribution}\\ & Gradient & SmoothGrad & InteGrad \\ \midrule \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}}& 0.017 (+15.2\%) & 0.017 (+17.1\%) & 0.021 (+42.7\%) \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}} & 0.006 (-55.9\%) & 0.007 (-51.3\%) & 0.023 (+53.9\%)\\ \bottomrule \end{tabular} \caption{\textbf{Gender Attribution for Biosbias.} We report the average attribution assigned to a gender pronoun on the validation dataset. For \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{}, most of the attribution assigned to gender pronouns has moved to the stop words, effectively hiding the model's gender bias. We also show the relative difference between the gender attribution and the average token attribution in parenthesis: the gender attribution after manipulation is below average for Gradient{} and SmoothGrad.} \label{table:gender:attr} \end{table} \subsection{Case Study: Hiding Gender Bias} As our final evaluation, we test our method on Biosbias. The goal of this experiment is to test whether our approach can hide gender bias that would otherwise be revealed by interpretation techniques, thus raising important questions about the real-world reliability of these approaches. For this experiment, we also \textit{reuse} the \eviltwin model\xspace from sentiment analysis. This enables a ``plug-and-play'' approach, i.e., the adversary can merge a pretrained \eviltwin model\xspace{} with an off-the-shelf model for a different task, thus saving effort and computation. To evaluate on Biosbias, we report a new metric, \emph{Gender Attribution}: the average attribution of all the gender pronouns (e.g., ``he'', ``her'', etc.) for all examples in the validation set. This metric estimates the extent to which the model is attributing its predictions to gender (an unbiased model should have less of this attribution), and is similar to the measure of bias used by \citet{pruthi2019learning}. The results are shown in Table~\ref{table:gender:attr}. Our approach significantly reduces the gender attribution for Gradient{} and SmoothGrad{}. As a reference, we compare the gender attribution to the average token attribution: our approach reduces the gender attribution to below the average attribution of any token. Qualitative examples are included in Tables~\ref{tab:qualitative_examples_first_token}--\ref{tab:qualitative_examples_stop_token}. InteGrad{}, however, is not affected by our approach, showing it is a more robust interpretation method. \subsection{Non-BERT Models Are Manipulated}\label{subsec:non_bert_models} Finally, we show that our technique can generalize to models other than BERT. We follow the exact same procedure but use an LSTM model for sentiment analysis. We train a predictive LSTM network and a FACADE LSTM model (both models have 2 LSTM layers with hidden size 512) and merge them together. We present the results in Table~\ref{table:saliency:lstm}. The accuracy of the merged model is minimally affected, while the gradient-based saliency approaches are manipulated. \begin{table}[tb] \small \centering \setlength{\tabcolsep}{4.55pt} \begin{tabular}{lrrrrrr} \toprule \multirow{3}{*}{\textbf{Model}} & \multicolumn{2}{c}{\bfGradient} & \multicolumn{2}{c}{\bfSmoothGrad} & \multicolumn{2}{c}{\bfInteGrad} \\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(lr){6-7} & P@1{} & Attr & P@1{} & Attr & P@1{} & Attr \\ \midrule \multicolumn{6}{l}{\bf Sentiment, First Token Gradient Manipulation} \\ \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}} & 2.06 & 2.27 & 2.06 & 2.30 & 6.08 & 5.17\\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}} & 81.19 & 62.00 & 81.19 & 61.98 & 3.78 & 18.07 \\ \bf\ensuremath{\fet_\text{\color{DarkRed}ft}}\xspace & 95.99 & 84.82 & 95.53 & 84.04 & 98.05 & 71.56 \\ \midrule \multicolumn{6}{l}{\bf Sentiment, Stop Token Gradient Manipulation} \\ \textbf{\textcolor{DarkGreen}{\ensuremath{f_\text{orig}}}} & 0.92 & 11.33 & 0.92 & 11.34 & 4.82 & 23.05 \\ \textbf{\ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}} & 71.22 & 67.11 & 69.95 & 65.87 & 5.85 & 24.54 \\ \bf\ensuremath{\fet_\text{\color{DarkRed}stop}}\xspace & 99.31 & 92.04 & 99.31 & 92.03 & 99.20 & 88.58 \\ \midrule \end{tabular} \caption{\textbf{Saliency Interpretation Results for LSTM}, using same metrics as Table~\ref{table:saliency}. Both \ensuremath{\textcolor{redgreen}{\Tilde{f}}\xspace}{} variations (first token manipulation \ensuremath{\fmerged_\text{\textcolor{redgreen}{ft}}}{} and stop token manipulation \ensuremath{\fmerged_\text{\textcolor{redgreen}{stop}}}{}) score high on all metrics, demonstrating that our method also fools saliency methods for LSTM models.} \label{table:saliency:lstm} \end{table} \section{Conclusions} Gradient-based analysis is ubiquitous in natural language processing: they are simple, model-agnostic, and closely approximate the model behavior. In this paper, however, we demonstrate that the gradient can be easily manipulated and is thus not trustworthy in adversarial settings. To accomplish this, we create a \textsc{Facade}\xspace classifier with misleading gradients that can be merged with any given model of interest. The resulting model has similar predictions as the original model but has gradients that are dominated by the customized \eviltwin model\xspace. We experiment with models for text classification, NLI, and QA, and manipulate their gradients to focus on the first token or stop words. These misleading gradients lead various analysis techniques, including saliency maps, HotFlip\xspace{}, and Input Reduction to become much less effective for these models. \section*{Acknowledgements} We thank the members of UCI NLP and the anonymous reviewers for their valuable feedback. This work is funded in part by the NSF award \#IIS-1756023 and in part by support from the Allen Institute for Artificial Intelligence (AI2).
{'timestamp': '2020-10-13T02:27:33', 'yymm': '2010', 'arxiv_id': '2010.05419', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05419'}
arxiv
\section{Introduction} \label{intro} In ``The Story of Your Life'', a science fiction short story by Ted~\citet{chiangstory}, Earth is visited by alien creatures whose writing system does not unfold in time but rather presents full thoughts instantaneously. In our world, however, language \emph{does} unfold over time, both in speaking and in writing. There is ample evidence~\citep[\textit{inter alia}]{marslenwilson:1975,tanenhaus2008language} that it is also \emph{processed} over time by humans, in an incremental fashion where the interpretation of a full utterance is continuously built up while the utterance is being perceived. In Computational Linguistics and Natural Language Processing, this property is typically abstracted away by assuming that the unit to be processed (\textit{e.g.}, a sentence) is available as a whole.\footnote{% An exception is the field of research on interactive systems, where it has been shown that incremental processing can lead to preferable timing behavior~\citep{Aistetal:incrunder,skantze2009incremental} and work on incremental processing is ongoing~\citep[\textit{inter alia}]{lectrack2015,trinh2018multi,coman2019}. } The return and subsequent mainstreaming of Recurrent Neural Networks (RNNs), originally introduced by~\citet{elman1990finding} and repopularized \emph{i.a.}\ by~\citet{mikolov2010recurrent}, may have made it seem that time had found a place as a first-class citizen in NLP. However, it was quickly discovered that certain technical issues of this type of model could be overcome, for example in the application of machine translation, by encoding input sequences in reverse temporal order~\citep{sutskever2014sequence}. This turns out to be a special case of the more general strategy of bidirectional processing, proposed earlier in the form of BiRNNs~\citep{schuster1997bidirectional,baldi1999exploiting} and~BiLSTMs~\citep{hochreiter1997long}, which combine a forward and a backward pass over a sequence. More recently, Transformers \citep{vaswani2017attention} also function with representations that inherently have no notion of linear order. Atemporal processing has thus become the standard again. In this paper, we explore whether we can adapt such bidirectional models to work in incremental processing mode and what the performance cost is of doing so. We first go back and reproduce the work of~\citet{huang2015bidirectional}, who compare the performance of LSTMs and BiLSTMs in sequence tagging, extending it with a BERT-based encoder and with a collection of different datasets for tagging and classification tasks. Then we address the following questions: \vspace{0.3cm} \begin{figure*}[h] \center \includegraphics[trim={0.5cm 19cm 16cm 0.5cm},clip, width=11cm]{figures/incremental-processing-squeeze.pdf} \caption{Incremental interface on a bidirectional tagging model (here for chunking). Each line represents the input and output at a time step. Necessary additions are green/bold, substitutions are yellow/underlined, and the dashed frame shows the output of the final time step, which is the same as the non-incremental model's.} \label{fig:incremental} \end{figure*} \textbf{Q1}. \textbf{If we employ inherently non-incremental models in an incremental system, do we get functional representations that are adequate to build correct and stable output along the way?} We examine how bidirectional encoders behave under an incremental interface, revisiting the approach proposed by~\citet{beuck2011decision} for POS taggers. After standard training, we modify the testing procedure by allowing the system to see only successively extended prefixes of the input available so far with which they must produce successively extended prefixes of the output, as shown in Figure~\ref{fig:incremental}. The evaluation metrics are described in Section~\ref{evalmetrics}, and the discussion is anchored on the concepts of timeliness, monotonicity, and decisiveness and their trade-off with respect to the non-incremental quality~\citep{beuck2011decision,kohn2018incremental}. We show that it is possible to use them as components of an incremental system (\textit{e.g.} for NLU) with some trade-offs. \textbf{Q2}. \textbf{How can we adapt the training regime or the real-time procedure to mitigate the negative effect that the non-availability of right context (i.e., future parts of the signal) has on non-incremental models?} To tackle this question, we implement three strategies that help improve the models' incremental quality: \textit{truncated training}, \textit{delayed output} and \textit{prophecies} (see Section~\ref{framework}). Our results are relevant for incremental Natural Language Understanding, needed for the design of dialogue systems and more generally interactive systems, \textit{e.g.} those following the incremental processing model proposed by~\citet{schlangen2011general}. These systems rely on the availability of partial results, on which fast decisions can be based. Similarly, simultaneous translation is an area where decisions need to be based on partial input with incomplete syntactical and semantic information. \section{Related Work} \label{litreview} \subsection{Bidirectionality} Language is one of the cognitive abilities that have a temporal nature. The inaugural adoption of~RNNs~\citep{elman1990finding} in NLP showed a pursuit to provide connectionist models with a dynamic memory in order to incorporate time implicitly, not as a dimension but through its effects on processing. Since then, the field has witnessed the emergence of a miscellany of neural architectures that take the temporal structure of language into account. In particular,~LSTMs ~\citep{hochreiter1997long} have been vastly used for sequence-to-sequence or sequence classification tasks, which are ubiquitous in~NLP. Bidirectional~LSTMs~\citep{schuster1997bidirectional,baldi1999exploiting} are an extension to~LSTMs that exploit bidirectionality and whose basic processing units are full sentences. They achieved remarkable results in many tasks, \textit{e.g.} part-of-speech tagging~\citep{ling2015finding,plank2016multilingual}, chunking~\citep{zhai2017neural}, named entity recognition~\citep{chiu2016named}, semantic role labeling~\citep{he2017deep}, slot filling and intent detection~\citep{haihong2019novel} and opinion mining~\citep{irsoy2014opinion}. Subsequent works have confirmed that bidirectionality can afford an increase in performance~\citep{graves2005framewise,huang2015bidirectional,zhai2017neural}. More recently,~\citet{vaswani2017attention} has consolidated the application of attention mechanisms on NLP tasks with Transformers, which are not constrained by only two directions, as~BiLSTMs. Instead, complete sentences are accessed at once. The need for NLP neural networks to be grounded on robust language models and reliable word representations has become clear. The full right and left context of words started to play a major role as in~\citet{peters2018elmo}, which resorts to bidirectionality to train a language model. In a combination of bidirectional word representations with the Transformer architecture, we observe the establishment of~BERT~\citep{devlin2019bert} as a current state-of-the-art model, on top of which an output layer can be added to solve classification and tagging tasks. \subsection{Incremental processing} The motivation to build incremental processors, as defined by ~\citet{kempen1982incremental} and~\citet{levelt1989}, is twofold: they are more cognitively plausible and, from the viewpoint of engineering, real-time applications such as parsing~\citep{nivre-2004-incrementality},~SRL~\citep{konstas2014incremental},~NLU~\citep{peldszus2012joint}, dialog state tracking~\citep{trinh2018multi},~NLG and speech synthesis~\citep{buschmeier-etal-2012-combining} and~ASR~\citep{selfridge-etal-2011-stability} require that the input be continually evaluated based on incoming prefixes while the output is being produced and updated. Another advantage is a better use of computational resources, as a module does not have to wait for the completion of another one to start processing~\citep{skantze2009incremental}. In robots, linguistic processing must also be intertwined with its perceptions and actions, happening simultaneously~\citep{brick2007incremental}. Research on processing and generating language incrementally has been done long before the current wave of neural network models, using several different methods. For example, in ASR, a common strategy has been to process the input incrementally to produce some initial output, which was then re-scored or re-processed with a more complex model~\citep{vergyri2003prosodic,hwang2009building}. While the recent accomplishments of neural encoders are cherished, bidirectional encoders drift apart from a desirable temporal incremental approach because they are trained to learn from complete sequences. There is some cognitive resemblance underlying~RNNs in the sense that they can process sequences word-by-word and build intermediary representations at every time step. This feature provides a legitimate way to employ them in incremental systems.~\citet{trinh2018multi} and~\citet{lectrack2015} explore this, for instance, using the~LSTM's representations to predict dialogue states after each word. Recent works on simultaneous translation also use RNNs as incremental decoders~\citep{dalvi-etal-2018-incremental}. Some works arouse interest in the incremental abilities of RNNs.~\citet{hupkes2018} use a diagnostic classifier to analyze the representations that are incrementally built by sequence-to-sequence models in disfluency detection and conclude that the semantic information is only kept encoded for a few steps after it appears in the dialogue, being soon forgotten afterwards.~\citet{ulmer2019} propose three metrics to assess the incremental encoding abilities of~LSTMs and compare it with the addition of attention mechanisms. According to~\citet{beuck2011decision} and~\citet{schlangen2011general}, incrementality is not a binary feature. Besides using inherently incremental algorithms, it is also possible to provide incremental \emph{interfaces} to non-incremental algorithms. Such interfaces simply feed ever-increasing prefixes to what remains a non-incremental algorithm, providing some ``housekeeping'' to manage the potentially non-monotonic results. To alleviate the effect of the partiality of the input, we test the use of anticipated continuations, inspired by the mechanism of predictive processing discussed in cognitive science~\citep{christiansen2016} and the idea of interactive utterance completion introduced by~\citet{devault2011incremental}. Related strategies to predict upcoming content and to wait for more right context are also applied in recent work on simultaneous translation~\citep{grissom-rl-simul-mt,oda-etal-2015-syntax,ma-etal-2019-stacl}. The use of truncated inputs during training, discussed below, aims at making intermediate structures available during learning, an issue discussed in~\citet{kohn2018incremental}. This is a variation of chunked training used in~\citet{dalvi-etal-2018-incremental}. \section{Evaluation of incremental processors} \label{evalmetrics} The hierarchical nature of language makes it likely that incremental processing leads to non-monotonic output due to re-analysis, as in the well-known ``garden path'' sentences. Incremental systems may edit the output by adding, revoking, and substituting its parts~\citep{baumann2011evaluation}. We expect an incremental system to produce accurate output as soon as possible~\citep{trinh2018multi}, with a minimum amount of revocations and substitutions, ideally only having correct additions, to avoid jittering that may be detrimental to subsequent processors working on partial outputs. To assess the incremental behavior of sequence tagging and classification models, we use the evaluation metrics for incremental processors established by~\citet{schlangen2009incremental} and~\citet{baumann2011evaluation}. The latter defines three diachronic metrics: \textit{edit overhead} (EO $\in [0,1]$), the proportion of unnecessary edits (the closer to 0, the fewer edits were made); \textit{correction time} (CT $\in [0,1]$), the fraction of the utterance seen before the system commits on a final decision for a piece of the output (the closer to 0, the sooner final decisions were made); and \textit{relative correctness} (RC $\in [0,1]$), the proportion of outputs that are correct with respect to the non-incremental output (being close to 1 means the system outputs were most of the time correct prefixes of the non-incremental output). The sequence tagging tasks we evaluate are massively incremental~\citep{hildebrandt1999inkrementelle}, meaning that a new label is always added to the output after a new word is processed. The models can also substitute any previous labels in the output sequence in the light of new input. Sequence classifiers must add one label (the sequence's class) after seeing the first word and can only substitute that single label after each new word. In both cases, additions are obligatory and substitutions should ideally be kept as low as possible, but there can be no revocations. Moreover, our data is sequential, discrete, and order-preserving \cite{kohn2018incremental}. Given a sequence of length $n$, the number of necessary edits is always the number of tokens in the sequence (all additions) for sequence taggers and we set it to 1 for sequence classifiers. All other edits (substitutions) count as unnecessary and their number is bounded by $\sum_{i=1}^{n-1}i$ for tagging, and by $(n-1)$, for classification. We need to slightly adapt the CT measure for sequences. It is originally defined as FD-F0, the time step of a final decision minus the time step when the output first appeared. F0 is fixed for every word in a sequence (the systems always output a new label corresponding to each new word it sees), but each label will have a different FD. In order not to penalize initial labels, which have more opportunities of being substituted than final ones, we instead sum the FD of each token and divide by the sum of the number of times each one could be modified, to get a score for the sequence as a whole. Let the sequence length be $n$, then here CTscore $=(\sum_{i=1}^{n} F\!D_i) / (\sum_{i=1}^{n} n-i)$. We define it to be 0 for sequences of one token. Again, 0 means every label is immediately committed, 1 means all final decisions are delayed until the last time step. Figure \ref{fig:metrics} presents a concrete example of how to estimate the metrics. \begin{figure} \centering \includegraphics[trim={0cm 18cm 21cm 0cm},clip, width=\linewidth]{figures/metrics-examples.pdf} \caption{How we estimate the evaluation metrics for the complete sequence of outputs from Figure~\ref{fig:incremental}.} \label{fig:metrics} \end{figure} Based on the trade-off between responsiveness and output quality~\citep{skantze2009incremental}, we also estimate whether there is any improvement in the quality of the outputs if the encoder waits for some right context to appear before committing on output previously generated. For that, we use delayed EO and delayed RC (also named \emph{discounted} in~\citealp{baumann2011evaluation}), which allows one or two words of the right context to be observed before outputting previous labels, named EO/RC$\Delta1$ and EO/RC$\Delta2$, respectively. In order to concentrate on the incremental quality despite the eventual non-incremental deficiencies, we follow the approach by~\citet{baumann2011evaluation} and evaluate intermediate outputs in comparison to the processor's final output, which may differ from the gold output but is the same as the non-incremental output. The general non-incremental correctness should be guaranteed by having high accuracy or F1 score in the non-incremental performance. \section{Models} \label{framework} \begin{figure}[h] \centering \includegraphics[trim={0cm 16cm 23cm 2.3cm},clip, width=\linewidth]{figures/models-squeeze.pdf} \caption{Models for sequence tagging, w=word and l=label. (a) is the only inherently incremental. (a), (b) and (e) can also be used for sequence classification if we consider only their final representation.} \label{fig:models} \end{figure} We test the behavior of five neural networks, illustrated in Figure~\ref{fig:models}, under an incremental processing interface operating on word level and having full sentences as processing units: a) a vanilla~LSTM; b) a vanilla~BiLSTM; c) an~LSTM with a~CRF (Conditional Random Field) layer; d) a~BiLSTM with a~CRF layer; and e)~BERT. The vanilla~LSTM is the only model that works solely in temporal direction. We choose to use the basic forms of each model to isolate the effect of bidirectionality. They perform well enough on the tasks to enable a realistic evaluation (see Table~\ref{table:performance}). Note that state-of-the-art results are typically achieved by combining them with more sophisticated mechanisms. We use the models for both sequence tagging and classification. They use the representation at each time step to predict a corresponding label for sentence tagging, whereas for sequence classification they use the representation of the last time step~(LSTM) or a combination of the last forward and backward representations~(BiLSTM) or, in case of BERT, the representation at the~CLS (initial) token, as suggested in~\citet{devlin2019bert}. The two models with~CRF cannot be used for classification, as there are no transition probabilities to estimate. Sequence tagging implies a one-to-one mapping from words to labels, so that for every new word the system receives, it outputs a sequence with one extra label. In sequence classification, we map every input to a single label. In that case, the~LSTM can also edit the output since it can change the chosen label as it processes more information. Because the datasets we use are tokenized and each token has a corresponding label, we follow the instructions given by~\citet{devlin2019bert} for dealing with~BERT's subtokenization: the scores of the first subtoken are used to predict its label, and further subtoken scores are ignored. Except for the~LSTM on sequence tagging, all models' outputs are non-monotonic, i.e., they may reassign labels from previous words. The concept of timeliness is trivial here because we know exactly that the label for the \textit{t}-th word will appear for the first time at the \textit{t}-th version of the output, for all \textit{t}. Even so, we can delay the output to allow some lookahead. In terms of decisiveness, all models commit to a single output at every time step. Figure~\ref{fig:inc-interface} shows an example of the computation graph.~BiLSTMs can recompute only the backward pass, while~BERT needs a complete recomputation. \begin{figure} \center \vspace{0.8cm} \includegraphics[trim={0 20cm 23cm 0.5cm},clip, width=\linewidth]{figures/inc-interface.pdf} \caption{Incremental interface of a non-incremental bidirectional model, showing the input and output at time step 3. The context vector fed into the backward~LSTM can be zero or initialized with a hypothetical right context generated by a language model.} \label{fig:inc-interface} \end{figure} \subsection{Strategies} We check the effect of three strategies: \textit{truncated training}, \textit{delayed output} and \textit{prophecies}. In the first case, we modify the training regime by stripping off the endings of each sentence in the training set. We randomly sample a maximum length $l \leq n$, where $n$ is the original sentence length, and cut the subsequent words and labels. We expect this to encourage the model to know how to deal with truncated sequences that it will have to process during testing. The second strategy involves allowing some upcoming words to be observed before outputting a label corresponding to previous words. This is a case of lookahead described in ~\citet{baumann2011evaluation}, where the processor is allowed to wait for some right context before making a first decision with respect to previous time steps. We experiment with right contexts of one or two words, $\Delta1$ and $\Delta2$, respectively. $\Delta1$ means the model outputs the first label for word $t$ once it consumes word $t+1$. Analogously, $\Delta2$ means the model can observe words $t+1$ and $t+2$ before outputting the first label for word $t$. Figure \ref{fig:lookahead} illustrates how to calculate $EO$ with $\Delta1$ delay for the same example as in Figure \ref{fig:metrics}. \begin{figure}[h] \center \includegraphics[trim={0cm 20cm 24cm 0.3cm},clip, width=\linewidth]{figures/lookahead.pdf} \caption{Example of the calculation of Edit Overhead with $\Delta1$ delay for the example in Figure \ref{fig:metrics}. The first choice for each label happens once the subsequent word has been observed, except for the last token in the sentence.} \label{fig:lookahead} \end{figure} In the third strategy, we first feed each prefix as left context in the~GPT-2 language model and let it generate a continuation up to the end of a sentence to create a hypothetical full context that meets the needs of the non-incremental nature of the models (see Figure \ref{fig:incremental-prophecies} for an example). Not surprisingly, the mean BLEU scores of the prophecies with respect to the real continuation of the sentences are less than 0.004 for all datasets.\footnote{ Fine-tuning GPT-2 did not improve BLEU and caused marginal difference in the evaluation metrics. We thus present the results using the pre-trained model only, and leave more exploration of fine-tuning for future work.} \begin{figure}[h] \center \includegraphics[trim={0cm 16.4cm 19cm 0.3cm},clip, width=\linewidth]{figures/incremental-processing-prophecies-squeeze.pdf} \caption{Input throughout time steps using hypothetical right contexts generated by~GPT-2, providing a full sequence for the backward direction.} \label{fig:incremental-prophecies} \end{figure} \section{Experiments} \label{experiments} \begin{table*}[!h] \small \centering \begin{tabular}{r c c c c c c} \toprule & & \multicolumn{5}{c}{\bf Model } \\ \cmidrule{3-7} \bf Task & \bf Metric & \bf LSTM & \bf LSTM+CRF & \bf BiLSTM & \bf BiLSTM+CRF & \bf BERT \\ \cmidrule{1-7} Chunk & & 86.93 (84.23) & 90.40 (88.13) & 90.22 (88.07) & 91.24 (89.44) & 96.32 (96.11)\\ Named Entity Recognition & & 70.78 (67.64) & 86.30 (83.98) & 88.79 (84.72) & 89.29 (87.50) & 93.52 (92.54)\\ Semantic Role Labeling & F1 Score & 52.27 (49.63) & 70.83 (68.71) & 77.39 (73.34) & 84.28 (80.88) & 89.01 (87.23)\\ Slot Filling (ATIS) & (\%) & 93.82 (90.78) & 95.36 (92.09) & 94.84 (91.41) & 95.26 (92.63) & 95.57 (93.88)\\ Slot Filling (SNIPS) & & 82.20 (78.09) & 89.63 (85.28) & 90.44 (85.41) & 92.32 (87.82) & 95.46 (92.93)\\ \cmidrule{2-7} Intent (ATIS) & & 96.86 (93.06) & - & 95.74 (93.62) & - & 97.31 (95.86) \\ Intent (SNIPS) & &96.86 (97.43) & - & 97.43 (97.43) & - & 97.57 (97.71) \\ Part-of-Speech Tagging & Accuracy & 94.98 (94.32) & 96.02 (95.56) & 96.44 (96.23) & 96.64 (96.35) & 97.87 (97.65) \\ Positive/Negative & (\%) & 82.17 (72.83) & - & 83.33 (75.67) & - & 93.83 (92.50) \\ Pros/Cons & & 94.51 (93.85) & - & 94.40 (93.65) & - & 95.74 (95.17) \\ \bottomrule \end{tabular} \caption{Non-incremental performance of all models on test sets (truncated training in parentheses). The results are not necessarily state-of-the-art because we use basic forms of each model in order to isolate the effect of bidirectionality and have comparable results among different tasks.} \label{table:performance} \end{table*} \subsection{Data} We examine the incremental evaluation metrics on ten datasets in English, six for sequence tagging: chunking~\citep{conllchunk}, slot filling~\citep[ATIS and SNIPS, respectively]{hemphill1990atis,coucke2018snips}, named entity recognition, part-of-speech tagging and semantic role labeling ~\citep{ontonotes}; and four for sentence classification: intent~\citep[ATIS and SNIPS, respectively]{hemphill1990atis,coucke2018snips} and sentiment \citep[positive/negative and pros/cons, respectively]{kotzias2015posneg,ganapathibhotla2008proscons}. Chunking,~NER,~SRL, and slot filling use the~BIO labeling scheme and are evaluated using the F1 score adapted for sequence evaluation, whereas the performance on~POS tagging and classification tasks is measured by accuracy. The models map from raw words to labels without using any intermediate annotated layer, even though they are available in some datasets. The only exception is the SRL task, for which we concatenate predicate embeddings to word embeddings following the procedure described in~\citet{he2017deep}, because a sequence can have as many label sequences as its number of predicates. \subsection{Implementation} During training, we minimize cross entropy using the Adam method for optimization~\citep{kingma2014adam}. We perform hyperparameter search for the~LSTM model using Comet's Bayes search algorithm,\footnote{\url{http://www.comet.ml}} to maximize the task's performance measure on the validation set and use its best hyperparameters for all other models, except ~BERT, for which we use HuggingFace's pre-trained bert-base-cased model. We use GloVe embeddings~\citep{pennington2014glove} to initialize word embeddings for all models except~BERT, which uses its own embedding mechanism. Random embeddings are used for out-of-GloVe words. We randomly replace tokens by a general $<$unk$>$ token with probability 0.02 and use this token for all unknown words in the validation and test sets~\citep{lectrack2015}. No parameters are kept frozen during training. Overfitting is avoided with early stopping and dropout. Our implementation uses PyTorch v.1.3.1, and prophecies are generated with~HuggingFace's port of the GPT-2 language model. The evaluation of incrementality metrics is done on the test sets. \footnote{The code is available at \url{https://github.com/briemadu/inc-bidirectional}. For more details on implementation and data for reproducibility, see Appendix.} \section{Results} \label{results} The results in Table~\ref{table:performance} (above) support the observation that, in general, bidirectional models do have a better non-incremental performance than~LSTMs (except for~IntentATIS and~ProsCons) and that there is an overall considerable improvement in the use of~BERT model for all tasks. Truncated training reduces overall performance but even so~BERT with truncated training outperforms all models, even with usual training, in most tasks (except for slot filling and~IntentATIS). \begin{figure}[h!] \begin{subfigure}[t]{\linewidth} \centering \includegraphics[trim={0cm 9.8cm 0cm 0cm}, clip, height=0.5cm]{figures/columns_EO.pdf} \end{subfigure} \centering \begin{subfigure}[t]{\linewidth} \centering \includegraphics[trim={0.5cm 0.3cm 0.5cm 1cm}, clip, height=5cm]{figures/columns_CT.pdf} \caption{Mean Correction Time Score} \label{fig:rose-ct} \end{subfigure} \centering \begin{subfigure}[t]{\linewidth} \centering \includegraphics[trim={0.5cm 0.3cm 0.5cm 1cm}, clip, height=5cm]{figures/columns_EO.pdf} \caption{Mean Edit Overhead} \label{fig:rose-eo} \end{subfigure} \begin{subfigure}[t]{\linewidth} \centering \includegraphics[trim={0.5cm 0.3cm 0.5cm 1cm}, clip, height=5cm]{figures/columns_RC.pdf} \caption{Mean Relative-Correctness} \label{fig:rose-rc} \end{subfigure} \caption{Comparison of evaluation metrics for all models and tasks. The incremental behavior is more stable for sequence tagging than for sequence classification.~BERT takes longer to reach final decisions, and its outputs are edited more often than other models, especially in sequence tagging tasks.} \label{fig:roses} \end{figure} Figure~\ref{fig:roses} presents an overview of the incremental evaluation metrics for all models and tasks. Sequence tagging has, in general, low EO and low CT score; i.e., labels are not edited much and a final decision is reached early. That does not hold for~BERT, whose CT score and EO is, in general, higher. CT score and EO in sequence classification are also higher because the label in this case should capture a more global representation, which cannot reasonably be expected to be very good when only a small part of the sequence has yet been seen. When it comes to RC (correctness relative to the final output), again~BERT has worse results than other models, especially for tagging. For sequence classification, BERT's performance is more in line with the other models. Achieving high RC is desirable because it means that, most of the time, the partial outputs are correct prefixes of the non-incremental output and can be trusted, at least to the same degree that the final result can be trusted. This overview shows that although~BERT's non-incremental performance is normally the highest, the quality of its incremental outputs is more unstable. The next step is examining the effect of the three strategies that seek to improve the quality and stability of incremental outputs. Figure~\ref{fig:aggregate-comparison} shows that truncated training is always beneficial, as is delayed evaluation, with both strategies reducing EO and increasing RC. The fact that delay helps in all cases indicates that most substitutions happen in the last or last but one label (the right frontier, given the current prefix), or, in other words, that even having a limited right context improves quality substantially. \footnote{ Results for SRL are not included in Figure \ref{fig:aggregate-comparison}, because they go in the opposite direction of all other tasks. Since this task depends on the predicate embedding, both truncating the training sequence or adding a right context with no predicate information reduces performance in most cases, except for~BERT. See Appendix for results separated by model and task.} Prophecies are detrimental in classification tasks, but they help in some tagging tasks, especially for~BERT. Most importantly, any of the strategies cause a great improvement to~BERT's incremental performance in sequence tagging, making its metrics be on the same level as other models while retaining its superior non-incremental quality. Note that while CT and RC can only be measured once the final output is available, an estimate of EO may be evaluated on the fly if we consider the edits and additions up to the last output. Figure \ref{fig:eo-overtime} shows how the mean EO evolves, breaking out the results for cases where the non-incremental final output will be correct and those where it will not with respect to the gold labels. We can observe an intriguing pattern: the mean EO grows faster for cases where the final response will be wrong; this is most pronounced for the sequence classification task. It might be possible to use this observation as an indication of how much to trust the final result: If the incremental computation was more unstable than the average, we should not expect the final result to be good. However, initial experiments on building a classifier based on the instability of partial outputs have so far not been successful in cashing in on that observation. \begin{figure*}[h] \centering \begin{subfigure}[t]{0.49\textwidth} \centering \includegraphics[trim={0cm 0cm 0cm 0cm}, clip, width=7.9cm]{figures/strategies-aggregated-tagging-EORCwithoutSRL.pdf} \caption{Sequence tagging} \label{fig:strategies-tagging} \end{subfigure} \centering \begin{subfigure}[t]{0.49\textwidth} \centering \includegraphics[trim={0cm 0cm 0cm 0cm},clip, width=7.9cm]{figures/strategies-aggregated-classification-EORC.pdf} \caption{Sequence classification} \label{fig:strategies-classification} \end{subfigure} \caption{Comparison of mean Edit Overhead and mean Relative-Correctness on the baseline incremental interface and the three strategies using observations from all tasks except SRL.} \label{fig:aggregate-comparison} \end{figure*} \begin{figure} \centering \begin{subfigure}[t]{\linewidth} \centering \includegraphics[width=6cm]{figures/eo-overtime-tagging-aggregated.pdf} \caption{Sequence tagging} \label{fig:eo-time-tagging} \end{subfigure} \centering \begin{subfigure}[t]{\linewidth} \centering \includegraphics[width=8cm]{figures/eo-overtime-classification-aggregated.pdf} \caption{Sequence classification} \label{fig:eo-time-classification} \end{subfigure} \caption{Development of mean Edit Overhead over time using observations from all tasks. \textit{correct} means that all final output labels of a sentence are right and \textit{incorrect} means that at least one label of the final output sequence is wrong. All models are more unstable when their non-incremental final output is incorrect with respect to the gold output.} \label{fig:eo-overtime} \end{figure} \section{Discussion and conclusion} \label{conclusion} We show that bidirectional encoders can be adapted to work under an incremental interface without a too drastic impact on their performance. Even though the training (being done on complete sequences) differs from the testing situation (which exposes the model to partial input), the incremental metrics of most models are, in general, good: in sequence tagging, edit overhead is low, final decisions are taken early, and often partial outputs are a correct prefix of the complete non-incremental output. Sequence classification is more unstable because, at initial steps, there is a higher level of uncertainty on what is coming next. Our experiments show that the deficiencies of~BERT in the incremental metrics can be mitigated with some adaptations (truncated training or prophecies together with delay), which make its incremental quality become as good as those of other models. Since the semantic information is only kept encoded for a few steps in RNNs~\citep{hupkes2018}, this may be a reason why delay causes incremental metrics to be much better. If long-range dependencies are not captured, only neighboring words exert more influence in the choice of a label, so after seeing two words in the right context, the system rarely revises labels further back. BERT, having access to the whole sentence at any time step, is less stable because new input can cause it to reassess past labels more easily. Besides, we also found evidence of different behavior of the instability of partial outputs between correct and incorrect output sequences, which could potentially be a signal of later lower quality. This could be used, for example, in dialog systems: if edit overhead gets too high, a clarification request should be made. A follow-up idea is training a classifier that predicts more precisely how likely it is that the final labels will be accurate based on the development of EO. However, our initial experiments on building such classifier were not successful. We suppose this is due to the fact that, in our datasets, incorrect final output sequences still usually have more than 90\% correct labels, so the learnable signal may be too weak. The use of~GPT-2 prophecies led to promising improvements for~BERT in sequence tagging. We see room for improvement, \textit{e.g.} resorting to domain adaptation to make prophecies be more related to each genre. A natural extension is training a language model that generates the prophecies together with the encoder. Finally, we believe that using attention mechanisms to study the grounding of the edits, similarly to the ideas in~\citet{kohn2018incremental}, can be an important step towards understanding how the preliminary representations are built and decoded; we want to test this as well in future work. \section*{Acknowledgments} We are thankful to the three anonymous reviewers and to our colleagues in the Foundations of Computational Linguistics Lab at the University of Potsdam for their valuable comments and insights. D.S. acknowledges the support by the Deutsche Forschungsgemeinschaft (DFG), grant SCHL 845/9-1. \bibliographystyle{acl_natbib}
{'timestamp': '2020-10-13T02:25:11', 'yymm': '2010', 'arxiv_id': '2010.05330', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05330'}
arxiv
\section{Introduction} Offensive posts on social media result in a number of undesired consequences to users. They have been investigated as triggers of suicide attempts and ideation, and mental health problems \cite{bonanno2013cyber,bannink2014cyber}. One of the most common ways to cope with offensive content online is training systems to be capable of recognizing offensive messages or posts. Once recognized, such offensive content can be set aside for human moderation or deleted from the respective platform (e.g. Facebook, Twitter), preventing harm to users and controlling the spread of abusive behavior in social media. There have been several recent studies published on automatically identifying various kinds of offensive content such as abuse \cite{mubarak2017}, aggression \cite{kumar2018benchmarking,trac2020}, cyber-bullying \cite{rosa2019automatic}, and hate speech \cite{malmasi2018}. While there are a few studies published on languages such as Arabic \cite{mubarak2020arabic} and Greek \cite{pitenis2020}, most studies and datasets created so far include English data. Data augmentation \cite{ghadery2020liir} and multilingual word embeddings \cite{pamungkas2019cross} have been applied to take advantage of existing English resources to improve the performance in systems dealing with languages other than English. To the best of our knowledge, however, state-of-the-art cross-lingual contextual embeddings such as XLM-R \cite{conneau2019unsupervised} have not yet been applied to offensive language identification. To address this gap, we evaluate the performance of cross-lingual contextual embeddings and transfer learning (TL) methods in projecting predictions from English to other languages. We show that our methods compare favorably to state-of-the-art approaches submitted to recent shared tasks on all datasets. The main contributions of this paper are the following: \begin{enumerate} \item We apply cross-lingual contextual word embeddings to offensive language identification. We take advantage of existing English data to project predictions in three other languages: Bengali, Hindi, and Spanish. \vspace{-2mm} \item We tackle both off-domain and off-task data for Bengali. We show that not only can these methods project predictions for different languages but also for different domains (e.g. Twitter vs. Facebook) and tasks (e.g. binary vs. three-way classification). \vspace{-2mm} \item We provide important resources to the community: the code, and the English model will be freely available to everyone interested in working on low-resource languages using the same methodology. \end{enumerate} \section{Related Work} \label{sec:RW} There is a growing interest in the development of computational models to identify offensive content online. Early approaches relied heavily on feature engineering combined with traditional machine learning classifiers such as naive bayes and support vector machines \cite{xu2012learning, dadvar2013improving}. More recently, neural networks such as LSTMs, bidirectional LSTMs, and GRUs combined with word embeddings have proved to outperform traditional machine learning methods in this task \cite{aroyehun2018aggression, majumder2018filtering}. In the last couple of years, transformer models like ELMO \cite{peters-etal-2018-deep} and BERT \cite{devlin2019bert} have been applied to offensive language identification achieving competitive scores and topping the leaderboards in recent shared tasks \cite{liu-etal-2019-nuli,ranasinghe2019brums}. Most of these approaches use existing pre-trained transformer models which can also be used as text classification models. The clear majority of studies on this topic deal with English \cite{malmasi2017detecting,yao2019cyberbullying,ridenhour2020detecting} partially motivated by the availability English resources (e.g. corpora, lexicon, and pre-trained models). In recent years, a number of studies have been published on other languages such as Arabic \cite{mubarak2020arabic}, Danish \cite{sigurbergsson2020offensive}, Dutch \cite{tulkens2016dictionary}, French \cite{chiril-etal-2019-multilingual}, Greek \cite{pitenis2020}, Italian \cite{poletto2017hate}, Portuguese \cite{fortuna2019hierarchically}, Slovene \cite{fiser2017}, and Turkish \cite{coltekin2020} creating new datasets and resources for these languages. Recent competitions organized in 2020 such as TRAC \cite{trac2020} and OffensEval \cite{zampieri2020semeval} have included datasets in multiple languages providing participants with the opportunity to explore cross-lingual learning models opening exciting new avenues for research on languages other than English and, in particular, on low-resource languages. The aforementioned deep learning methods require large annotated datasets to perform well which is not always available for low-resource languages. In this paper, we address the problem of data scarcity in offensive language identification by using transfer learning and cross-lingual transformers from a resource rich language like English to three other languages: Bengali, Hindi, and Spanish. \section{Data} \label{sec:data} We acquired datasets in English and three other languages: Bengali, Hindi, and Spanish (listed in Table \ref{tab:data}). The four datasets have been used in shared tasks in 2019 and 2020 allowing us to compare the performance of our methods to other approaches. As our English dataset, we chose the Offensive Language Identification Dataset (OLID) \cite{OLID}, used in the SemEval-2019 Task 6 (OffensEval) \cite{offenseval}. OLID is arguably one of the most popular offensive language datasets. It contains manually annotated tweets with the following three-level taxonomy and labels: \vspace{-2mm} \begin{itemize} \item[\bf A:] Offensive language identification - offensive vs. non-offensive; \vspace{-2mm} \item[\bf B:] Categorization of offensive language - targeted insult or thread vs. untargeted profanity; \vspace{-6mm} \item[\bf C:] Offensive language target identification - individual vs. group vs. other. \end{itemize} \vspace{-2mm} \noindent We chose OLID due to the flexibility provided by its hierarchical annotation model that considers multiple types of offensive content in a single taxonomy (e.g. targeted insults to a group are often {\em hate speech} whereas targeted insults to an individual are often {\em cyberbulling}). This allows us to map OLID level A (offensive vs. non-offensive) to labels in the other three datasets. OLID's annotation model is intended to serve as a general-purpose model for multiple {\em abusive language detection sub-tasks} \cite{waseem2017understanding}. The transfer learning strategy used in this paper provides us with an interesting opportunity to evaluate how closely the OLID labels relate to the classes in datasets annotated using different guidelines and sub-task definitions (e.g. {\em aggression} and {\em hate speech}). The Hindi dataset \cite{hasoc2019} was used in the HASOC 2019 shared task, while the Spanish dataset \cite{hateval2019} was used in SemEval-2019 Task 5 (HatEval). They both contain Twitter data and two labels. The Bengali dataset \cite{trac2-dataset} was used in the TRAC-2 shared task \cite{trac2020} on aggression identification. It is different than the other three datasets in terms of domain (Facebook instead of Twitter) and set of labels (three classes instead of binary), allowing us to compare the performance of cross-lingual embeddings on off-domain data and off-task data. \begin{table}[!ht] \centering \setlength{\tabcolsep}{4.5pt} \scalebox{.85}{ \begin{tabular}{lccp{5.2cm}} \hline \bf Lang. & \bf Inst. & \bf S & \bf Labels \\ \hline Bengali & 4,000 & F & overtly aggressive, covertly aggressive, non aggressive \\ English & 14,100 & T & offensive, non-offensive \\ Hindi & 8,000 & T & hate offensive, non hate-offensive \\ Spanish & 6,600 & T & hateful, non-hateful \\ \hline \end{tabular} } \caption{Instances (Inst.), source (S) and labels in all datasets. F stands for Facebook and T for Twitter.} \label{tab:data} \end{table} \section{Methodology} Transformer models have been used successfully for various NLP tasks \cite{devlin2019bert}. Most of the tasks were focused on English language due to the fact the most of the pre-trained transformer models were trained on English data. Even though, there were several multilingual models like BERT-m \cite{devlin2019bert} there was much speculations about its ability to represent all the languages \cite{pires-etal-2019-multilingual} and although BERT-m model showed some cross-lingual characteristics it has not been trained on crosslingual data \cite{karthikeyan2020cross}. The motivation behind this methodology was the recently released cross-lingual transformer models - XLM-R \cite{conneau2019unsupervised} which has been trained on 104 languages. The interesting fact about XLM-R is that it is very compatible in monolingual benchmarks while achieving the best results in cross-lingual benchmarks at the same time \cite{conneau2019unsupervised}. The main idea of the methodology is that we train a classification model on a resource rich, typically English, using a cross-lingual transformer model, save the weights of the model and when we initialise the training process for a lower resource language, start with the saved weights from English. This process is also known as transfer learning and is illustrated in Figure \ref{fig:transfer_learning}. \begin{figure}[!ht] \centering \includegraphics[scale=0.72]{images/Transferlearning.png} \caption{Transfer learning strategy.} \label{fig:transfer_learning} \end{figure} \noindent There are two main parts of the methodology. Subsection \ref{subsec:classification} describes the classification architecture we used for all the languages. In Subsection \ref{subsec:transfer} we describe the transfer learning strategies used to take advantage of English offensive language data in predicting offense in less-resourced languages. \subsection{XLM-R for Text Classification} \label{subsec:classification} Similar to other transformer architectures XLM-R transformer architecture can also be used for text classification tasks \cite{conneau2019unsupervised}. XLM-R-large model contains approximately 125M parameters with 12-layers, 768 hidden-states, 3072 feed-forward hidden-states and 8-heads \cite{conneau2019unsupervised}. It takes an input of a sequence of no more than 512 tokens and outputs the representation of the sequence. The first token of the sequence is always [CLS] which contains the special classification embedding \cite{10.1007/978-3-030-32381-3_16}. For text classification tasks, XLM-R takes the final hidden state \textbf{h} of the first token [CLS] as the representation of the whole sequence. A simple softmax classifier is added to the top of XLM-R to predict the probability of label c: as shown in Equation \ref{equ:softmax} where W is the task-specific parameter matrix. \begin{equation} \label{equ:softmax} p(c|\textbf{h}) = softmax(W\textbf{h}) \end{equation} \noindent We fine-tune all the parameters from XLM-R as well as W jointly by maximising the log-probability of the correct label. The architecture diagram of the classification is shown in Figure \ref{fig:architecture}. We specifically used the XLM-R large model. \begin{figure}[ht] \centering \includegraphics[scale=0.4]{images/DeepOffense.jpg} \caption{Text classification architecture with XLM-R.} \label{fig:architecture} \end{figure} \subsection{Transfer-learning strategies} \label{subsec:transfer} When we adopt XLM-R for multilingual offensive language identification, we perform transfer learning in two different ways. \paragraph{Inter-language transfer learning} We first trained the XLM-R classification model on first level of English offensive language identification dataset (OLID) \cite{OLID}. Then we save the weights of the XLM-R model as well as the softmax layer. We use these saved weights from English to initialise the weights for a new language. To explore this transfer learning aspect we experimented on Hindi language which was released for HASOC 2019 shared task \cite{hasoc2019} and on Spanish data released for Hateval 2019 \cite{hateval2019}. \paragraph{Inter-task and inter-language transfer learning} Similar to the inter-language transfer learning strategy, we first trained the XLM-R classification model on the first level of English offensive language identification dataset (OLID) \cite{OLID}. Then we only save the weights of the XLM-R model and use the saved weights to initialise the weights for a new language. We did not use the weights of the last softmax layer since we wanted to test this strategy on data that has a different number of offensive classes to predict. We explored this transfer learning aspect with Bengali dataset released with TRAC - 2 shared task \cite{trac2020}. As described in the Section \ref{sec:data} the classifier should make a 3-way classification in between ‘Overtly Aggressive’, ‘Covertly Aggressive’ and ‘Non Aggressive’ text data. We used a Nvidia Tesla K80 GPU to train the models. We divided the dataset into a training set and a validation set using 0.8:0.2 split on the dataset. We predominantly fine tuned the learning rate and number of epochs of the classification model manually to obtain the best results for the validation set. We obtained $1e^-5$ as the best value for learning rate and 3 as the best value for number of epochs for all the languages. Training for English language took around 1 hour while training for other languages took around 30 minutes. The code and the pretrained English model is available on GitHub.\footnote{The public GitHub repository are available on \url{https://github.com/tharindudr/DeepOffense}} \section{Results and Evaluation} We evaluate the results obtained by all models using the test sets provided by the organizers of each competition. We compared our results to the best systems in TRAC-2 for Bengali, HASOC for Hindi, HatEval for Spanish in terms of weighted and macro F1 score according to the metrics reported by the task organizers - TRAC-2 reported only macro F1, HatEval reported only weighted F1, and HASOC reported both. Finally, we evaluate the improvement of the transfer learning strategy in the performance of both BERT and XLM-R. We present the results along with the majority class baseline for each language in Table \ref{tab:all}. \textit{TL} indicates that the model used the inter language transfer learning strategy described in Subsection \ref{subsec:transfer}. \begin{table}[!ht] \centering \setlength{\tabcolsep}{4.5pt} \scalebox{0.85}{ \begin{tabular}{llcc} \hline \bf Language & \bf Model & \bf M F1 & \bf W F1 \\ \hline & XLM-R (TL) & 0.8415 & 0.8423 \\ & \newcite{risch2020bagging} & 0.8219 & \\ Bengali & BERT-m (TL) & 0.8197 & 0.8231 \\ & XLM-R & 0.8142 & 0.8188 \\ & BERT-m & 0.8132 & 0.8157 \\ & Baseline & 0.2498 & 0.4491 \\ \hline & XLM-R (TL) & 0.8568 & 0.8580 \\ & BERT-m (TL) & 0.8211 & 0.8220 \\ Hindi & \newcite{bashar2019qutnocturnal} & 0.8149 & 0.8202 \\ & XLM-R & 0.8061 & 0.8072 \\ & BERT-m & 0.8025 & 0.8030 \\ & Baseline & 0.3510 & 0.3798 \\ \hline & XLM-R (TL) & 0.7513 & 0.7591 \\ & BERT-m (TL) & 0.7319 & 0.7385 \\ & \newcite{vega2019mineriaunam} & & 0.7300 \\ Spanish & \newcite{perez2019atalaya} & & 0.7300 \\ & XLM-R & 0.7224 & 0.7265 \\ & BERT-m & 0.7215 & 0.7234 \\ & Baseline & 0.3700 & 0.4348 \\ \hline \end{tabular} } \caption{Results ordered by macro (M) F1 for Bengali and weighted (W) F1 for Hindi and Spanish.} \label{tab:all} \end{table} \noindent For Hindi, transfer learning with XLM-R cross lingual embeddings provided the best results achieving 0.8568 and 0.8580 weighted and macro F1 score respectively. In HASOC 2019 \cite{hasoc2019}, the best model by \newcite{bashar2019qutnocturnal} scored 0.8149 Macro F1 and 0.8202 Weighted F1 using convolutional neural networks. For Spanish transfer learning with XLM-R cross lingual embeddings also provided the best results achieving 0.7513 and 0.7591 macro and weighted F1 score respectively. The best two models in HatEval \cite{hateval2019} for Spanish scored 0.7300 macro F1 score. Both models applied SVM classifiers trained on a variety of features like character and word n-grams, POS tags, offensive word lexicons, and embeddings. The results for Bengali deserve special attention because the Bengali data is off-domain with respect to the English data (Facebook instead of Twitter), and it contains three labels (covertly aggressive, overtly aggressive, and not aggressive) instead of the two labels present in the English dataset (offensive and non-offensive). \textit{TL} indicates that the model used the inter-task, inter-domain, and inter-language transfer learning strategy described in Subsection \ref{subsec:transfer}. Similar to the Hindi and Spanish, transfer learning with XLM-R cross lingual embeddings provided the best results for Bengali achieving 0.7513 and 0.7591 macro and weighted F1 respectively thus outperforming the other models by a significant margin. The best model in the TRAC-2 shared task \cite{trac2020} scored 0.821 weighted F1 score in Bengali using a BERT-based system. We look closer at the test set predictions by XLM-R (TL) for Bengali in Figure \ref{fig:heatmap}. We observe that the performance for the non-aggressive class is substantially better than the performance for the overtly aggressive and covertly aggressive classes following a trend observed by the TRAC-2 participants including \newcite{risch2020bagging}. \begin{figure}[ht] \centering \includegraphics[scale=0.62]{images/heatmap.png} \caption{Heat map of the Bengali test set predictions by XLM-R (TL).} \label{fig:heatmap} \end{figure} \noindent Finally, it is clear that in all the experimental settings, the cross-lingual embedding models fine-tuned with transfer learning, outperforms the best system available for the three languages. Furthermore, the results show that the cross-lingual nature of the XLM-R model provided a boost over the multilingual BERT model in all languages tested. \section{Conclusion} This paper is the first study to apply cross-lingual contextual word embeddings in offensive language identification projecting predictions from English to other languages using benchmarked datasets from shared tasks on Bengali \cite{trac2020}, Hindi \cite{hasoc2019}, and Spanish \cite{hateval2019}. We have showed that XLM-R with transfer learning outperforms all of the other methods we tested as well as the best results obtained by participants of the three competitions. The results obtained by our models confirm that OLID's general hierarchical annotation model encompasses multiple types of offensive content such as {\em aggression}, included in the Bengali dataset, and {\em hate speech} included in the Hindi and Spanish datasets, allowing us to model different sub-tasks jointly using the methods described in this paper. Furthermore, the results we obtained for Bengali show that it is possible to achieve high performance using transfer learning on off-domain (Twitter vs. Facebook) and off-task data when the labels do not have a direct correspondence in the projected dataset (two in English and three in Bengali). This opens exciting new avenues for future research considering the multitude of phenomena (e.g. {\em hate speech, aggression, cyberbulling}), annotation schemes and guidelines used in offensive language datasets. In future work, we would like to further evaluate our models using SOLID, a novel large English dataset with over 9 million tweets \cite{rosenthal2020}, along with datasets in four other languages (Arabic, Danish, Greek, and Turkish) that were made available for the second edition of OffensEval \cite{zampieri2020semeval}. These datasets were collected using the same methodology and were annotated according to OLID's guidelines. Finally, we would also like to apply our models to languages with even less resources available to help coping with the problem of offensive language in social media. \section*{Acknowledgement} We would like to thank the HASOC, HatEval, and OffensEval shared task organizers for making the datasets used in this paper available. We further thank the anonymous EMNLP reviewers for providing us with valuable feedback to improve this paper. \bibliographystyle{acl_natbib}
{'timestamp': '2020-10-13T02:24:56', 'yymm': '2010', 'arxiv_id': '2010.05324', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05324'}
arxiv
\section{Introduction}\label{sec:intro} Centralized decision-making systems are being increasingly automated through the use of algorithmic tools: user data is processed through algorithms that predict what products and ads a user will click on, student data is used to predict academic performance for admissions into schools and universities, potential employees are increasingly being filtered through algorithms that process their resume data, and so on. Many of these applications have traditionally fallen under the umbrella of mechanism design, from auction design to fair allocation and school matching to labor markets and online platform design. However, recent pushes towards data-driven decision-making have brought together the fields of mechanism design (MD) and machine learning (ML), creating complex pipelines that mediate access to resources and opportunities. Increasingly, learning algorithms are used in the context of mechanism design applications by adopting reinforcement learning techniques in auctions \citep{feng2018deep,dutting2019optimal,zheng2020ai, tang2017reinforcement} or general machine learning algorithms in combinatorial optimization \citep{bengio2020machine} and transportation systems \citep{jones2018future}. As such applications do not directly focus on fairness and discrimination, they are not the central focus of this paper. The growing impact of these decision-making and resource allocation systems has prompted an inquiry by computer scientists and economists: are these systems fair and equitable, or do they reproduce or amplify discrimination patterns from our society? In building fair and equitable systems, the question of fairness and discrimination is often a contested one. Paraphrasing \citet{dworkin2002sovereign}, \textit{``People who praise or disparage [fairness] disagree about what they are praising or disparaging.''} The causes of these philosophical debates include divergent value systems and the context-dependent nature of fairness and discrimination. However, even when we do agree on the types of harms and discrimination we seek to prevent, mechanism design and machine learning often provide different sets of techniques and methodologies to investigate and mitigate these harms. A key goal of this work is to identify the gaps between how machine learning and mechanism design reason about how to treat individuals fairly and detail concrete lessons each field can learn from the other. Our hope is that these lessons will enable more comprehensive analyses of joint ML--MD systems. Where do the gaps between machine learning and mechanism design come from? Crucially, each field tends to make assumptions or abstractions that can limit the extent to which these interventions perform as desired in practice. This limitation is not specific to machine learning and mechanism design; in general, any field must choose an appropriate scope in which to operate, i.e., a \textit{reducibility assumption}: it is assumed that the issue at hand is reducible to a standard domain problem, and that if the solution to this problem is fair and equitable, then so too will be the overall sociotechnical system \citep{selbst2019fairness}. Under the reducibility assumption, fairness and discrimination can be addressed by an intervention that operates within the frame of the field in question, whether that be a constraint on a machine learning algorithm or a balance between the utilities of various agents in a mechanism. Yet, in practice, complex algorithmic decision-making systems rarely satisfy any sort of reducibility assumption; not only do these systems require the combination of ideas from both disciplines, they also depend heavily on the social and cultural contexts in which they operate. Our goal here is not to argue that it is \textit{sufficient} to consider machine learning and mechanism design in conjunction with one another; rather, we argue that it is \textit{necessary} to do so. Working within each field in isolation will ultimately lead to gaps in our broader understanding of the decision-making systems within which they operate, making it impossible to fully assess the impact these systems have on society. Of course, broadly construed sociotechnical systems cannot be fully understood just through these technical disciplines; our hope is that a more robust understanding of the strengths and weaknesses of machine learning and mechanism design will allow for a clearer view into how they can be integrated into a broader study of these sociotechnical systems. As an illustrative example, consider the problem of online advertising. Most modern online advertising systems perform a combination of prediction tasks (e.g., how likely is a user to click on this ad?) and allocation tasks (e.g., who should see which ad?). Moreover, these advertising systems significantly impact individuals' lives, including their access to economic opportunity, information, and housing, and new products and technologies (see, e.g., \cite{facebookhud, facebookaddiscrimination}). Thus, advertising platforms must consider the social impact of their design choices and actively ensure that users are treated fairly. In isolation, techniques to ensure fair ad distribution from either machine learning or mechanism design fail to fully capture the complexity of the system. On the mechanism design side, auctions typically take learned predictions as a given; as a result, they can overlook the fact that algorithmic predictions are trained on past behavior, which may include the biased bidding and targeting decisions of advertisers. On the other hand, while evaluation tools from fair machine learning would help to ensure that the predictions of interest are ``good'' for everyone (by some definition), they may fail to capture the externalities of competition between ads that might lead to outcome disparities \citep{ali2019discrimination}. For example, a job ad may be shown at a higher rate for men than for women because it must compete against a different set of ads targeted at women than at men. As each field has only a partial view of the overall system, it might be impossible to reason about the system's overall impact without taking a broader view that encompasses both the machine learning and mechanism design considerations. This disconnect is not limited to the ad auction setting described above. Due to their historically different applications and development, both machine learning and mechanism design tend to make different sets of assumptions that do not always hold in practice, especially in pipelines that combine tools from both fields. On the one hand, machine learning traditionally treats people as data points without agency and defines objectives for learning algorithms based on loss functions that depend either on deviations from a ground truth or optimize a pre-defined metric on such data points. Thus, machine learning definitions of fairness tend to ignore complex preferences, long-term effects, and strategic behavior of individuals. On the other hand, as mechanism design often assumes known preferences, and more generally, that information comes from a fixed and known distribution without further critique, and measures utility as a proxy for equality, it tends to miss systematic patterns of discrimination and human perceptions (see also Section \ref{sec:humanperceptions}). While recent works have started to address these gaps between machine learning and mechanism design approaches to fairness by embedding welfare notions in measures of accuracy and fairness and using learning algorithms to elicit preferences, many open questions remain on what each field can learn from the other to improve the design of automated decision-making systems. In this paper, we formalize these ideas into a set of lessons that each field can learn from the other in order to bridge gaps between different theories of fairness and discrimination. In doing so, we aim to provide concrete avenues to address some of the limitations of machine learning and mechanism design, under the acknowledgement that bridging these fields is only an initial step towards a comprehensive analysis of sociotechnical systems. We make the following contributions: \begin{itemize}[noitemsep,topsep=0pt] \item We review definitions of fairness and discrimination in machine learning and mechanism design, highlighting historical differences in the way fairness has been defined and implemented in each (Section~\ref{sec:differences}). \item We define several lessons that can be learned from mechanism design and machine learning in order to create an encompassing framework for decision-making. Specifically, we highlight the gap between fairness and welfare, the potential of long-term assessment of decision making systems, group versus individual assessment of fairness and the effect of human perception of fairness, among others (Section~\ref{sec:pastfuturelessons}). \item Finally, we highlight different application domains and survey relevant works in which both mechanism design and machine learning tools have been deployed, such as advertising, education, labor markets and the gig economy, criminal justice, health insurance markets, creditworthiness, and social networks. We discuss advances and limitations of current techniques and implementations in each of these domains, relating to the lessons from the previous section (Section~\ref{sec:applications}). \end{itemize} \section{Differences between Mechanism Design and Machine Learning}\label{sec:differences} Machine learning has been increasingly used to supplement human decisions, drawing attention to biases rooted in learning from historically prejudiced data \citep{angwin2016machine,buolamwini2018gender,barocas2016big}. Fair machine learning often defines fairness conditions (e.g. parity for legally protected groups) without considering core mechanism design concerns such as welfare and strategic behavior. Yet, mechanism design often fails to conceptualize the impact of decisions for different social groups. While both fields incorporate quantitative notions of fairness into optimization, they differ in the roles those notions play: in machine learning, fairness is typically a constraint to be satisfied, hence the learning algorithms are not optimizing for the \emph{most} fair solution; in contrast, mechanism design typically defines and directly optimizes a fair utility-based objective (e.g., social welfare). This is only one of many high-level differences between the two fields. \citet{abebe2018mechanism} and \citet{kasy2020fairness} indirectly observe that understanding those differences and bridging different notions of fairness is essential in improving access to opportunity for different communities, as well as extending the purpose of each field to encompass the causal effect of algorithmic design on inequality and distribution of power \citep{kasy2020fairness}. \subsection{Fairness in machine learning}\label{subsec:fair-ml} Multiple definitions of fairness have been proposed; interestingly, their common characteristic seems to be that they agree to disagree. \citet{mehrabi2019survey} collect the most common fairness definitions; most of them fall into two main categories, \emph{individual} and \emph{group} fairness. Group fairness notions assess the large-scale effect of an algorithmic system on different demographic groups (often defined by legally protected classes). Individual fairness, however, compares outcomes between each individual in a population, requiring people who are similar to each other to receive a similar outcome, and is therefore typically a stronger constraint. \vspace{0.37em} \noindent\textbf{Individual fairness.} Inspired by \citet{rawls2009theory}' fair equality of opportunity in political philosophy, \citet{dwork2012fairness} formalize the notion of individual fairness as a constraint in a classification setting where one wants to \textit{``treat similar individuals similarly''} based on a pairwise similarity metric of their features, (partially) designed by domain experts. However, defining similarity metrics is not easy, especially between individuals belonging to sub-populations with different characteristics. Subsequent work, though limited, mainly aims to overcome this obstacle by either learning feature representations that conceal the individuals' membership to a protected group \citep{zemel2013learning, lahoti2019ifair} or by selecting individuals based on how they compare in terms of qualification with other members of their own sub-group \citep{kearns2017meritocratic}. However, individual fairness is not equivalent to meritocracy, since qualified covariates might be more difficult to obtain for disadvantaged people, meaning one person may have worked harder to be recognized as ``similar'' by the algorithm \citep{hu2019disparate}. Overall, individual fairness is reminiscent, yet different, from the individual perspective that utility measures in mechanism design often take (e.g., the notion of envy-freeness from mechanism design) and can be used to compare metrics that assess the individual experience in an algorithmic setting. While individual fairness does not take into account one's preferences (often assumed in mechanism design), recent works \citep{kim2019preference} re-design this definition by taking into account individual preferences. \vspace{0.37em}\noindent\textbf{Group fairness.} Numerous definitions have been proposed for group fairness \citep{verma2018fairness,mehrabi2019survey}, suggesting to impose either simple statistical parity conditions between groups \citep{ corbett2017algorithmic} or more complex classification constraints; some aim to equalize each group's opportunity to positive outcomes \citep{hardt2016equality}, balance the misclassification rates among groups \citep{berk2018fairness, zafar2017fairness} or provide similar classifications under counterfactual group memberships \citep{kusner2017counterfactual}. \citet{kleinberg2017inherent} and \citet{chouldechova2017fair} show that tensions arise when trying to simultaneously achieve multiple notions. However, as \citet{madaio2020co} emphasize, if one is to strive for quantitative fairness, the notion one optimizes for should be context-dependent and developed in partnership with stakeholders. \vspace{0.37em} Despite the variety of individual and group fairness definitions, it becomes apparent that they lack \textit{expressiveness}. Most of these definitions focus solely on the inputs and outputs of the algorithm without taking into account how those outputs ultimately impact real-world outcomes. For example, the most common assumption is that a ``positive classification'' output is an equally valuable outcome for everyone. As we discuss in Sections~\ref{subsec:fair-md} and~\ref{sec.tension_fairness_welfare}, mechanism design can offer the tools and definitions to overcome such limitations and successfully incorporate important aspects such as individual- and group-level utilities, resource constraints, as well as strategic incentives, to the design of decision-making models. \subsection{Fairness in mechanism design} \label{subsec:fair-md} The mechanism design literature shifts the focus away from \emph{fairness} towards \textit{welfare} and \emph{discrimination.} We review (i) the classic theories of taste-based and statistical discrimination, (ii) utilitarianism and the idealized objective of maximum social welfare, and (iii) fairness in social choice theory. \vspace{0.37em}\noindent\textbf{Economic theories of discrimination.} There are two prevalent economic theories of discrimination: \textit{taste-based} and \textit{belief-based}. The key difference between them is the effect of information; taste-based discrimination arises due to pure preferences \citep{becker1957economics}, and persists even with perfect information about individuals. This theory has often been criticized as being simplistic since it is based on the discriminatory principle that decision-making agents derive higher utility from certain social groups \citep{guryan2013taste}; however, empirical evidence is rather inconclusive and application-dependent \citep{charles2008prejudice, altonji2001employer, knowles2001racial, cui2017discrimination}. The latter theory of belief-based discrimination can be particularly informative for the design of fair machine learning systems as the true attribute of an agent is often not observed directly, but only through a proxy. From this theory, \textit{statistical discrimination} \citep{arrow1973theory,phelps1972statistical} generally assumes that differences are exogenous but exist. Other papers attribute discrimination to \textit{coordination failure}: agents are born unqualified but can undertake some costly skill investment, which may lead to asymmetric equilibria \citep{coate1993will}. Finally, another belief-based discrimination theory is \textit{mis-specification} \citep{bohren2019dynamics}; unaware of their own bias \citep{pronin2002bias}, decision-makers may hold misspecified models of group differences which, in the absence of perfect information, lead to false judgment of an individual's abilities. Such economic models offer useful insights on how to design a system aware of inequality due to (i) equilibrium asymmetries, (ii) information limitations, and (iii) human behavioral biases. For example, different social groups may differ in their skill level due to systematic inequalities of opportunity when certain equilibria arise, but not due to inherited differences in their true ability. This may be in sharp contrast to human decision-makers (or even algorithms) who, due to imperfect information or other biases, may incorrectly infer that perceived differences among individuals can be perfectly explained by observed characteristics. \vspace{0.37em}\noindent\textbf{Utilitarianism and normative economics.} Beyond discrimination theories, utilitarianism and normative economics have been extensively used in mechanism design to motivate using utility functions as a synonym for social welfare. Although these two terms are used interchangeably and welfare economics is often viewed as applied utilitarianism, their origin differs. As \citet{posner1983economics} writes, \textit{utilitarianism} is a philosophical system which holds that \textit{``the moral worth of an action, practice institution or law is to be judged by its effect on promoting happiness of society.'' } On the other hand, \textit{normative} or \textit{welfare economics} holds that \textit{``an action is to be judged by its effects in promoting the social welfare.''} \citep{posner1983economics} In contrast to machine learning and its multiple definitions of fairness, weighted social welfare is the most accepted measure of broader ``social good'' in mechanism design but not necessarily of fairness or equity. Typically, utilitarian approaches capture equity by assigning appropriately defined weights to the utility of each agent. Nevertheless, a major limitation remains as welfare economics models rarely explain how to come up with these weights and how to interpret the relative difference between two agents' weights \vspace{0.37em}\noindent\textbf{Fairness in social choice theory.} Social choice theory deals with collective decision making processes, and fairness is of great significance in such processes---particularly in resource allocation problems and voting. In fair allocation, the goal is to divide a resource or set of goods among $n$ agents that is somehow ``fair.'' The literature tends to focus on three primary notions of fairness: {\it proportional division} \citep{steihaus1948problem} (every agent receives at least $\frac{1}{n}$ of her perceived value of resources); {\it equitability} \citep{foley1967resource} (every agent equally values their allocations); and {\it envy-freeness} \citep{varian1973equity} (every agent values their allocation at least as much as another's). While these notions capture fairness of allocations at an individual level, they treat all individuals equally in contrast to individual fairness which relies on some similarity metric to ensure similar outcomes only for simila individuals. Moreover, in many real-world problems in healthcare, finance, education, relaxed notions of fairness are used due to the hardness of the absolute notions. \citet{conitzer2019group} points out that one deficiency of relaxed notions of fair allocation is that they fail to capture group-level disparities and often leave room for group unfairness (see Section \ref{subsec:redefining_fairness}). Finally, another difference is that, unlike machine learning settings where all individuals prefer positive or higher outcomes, social choice theory can naturally capture different preferences of agents over the possible outcomes.\footnote{Voting theory deals with aggregating individual preferences. We exclude discussions on voting while we acknowledge the existence of substantial works on fair voting.} \section{Past and Future Lessons}\label{sec:pastfuturelessons} We enumerate several lessons that mechanism design (MD) and machine learning (ML) are able to learn from each other. We denote by $A \to B$ a lesson that has been or can be taught by field $A$ to $B$. \subsection{MD $\to$ ML: Tension between fairness and welfare} \label{sec.tension_fairness_welfare} \citet{kaplow2003fairness} are among the first to argue, from a legal and economic point of view, that \textit{``the pursuit of notions of fairness results in a needless and, at root, perverse reduction in individuals’ well-being,''} and that welfare should be instead the primary metric for the effectiveness of a social policy. Optimizing for fairness instead of welfare can actually cause harm in social decision-making processes (e.g., by leading to a violation of the Pareto principle). This is later supported for quantitative fairness metrics by \citet{hu2020fair,hossain2020designing}, who show that adding group parity constraints can decrease welfare for \emph{every} group. Recent works also propose fairness-to-welfare pathways that transform utility-based metrics into comparing probability of outcome \citep{zafar2017parity,balcan2019envy,hossain2020designing}, showing that fairness definitions do not automatically imply equitable outcomes from a mechanism design perspective, but on the contrary. \citet{kasy2020fairness} formalize some of these tensions, arguing that machine learning definitions fail to acknowledge inequality within protected groups as well as perpetuate it through notions of merit. This is further complicated by the fact that, while notions of fairness in machine learning often treat outcomes as binary with a single desirable outcome, the real world is far more complex; different individuals may have different preferences over a wide range of outcomes. While individual fairness is often incorporating stronger constraints to ensure that individuals receive a good outcome given their features, their preferences are not directly taken into account. Recent works are addressing this gap by re-designing notions of fairness with preferences in mind \citep{kim2019preference}. Using the lens of welfare economics as well as economic theories of discrimination to assess the equitability of machine learning systems can be useful for designing just systems, but it is no panacea. An important question that arises is whether the prevalent utilitarian view of mechanism design is already problematic. A common criticism of utilitarianism is that it is not clear whose utilities we should maximize and how much weight each individual should receive in the optimization objective. For example, should an algorithm ensure the average utilities of both protected and unprotected groups be the same, or should each group contribute to the total welfare proportionally to its size in society? If we search beyond economics and computer science, we soon realize that practical difficulties and tensions in philosophy, political science, history, sociology and other disciplines are similar to some of the tensions we currently see in machine learning. For example, borrowing from political philosophy, \citet{binns2017fairness} introduces new notions of fairness that challenge both the common concept of social welfare maximization and fair machine learning definitions, by asking questions such as: \textit{should we minimise the harms to the least advantaged?} In the end, while there may be no universal notion of welfare that adequately captures society's beliefs about whose welfare to prioritize, mechanism design provides the tools to begin to interrogate these welfare trade-offs in a way that machine learning has yet to fully reckon with. \subsection{MD $\to$ ML: Long-term effects of fairness}\label{sec:longterm} Because mechanism design considers outcomes for an entire population of agents, the machine learning community has started to adopt mechanism design techniques (ranging from equilibria analysis in games to dynamic models of learning agents) in order to study the effects of machine learning algorithms on different subpopulations. For example, the decisions made by an algorithm and the (strategic) participants can change the population data over time, requiring learning to be dynamic rather than one-shot. Economics has long studied such dynamic effects, but without a machine learning perspective. However, several useful lessons can be extracted from recent works \citep{zhang2020fairness}. First and foremost, dynamic effects over time are crucial, and, if neglected, they can worsen rather than improve inequality and discrimination in large-scale decision-making systems. Indeed, even simple two-stage models show that it is impossible to achieve full equality and have the potential of causing harm due to fairness constraints \citep{liu2018delayed,kannan2019downstream}; interestingly, such models and subsequent works \citep{liu2020disparate} are strongly influenced by the classic economic models such as \citet{coate1993will} and \citet{phelps1972statistical}. Second, the type and complexity of interventions needed to achieve long-term fairness may vary significantly. For example, \citet{hu2018short} build upon the labor market model in \citet{levin2009dynamics} and showcase the positive effect of simple short-term restrictions (via a group demographic parity constraint) on improving long-term fairness. However, other systems may require a more complex approach; \citet{wen2019fairness} study fairness in infinite-time dynamics by using a Markov Decision Process to learn a policy for decision-making that achieves demographic parity or equalized odds in the infinite time dynamics. From a technical perspective, increasing leaning on popular mechanism design tools such as large market models, mean-field equilibria analysis, and dynamic programming techniques seems to be a promising direction for the design of effective and fair policies in machine learning-driven systems. Finally, most machine learning models focus solely on algorithmic bias and are oblivious to the existence of the social bias that is coming from human agents making complex, dynamic decisions as a response to the system's algorithmic decisions. The interplay between social and algorithmic bias over time may in fact prove itself useful in explaining dynamic patterns of discrimination in sociotechnical systems. \citet{bohren2019dynamics} introduce the discrimination theory of mis-specification and show, both theoretically and empirically, that contradicting patterns of discrimination against women's evaluations in online platforms can be well explained by users' mis-specified bias in sequential ratings. \citet{monachou2019discrimination} build upon this theory and tools for learning from reviews to study the long-term effects of social bias on worker welfare inequality in online labor markets, while \citet{heidari2019long} also use observational learning to study the temporal relation between social segregation and unfairness. \subsection{MD $\to$ ML: Strategic agents} The economist's basic analytic tool is the assumption that people are \textit{rational maximizers} of their utility, and most principles of mechanism design are deductions from this basic assumption. Therefore, as machine learning algorithms are increasingly used in prescriptive settings, like hiring or loan approval, it becomes necessary to consider the incentives of the agents who are affected from those algorithmic decisions. As transparency laws regarding algorithmic decision-making are gradually being introduced \citep{voigt2017eu}, individuals are now more than ever capable to use insights about the deployed classifiers and accordingly alter their features in order to ``game'' the system and receive a beneficial outcome. This observation has initiated a line of work on \textit{strategic classification} \citep{dalvi2004adversarial,bruckner2011stackelberg,bruckner2012static, hardt2016strategic, dong2017strategic, chen2020learning, hu2019disparate} which focuses on incentive-aware machine learning algorithms that try to reduce misclassification caused by transparency-induced strategic behavior. The ability to manipulate their features naturally raises several fairness questions. For example, \citet{hu2019disparate} contextualize strategic investment in test preparation to falsely boost scores that are used as a proxy to quantify college readiness, as well as the disparate equilibria that could potentially emerge in the presence of social groups with disproportionate manipulation capabilities. Additionally, \citet{milli2019social} utilize credit scoring and lending data to show that there is a trade-off between the utility of a decision-maker who tries to protect themselves from the agents who modify their features strategically and the social burden different groups of agents incur as a consequence. On a more positive note, recent work has argued that this strategic modification of features does not always correspond to an agent's attempt to ``game'' the system but could also represent a truthful investment of effort towards improvement, depending on the features being used and the extent to which they can be maliciously manipulated. This idea has become apparent both in the mechanism design literature \citep{kleinberg2019classifiers, alon2020multiagent} on evaluation mechanisms and the machine learning literature \citep{tsirtsis2020optimal, miller2019strategic, haghtalab2020maximizing} on the design of transparent decision policies that aim to incentivize the individuals' improvement. Relaxing our initial assumption about strict individual rationality, we can easily see that transparent decision policies based on features prone to manipulation may prove themselves substantially unfair, by equally rewarding seemingly similar individuals with dissimilar effort profiles (in direct opposition to definitions of individual fairness), as those dissimilarities may have ethical, behavioral or cultural origins. For ease of exposition, consider a simple example of admitting graduate students solely based on their undergraduate GPA. Even if two students share the same observable features (GPA), that could reflect different mixtures of manipulating the undergraduate evaluation rules or achieving truthful academic excellence, a behavior often depending on their cultural background \citep{magnus2002tolerance,payan2010effect}. In this context, the uncertain relation between features and individual qualifications gives rise to a need for \textit{strategyproofness} in order to make prediction-based decision-making systems transparent and fair. Apart from simple classification settings, the interplay between machine learning and mechanism design also needs to be considered in more complex systems where the stakeholders have more diverse incentives and predictive models of different forms also appear. For example, in health insurance markets machine learning is used to predict the expected costs of individuals and proportionally compensate insurers, with strategic upcoding by the latter favorably skewing subsequent predictions \citep{cunningham2012risk} and disincentivizing all insurers from offering attractive insurance plans to people with specific medical conditions \citep{zink2020fair}. Moreover, the retrieval and recommender systems, well-known downstream applications of machine learning, are also vulnerable to strategic behavior leading to disparate effects even in the absence of model transparency; specifically, strategic manipulation in recommendations \citep{chakraborty2019equality,song2020poisonrec} and search engines \citep{baruchson2007manipulating,epstein2015search} often results in skewed information delivery leading to disproportional opportunity or exposure for the users. Such disparate effects of machine learning highlight the need for further research towards the direction of developing models aware of the strategic environment in which they operate as well as the effects of their predictions on different people and groups. \subsection{ML $\to$ MD: Defining and diagnosing unfairness under uncertainty} \label{subsec:redefining_fairness} Definitions of fairness from the mechanism design literature tend to be centered around preferences and utilities. As discussed earlier, the fair machine learning literature has yet to fully adopt this perspective, typically operating at the level of model outputs as opposed to the values for individuals produced by those outputs. However, a key assumption necessary for mechanism design’s preference-based notions of fairness is that individuals’ preferences are known or can be in some way communicated to a central decision-maker. In many mechanism design applications, like traditional auctions or school choice, this assumption can be reasonable. In more complex systems like online advertising, preferences are often unknown a priori and must be estimated in practice. Thus, questions of fairness necessarily involve reasoning about uncertainty and who bears the burden of errors. In this way, ideas about fairness from machine learning can be useful. Because machine learning treats uncertainty as a first class concept, many conceptions of fairness from the machine learning literature explicitly consider errors and their impact on different sub-populations \citep{hardt2016equality,chouldechova2017fair, zafar2017fairness}. Uncertainty can also manifest itself with respect to outcomes, not just to preferences. Many application domains utilize probabilistic models---for example, labor market models from mechanism design often consider two-stage processes in which noisy signals provide information about whether a worker is qualified or not \citep{coate1993will,hu2018short}. Importantly, while these models do incorporate uncertainty, the designer knows the true relationship between observed signals and true outcomes, even though this relationship is probabilistic. This style of analysis is less suited to deal with cases where the relationship between signals and ground truth is unknown and can only be learned about through data. The lack of ground-truth information greatly complicates any analysis of the impact of a mechanism, but it is precisely this lack of information that machine learning techniques are designed to handle. Many of the challenges that arise during learning, including data scarcity for certain groups \citep{buolamwini2018gender}, feedback loops \citep{ensign2018runaway}, preference elicitation \citep{zinkevich2003polynomial,blum2004preference,goldberg2020learning,frongillo2018axiomatic}, and explore-exploit trade-offs \citep{bird2016exploring,immorlica2019diversity,raghavan2018externalities}, implicate serious fairness concerns. By integrating lessons from machine learning on how to define and measure disparities that learning produces, mechanism design can gain a deeper understanding of real-world systems. Using fairness definitions as a diagnostic tool for potential harms and societal issues is a powerful application of computing, as \citet{abebe2020roles} argue. As such, the various group fairness definitions from machine learning focus on illustrating output differences between different legally protected groups, using error measurements to quantify such differences (e.g., false positive/negative rates). A single definition is thus not feasible, nor desirable, but the process of defining fairness has been expanding, both conceptually and practically: from early computer science works that defines fairness through observations \citep{dwork2012fairness,hardt2016equality} or representations \citep{zemel2013learning,feldman2015certifying} to understanding causal relationships between features \citep{kusner2017counterfactual,kilbertus2017avoiding}. While satisfying multiple definitions may not always be possible \citep{kleinberg2017inherent}, the different definitions of fairness in machine learning offer an opportunity to become more intersectional in defining sensitive groups and in assessing power differentials. More than that, they shift the purpose of defining fairness from a normative one to a diagnostic one, a purpose that mechanism design can learn from when assessing the utility of a system. Together with a plethora of works from economics that assess differences in welfare at a group level \citep{coate1993will,hu2018short}, recent works in mechanism design \citep{conitzer2019group} propose adapting individual notions of envy-freeness into group-level definitions through stability, e.g., no group of people should prefer the outcome of another group. The need to assess the outcome differences between groups becomes more pressing as machine learning tools are increasingly being used in traditional mechanism design applications, as previously discussed. Recent works increasingly adapt group fairness methods inspired from machine learning to design fair voting procedures \citep{celis2017multiwinner} and advertising \citep{kim2019preference}, bridging the gap between the individual perspective of mechanism design methods and group-level definitions of fairness from machine learning. Beyond transferring lessons from machine learning to mechanism design, we argue that future design must encompass perspectives other than the purely computational one, from sociological understandings of harm and power to economic discrimination and theories of justice. \subsection{ML $\to$ MD: Human perceptions and societal expectations of fairness} \label{sec:humanperceptions} Early studies on fairness in both mechanism design and machine learning propose various mathematical formulations of fairness, and normatively prescribe how fair decisions should be made. However, given the impossibility to simultaneously satisfy multiple fairness notions \citep{kleinberg2017inherent,chouldechova2017fair}, decision-making systems need to be restricted to only selected principles of fairness, a process that becomes challenging in certain applications, such as criminal justice, finance and lending, self-driving cars, and others. Given such applications and their potential for harm, it is essential for the chosen design and principles to be socially acceptable. Thus, there is a need to understand how people assess fairness and how to infer societal expectations about fairness principles in order to account for all voices in a democratic design of decision-making systems. A line of work \citep{woodruff2018qualitative, lee2018understanding, grgic2018human, green2019disparate, srivastava2019mathematical, saha2020measuring} in machine learning research has taken steps towards this democratization goal through participatory sociotechnical approaches to fairness \citep{baxter2011socio,van2012agent} by studying human perceptions and societal expectations of fairness. Three major questions emerge from this line of work, which, we argue, are central in developing participatory mechanism design tools that incorporate preferences. We discuss them next. First, {\it whose perceptions or assessment of fairness should be considered?} While \citet{awad2018moral} and \citet{noothigattu2018voting} used crowdsourced preferences from lay humans in the famous moral machine experiment, \citet{jaques2019moral} and \citet{yaghini2019human} have argued that preferences should be taken only from relevant individuals (e.g., primary stakeholders, ethicists, domain experts), citing context-dependent aspect of fairness and the possible vulnerability of lay humans to societal biases. Second, {\it what options and information should be made available to the participants?} Some studies \citep{harrison2020empirical,saxena2019fairness,awad2018moral,noothigattu2018voting} directly asked participants to choose the model with the best fairness notion or the best outcomes, whereas others \citep{srivastava2019mathematical,grgic2018human,yaghini2019human} asked indirect questions to infer the acceptable fairness principles (e.g., whether they approve of certain differences in decision outcomes for pairs of individuals from different groups, or the overall outcome distribution). In a different approach, \citet{grgic2018beyond} and \citet{van2019crowdsourcing} study the validity of using certain input features in the decision-making process in order to achieve procedural fairness. Finally, {\it how should the individual preferences be aggregated?} Even though most of the literature has followed some variant of majority rule for this, \citet{noothigattu2018voting} and \citet{kahng2019statistical} have argued for tools like score-based bloc voting or Borda count from voting theory \citep{elkind2017properties} for better representation of participants' choices. These studies have also shown the need of model explainability \citep{binns2018s,rader2018explanations,dodge2019explaining}, transparency \citep{rader2018explanations,wang2020factors}, and context-specific feature selection \citep{grgic2018beyond,van2019crowdsourcing} in improving societal fairness perceptions, which mechanism design has traditionally considered as out of scope or assumed to be known, leading to a recent surge in explainability and transparency studies in machine learning. Future work in mechanism design can learn from such studies in challenging current assumptions about preferences, perceptions, and values. \section{Application Domains}\label{sec:applications} In this section, we discuss several application domains of machine learning and mechanism design to illustrate the lessons of Section~\ref{sec:pastfuturelessons}, underscore the complex interplay between these domains, point out gaps, as well as potential ways of bridging these gaps. We note that many of the applications are open to critique. One might object to the idea of deciding which students are qualified or unqualified to receive an education in college admissions. More fundamentally, one might argue that the overall social system (e.g., criminal justice) in which an application (e.g., recidivism prediction) is embedded is unjust, and further that this cannot be remedied by any technical fairness intervention. We discuss applications merely as an illustration of the lessons we have articulated, and reiterate our position that it is necessary, though not sufficient, to bridge machine learning and mechanism design for algorithmic fairness. \subsection{Online advertising} Auction design (a subfield of mechanism design) deals with the optimal design of allocation and payment rules when a number of agents bid for a resource. As online ad auctions run in a high-frequency online setup that demands automated and precise bidding from the agents, many ad platforms have deployed machine learning models to estimate the relevance of an ad to a customer while using some high-level preferences about advertisers' budget, bidding strategies, and target audiences. Using the automated bids derived from these relevance predictions, ad allocation mechanisms \citep{ostrovsky2011reserve} are run to place specific ads every time a user visits a webpage, thus making the system a complex mix of interdependent components from both machine learning and mechanism design. Recent studies show that the resulting ad delivery may be problematically skewed; users who differ on sensitive attributes such as gender \citep{lambrecht2019algorithmic}, age \citep{angwin2017facebook}, race \citep{angwin2016facebook}, may receive very different types of ads. For example, search queries with Black-sounding names are highly likely to be shown ads suggestive of arrest records \citep{sweeney2013discrimination}. In another study, women were shown relatively fewer advertisements for high-paying jobs than men with similar profiles \citep{datta2015automated}. When ads are about housing, credit or employment, such disparities can harm equality of opportunity. One cause of problematically skewed ad delivery is explicit targeting of users based on sensitive attributes \citep{faizullabhoy2018facebook, angwin2016facebook}, which can be tackled by disallowing ad targeting based on sensitive attributes especially for housing, credit, and employment ads. Although major ad platforms like Google and Facebook had disallowed targeting of opportunities ad based on sensitive attributes, the advertisers could still exploit other personally identifiable information such as area code \citep{speicher2018potential}, or using a biased selection of the source audience in the Lookalike audience tool by Facebook. Following a lawsuit \citep{spinks2019contemporary}, Facebook removed targeting options for housing, credit, and employment ads \citep{facebookaddiscrimination}. Other studies \citep{sapiezynski2019algorithms,ali2019discrimination} again reveal that ad delivery mechanisms could still result in skewed audience distribution based on sensitive attributes even in the absence of any inappropriate targeting. These are often the results of competitive spillovers; relative competition between general opportunity ads and category-specific ads for items like women's fashion can result in opportunity ads being shown to more male audiences. This issue has been tackled from both advertisers’ side and auctioneer’s side. Solutions on the advertisers' side include running multiple ad campaigns for different sensitive groups (with parity-constrained budgets) \citep{gelauff2020advertising}, or using different bidding strategies for different demographics groups \citep{nasr2020bidding}. However, such type of targeting has been disallowed by the platforms because of earlier exploitation by discriminatory advertisers. Moreover, rational advertisers may not want to adopt solutions that decrease utility. On the auctioneer’s side, the allocation mechanism can be redesigned to ensure fair audience distribution \citep{dwork2018fairness, ilvento2020multi, chawla2020fairness, celis2019toward}. Along with the welfare optimization goal, group fairness constraints can be used to ensure fair audience distribution \citep{celis2019toward}, and individual fairness \citep{chawla2020fairness} or envy-freeness constraints \citep{ilvento2020multi} can be adopted to ensure similar individual satisfaction of the users. Most of these papers have focused on the mechanism design of online ad delivery. Yet all components---advertisers’ strategies, platform’s relevance prediction, ad allocation mechanism---may be responsible for unfair ad delivery. While the mechanism design components take the relevance predictions from machine learning models as inputs, they often overlook the possibility of biases in these predictions. Thus, to build a fair online ad ecosystem, there is a need to study the role of relevance prediction models and their role in the mechanism design pipeline. In this regard, a line of work in machine learning that studies preference elicitation in auction settings \citep{parkes2005auction,zinkevich2003polynomial,lahaie2004applying} can be explored and extended to online advertisements. \subsection{Admissions in education} Schools and universities increasingly use machine learning to inform admissions decisions \citep{clemsonadmissions}. Mechanism design has traditionally studied problems such as school choice, college admissions and affirmative action (e.g., \citep{abdulkadirouglu2003school,chade2014student,abdulkadirouglu2005college, chan2003does, fu2006theory, kamada2019fair, foster1992economic, immorlica2019access}). In general, most of these papers adopt similar assumptions and approaches. At their baseline, they model the problem as a two-sided ``market'' of strategic agents: schools or colleges on the one side and students on the other side. In school choice, the assignment decisions are usually centralized (e.g., all public schools in Boston may commit to a common matching process), while in college admissions, each university decides independently which applicants to admit. In both cases, explicit fairness considerations are rarely taken into account. The only exception is, of course, \textit{affirmative action}, which is imposed as an additional external constraint on the market. Most economics papers have mostly considered two categories of policies with respect to protected attributes: \textit{group-unaware} and \textit{group-aware} policies \citep{fang2011theories}. Both policy schemes usually translate to demographic parity constraints and similar quota rules. Interestingly, explicit notions of fairness and equity are less commonly considered. This may be due to various reasons. For example, in a decentralized system such as college admissions, it is unclear whether and---most importantly---how to optimize social welfare. But even in more centralized applications, such as school choice, several dilemmas arise. Given that both market sides have heterogeneous preferences and strategic incentives, should the central planner prioritize the students' or schools' welfare? How is social welfare even practically defined in this case? Indeed, several papers \citep{roth2008deferred,pathak2017really,robertson2020if,hitzig2018bridging,li2017ethics} have offered a broader critique of the approaches used by market designers, pointing to the gap between translating theoretical assumptions to practical solutions. Machine learning algorithms are increasingly being used in this area as well, for the purpose of parsing data at a large scale more efficiently and embedding missing notions of fairness. The machine learning literature \citep{haghtalab2020maximizing,liu2020disparate,hu2019disparate,emelianov2020fair,immorlica2019access,garg2020standardized} usually poses the admissions problem as a classification task to predict whether an applicant is ``qualified'' or ``unqualified'' to attend their university based on covariates given in the student's application (standardized test scores, demographic information, etc.). When framed as a machine learning problem, the task at its core is to accept students who are qualified and reject those who are not. However, when one widens the scope of the problem, one soon realizes that universities have finite capacity for accepting students, which creates market competition and thus strategic incentives among schools and applicants. This latter problem is studied through a dual ML-MD lens by \citet{emelianov2020fair}, who consider admission policies under implicit bias, and show how affirmative action in the form of group-specific admission thresholds can improve diversity and academic merit at a capacity-constrained university. Finally, \citet{kannan2019downstream} highlight another interesting dimension in the intersection of mechanism design, machine learning and policy: downstream effects of affirmative action. The paper draws upon the mechanism design literature to explore how the effects of different policy schemes propagate across education and labor when sequential decisions are made by utility-maximizing agents with potentially conflicting goals (universities vs. employers). They show that fairness notions such as equal opportunity and (strong) irrelevance of group membership can be achieved only in the extreme case where the college does not report grades to the employer. Thus, the problem of intersectionality occurs again: in complex decision pipelines where different fairness metrics may be required yet it may be infeasible to satisfy all simultaneously \citep{kleinberg2017inherent}, the question of what is an acceptable trade-off between utility maximization and various notions of fairness persists. \subsection{Labor markets and gig economy} Discrimination has been a perennial problem in labor markets. Decades of research has shown that hiring decisions are subject to bias against disadvantaged communities \citep{bertrand2004emily, wenneras2001nepotism, quillian2017meta}. More recently, techniques from both machine learning and mechanism design have been brought to bear in the labor market, and in particular, the gig economy, leading to a fresh wave of concern that the persistent discrimination found in traditional labor markets will manifest itself in new and unexpected ways. In particular, we focus on two use cases: employee selection and employee evaluation. Both of these use cases blend techniques from machine learning and mechanism design, and, as we will argue, it is impossible to adequately deal with issues of discrimination and bias without drawing upon ideas from both fields. Emerging data-driven techniques for employee selection have begun to employ techniques from machine learning to evaluate and sort candidates \citep{bogen2018help,raghavan2020mitigating,sajjadiani2019using}. While some contend that quantitative tools might help to reduce discrimination \citep{cowgill2018bias}, others warn that hiring discrimination will not be solved by machine learning alone \citep{gosh2017ai}. However, hiring cannot be treated as a purely predictive problem; it requires consideration of factors like allocation, incentives, externalities, and competition, all of which feature more prominently in the mechanism design literature. Consider, for example, the case of salary prediction \citep{chen2018linkedin}: platforms like LinkedIn use machine learning techniques to predict a job's salary. While this might appear to be a straightforward application of machine learning, it creates strategic incentives that may produce unintended consequences. If a candidate applies to a new position, their potential employer may be able to infer their current salary based on these predictions, enabling the new employer to reduce the salary they offer. Similar consequences can arise from efforts to predict a candidate's likelihood to leave a job \citep{jayaratne2020predicting,sajjadiani2019using}. Moreover, many predictions about candidates are ultimately used in contexts where there is a limited hiring capacity. As a result, predictions about candidates are often later used to rank or filter candidates---a type of mechanism. To avoid the explicit consideration of demographic characteristics, efforts to ensure that candidates are treated fairly (usually through constraints similar to demographic parity) often come at the prediction stage \citep{raghavan2020mitigating}, but fail to make guarantees about the eventual outcomes produced by downstream mechanisms. A more complete effort to prevent discrimination in algorithmic hiring pipelines must leverage the flexibility provided by machine learning to implement anti-discrimination solutions while taking into account the effects of downstream hiring mechanisms. Beyond issues of discrimination in hiring, recent technological developments have fundamentally changed how labor markets work, particularly with regards to the gig economy, and thus led to a plethora of recent works in this space. For example, \citet{rosenblat2017discriminating} and \citet{monachou2019discrimination} describe how mechanisms that use customer ratings to evaluate workers can internalize customers' discriminatory tastes. \citet{barzilay2016platform} call attention to the ways in which platform design can be used to create or reduce wage disparities. Similarly, \citet{hannak2017bias} document the existence of linguistic and other biases in employers' reviews for gig workers on two online labor platforms, TaskRabbit and Fiverr, and the negative effects of gender and racial bias on the number of reviews, rating, search and ranking. \citet{edelman2017racial} find evidence of discrimination against African-American guests on Airbnb, highlighting the role that Airbnb's design choices play in facilitating this discrimination. Spurred in part by this work, Airbnb recently launched an initiative to study racial discrimination on their platform \citep{basu2020measuring}. Crucially, this body of work combines insights from economics, mechanism design, and machine learning to better understand how discrimination can manifest in the gig economy. \subsection{Criminal justice} Recent popularity of the use of machine learning techniques in prescriptive settings has motivated several attempts to analyze the fairness aspects of predictive and statistical models, especially in the context of a critical application domain like criminal justice. Unsurprisingly, relying on such models in practice can end up reinforcing underlying racial biases, as it has been shown in studies about neighbourhood surveillance \citep{ainow2019report} and recidivism prediction \citep{angwin2016machine}. The latter ProPublica study has raised a heated discussion leading many to advocate that the deployed system, independent of the larger criminal justice system in which it is situated, is plainly unfair. While that was apparent in this instance, a rigorous explanation was not trivial; several responses argued that their claims of discrimination were mainly caused by differences in methodology, like the statistical measure of discrimination \citep{dieterich2016compas, flores2016false}. Since the deployment of predictive models in the criminal justice system is a contested idea \citep{harcourt2008against}, knowledge about their potential advantages and pitfalls regarding fairness is crucial in order to perform a fruitful debate on their applicability. As already mentioned in Section 2.1, the proposed theoretical notions of fairness seem to present significant trade-offs \citep{jung2020fair, corbett2018measure} while some of them are impossible to simultaneously satisfy \citep{chouldechova2017fair,kleinberg2017inherent}. Those contradictions naturally raise a major question regarding the criminal justice system and the automated decision-making systems within it: \textit{What do people consider truly fair?} Since there doesn't seem to be a one-size-fits-all answer to this question, a natural step forward is a more participatory approach to the definition of (context-dependent) notions of fairness. As discussed in Section~\ref{sec:humanperceptions}, some first approaches have been made \citep{woodruff2018qualitative, lee2018understanding, grgic2018human, green2019disparate, srivastava2019mathematical, saha2020measuring} towards studying human perceptions of fairness but questions regarding who are the relevant stakeholders in criminal justice, what notions are more appropriate in that field and how to aggregate preferences still need to be answered. But even under a ``perfect'' fairness definition, humans involved in the judicial decision-making process might be inherently biased. In this context, machine learning can be leveraged to mitigate these human biases \citep{valera2018enhancing} and mechanism design can be proven useful in studying the welfare implications and effects on inequality of decisions in criminal justice. Moreover, merely focusing on the task of fair recidivism prediction might be considered an oversimplification because the assessment of a ML system regarding innocence and guilt ignores both human incentives in the criminal justice pipeline and the humanity of the criminal justice system as a whole. In the United States, a defendant only needs to prove their innocence when their case goes to trial in court. Yet, 95\% of felony convictions in the United States are obtained through guilty pleas \citep{guiltypleaproblem}, and 18\% of known exonerees pleaded guilty or did not contest to crimes they did not commit. Machine learning techniques could be applied in conjunction with the critical perspective of mechanism design to better comprehend the racial disparities in both sentence and charge bargaining, as documented by \citet{berdejo2018criminalizing}. It is worth noting that any theoretical techniques used to examine the criminal justice system should be wary of the common mechanism design assumption that people are rational expected utility maximizing agents, while desperation, selflessness, or fear often counter this assumption in the real world. Though enlightening, theoretical understanding of fairness in risk assessment and its aforementioned aspects is not sufficient to suggest adopting the use of such systems. The ultimate decision should be made by the respective stakeholders, considering the practical issues that need to be addressed \citep{koepke2018danger} and the particular context in which risk assessment tools are utilized \citep{stevenson2018assessing}. \subsection{Health insurance markets} Interactions between machine learning and mechanism design are salient for fairness in healthcare. For example, prior work studied how machine learning formulations may underpredict black patients' health care needs \citep{obermeyer2019dissecting}. Here, we draw attention to problems at the intersection of the two fields in health insurance markets. The Patient Protection and Affordable Care Act (ACA) \citep{ACA} was designed in part to defuse health-insurer incentives to refuse or avoid coverage to individuals with higher healthcare costs (i.e., selection incentives) \citep{cunningham2012risk}. One way the ACA addresses this is through risk-adjustment based transfer payments: premiums are transferred from plans with lower expected costs to plans with higher expected costs, compensating insurers and fairly spreading costs. Thus issues of fairness in mechanism design inhere at the policy-design level. A key component of risk adjustment is estimating individual actuarial risk: inaccurate estimates can create selection incentives for insurers. The Centers for Medicare \& Medicaid Services' Hierarchical Condition Category (HCC) model is a widely-used risk adjustment model \citep{cms2018risk,zink2020fair}. The HCC predicts an enrollee's expected costs using demographic and diagnosis information; the HCC is therefore group-aware for some protected classes (e.g., sex, age), but is otherwise group-unaware, particularly to groups of enrollees with specific healthcare patterns related (but not limited) to diagnoses, treatments, and prescription-drug use. Although there is evidence that the HCC accurately predicts expected costs for many groups of enrollees, there is also evidence that the HCC makes systematic errors for some groups and that insurers often engage in benefit design to exploit the resulting selection incentives \citep{jacobs2015using, geruso2019screening}. Thus, healthcare-policy designers, approaching the problem from a mechanism design perspective, encounter the lesson from fair machine learning that it is in general necessary to be group-aware. ML practitioners also encounter the lesson from mechanism design that it is necessary to take into account the strategic behavior of stakeholders. A natural machine-learning oriented response to the systematic error observed in the HCC could be to incorporate more information about enrollees into the model, but because the HCC data are provided by the health insurers, there are concerns that insurers or healthcare providers might then strategically upcode enrollees to favorably skew subsequent predictions \citep{cunningham2012risk}. Recent work seeks to address these issues in risk adjustment by incorporating fairness interventions to learn a regression model that equalizes systematic error across groups. The proposed fair regression models can bring average predicted costs significantly more in line with average historical costs without a commensurately large penalty to the traditional evaluation metric of $R^2$ \citep{zink2020fair}. We see each discipline's techniques applied in a component-wise fashion towards a competitive health-insurance market that achieves socially optimal outcomes. Notably, neither discipline can independently achieve this goal: selection incentives cannot be defused without accurate risk adjustment; behavior cannot be changed by predictions without appropriately designed incentives. \subsection{Determining creditworthiness} The Financial Technology (FinTech) industry increasingly decides to whom a (home, business) loan should be awarded, and at what interest rate. When one considers banks have finite liquid assets, determining an individual's creditworthiness quickly becomes one piece of a larger problem. \citet{saunders2019fintech} notes that FinTech can help streamline the application process for loans, among other benefits. However, concerns including disparate impacts of disadvantaged communities, overcharging the poor, the unintelligibility of such algorithms, and protection under consumer laws emerge from the use of machine learning. Overcharging the poor particularly appears to be in part a corollary of determining creditworthiness as a machine learning problem in isolation from mechanism design. In determining creditworthiness, the true label (ability to pay back the loan) faces two shortcomings: first, it is only observed if the loan is given, and second, it might be a function of the given interest rate. The Pew Research Center \citep{pew2017black} revealed 27.4\% of Black applicants and 19.2\% of Hispanic applicants were denied mortgages, compared with about 11\% of White and Asian applicants. Moreover, when granted a loan, 39\% of Black applicants were charged an interest rate over 5\%, compared to only 28\% of White applicants. This in turn makes repaying the loan more difficult, exacerbating financial insecurities resulting from historical financial and housing oppression, such as loan denial and redlining of neighborhoods. Resulting from the historical imbalance of loan acceptance \citep{rambachan2019bias,liu2018delayed}, \citet{kallus2018residual} observe that algorithms might still yield ``bias in, bias out'' phenomena, even with fairness constraints, and online machine learning approaches aim to face this issue by incentivizing exploration \citep{joseph2016fair,joseph2016fairness,raghavan2018externalities,celis2019controlling,schumann2019group,kilbertus2020fair}. As transparency increasingly becomes a legal obligation of financial institutions, such technology is particularly susceptible to disparities \citep{bartlett2019consumer}, largely because of two tensions shaped by the incentives of different stakeholders. First, individuals who gain insight about the institutions' decision-making processes, might have disproportionate recourse abilities, based on their current financial status and access to opportunity. Since financial institutions are typically for-profit organizations aiming to maximize their utility, \citet{milli2019social} note that a lack of strategyproofness can disproportionately harm disadvantaged groups in the population. The second tension arises from the fact that financial institutions are asked to find a balance between transparency towards customers and protection of their intellectual property \citep{milli2019model,barocas2020hidden}. \citet{tsirtsis2020decisions} argue that maximizing utility in this context may provide limited recourse to disadvantaged populations and they propose methods to counteract such disparities. Those tensions reinforce the need to incorporate the study of incentives in automated decision-making systems before they can be effectively used in financial environments. As \citet{saunders2019fintech} concludes their report: \emph{The key to FinTech is: Understand first. Proceed with caution.} \subsection{Social networks} Social networks have received scrutiny in the way they reinforce patterns of social inequality and discrimination \citep{mcpherson2001birds,calvo2004effects,dimaggio2011network,gundougdu2019bridging,okafor2020all}. Inequality at the level of individual connections is often reinforced by algorithms that use these connections for learning: in opinion diffusion \citep{fish2019gaps,ali2019discrimination,stoica2020seeding}, recommendation \citep{stoica2018algorithmic}, clustering \citep{chierichetti2017fair,kleindessner2019fair}, and others. Often, such inequality arises from the individual preference for establishing new connections as well as from pre-defined communities \citep{avin2015homophily}. Recent papers discuss these patterns through the lens of welfare economics or equilibrium strategies, with \citet{avin2018preferential} analyzing the utility function for which preferential attachment is the unique equilibrium solution in a social network. Thus, understanding the incentives behind network creation patterns is crucial for designing better algorithms that learn from relational data and tackling bias at its root cause, as Section~\ref{sec:longterm} teaches us Beyond this, several works argue that ranking and retrieval algorithms not only reinforce existing bias, but also cause changes in people's behavior \citep{o2016weapons}. To tackle this, a recent line of work takes into consideration the post-ranking and post-recommendation effects in a game-theoretical framework, considering users as players and assigning highly ranked/recommended items to a high pay-off. The lesson from Section 3.3 of modeling individuals as rational agents has started a whole subfield in recommendation systems, starting with \citet{bahar2015economic}, who focus on finding stable equilibria for which users get the best pay-off for their desired items. \citet{ben2018game} propose new methods, such as the Shapley mediator, to fulfill both fairness and stability conditions (as defined by mechanism design) in cases where content providers are strategic to maximize utility and assume a rational behavior of their users based on their preferences. To account for the incentives of users in post-recommendation settings, \citet{basat2017game,ben2015probability} account for users attempting to promote their own content in information retrieval, describing it as an `adversarial setting'. The main results point to an increase in general utility when accounting for such incentives, as non-strategic design presents limitations in truly fulfilling individual preferences. \citet{49323} directly tackle the problem of welfare by considering recommendations as a resource to be allocated. Incorporating the preferences of the users of a social network in a fair way is thus a subsequent question. Recent works \citep{chakraborty2019equality} tackle this by adapting tools from social choice theory, specifically, by proposing a voting mechanism called Single Transferable Vote to aggregate inferred preferences (votes) of users and achieve better recommendations. This kind of tools can be used to operate in adversarial settings, for example in non-personalised recommendation systems like Twitter or Youtube trending topics, which can be manipulated by flooding the network with bot-created content that can become viral. Methods from mechanism design can be used to protect against strategic behavior that could game the underlying machine learning system, as well as incorporate individual preferences in a meaningful way. \section{Conclusion}\label{sec:conclusion} While the literature is rapidly growing, many open questions at the intersection of mechanism design and machine learning remain, motivating the need for developing a \textit{lingua franca} of fairness, identifying knowledge gaps and lessons, and ultimately bridging the two fields to work towards a fair pipeline in decision making. However, both communities must acknowledge that making the pipeline ``fair'' from a technical perspective does not mean the system is \textit{ipso facto} perfect or just. More interdisciplinary work is needed beyond mechanism design and machine learning to create interventions that improve access to sociotechnical systems and design algorithms for critical application domains. ~\\\noindent\textbf{Acknowledgments.} The authors would like to thank Rediet Abebe, Itai Ashlagi, Rafael Frongillo, Nikhil Garg, Jon Kleinberg, Hannah Li, Irene Lo, Francisco Marmolejo-Cossio, Angela Zhou, and anonymous reviewers of the ACM FAccT conference for helpful comments and suggestions. This project has been part of the MD4SG working group on Bias, Discrimination, and Fairness. This material is based upon work supported by the National Science Foundation Graduate Research Fellowship under Grants No. 1650115 (Finocchiaro), 1644869 (Maio), 1650441 (Raghavan) and 1761810 (Stoica). Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation. Stoica acknowledges support from the J.P. Morgan AI research fellowship. Monachou acknowledges support from the Krishnan-Shah Fellowship and the A.G. Leventis Foundation Grant. Patro is supported by a fellowship from Tata Consultancy Services Research. Tsirtsis acknowledges support from the European Research Council (ERC) under the European Union’s Horizon 2020 research and innovation programme (grant agreement No. 945719). \small \bibliographystyle{plainnat}
{'timestamp': '2021-03-08T02:07:05', 'yymm': '2010', 'arxiv_id': '2010.05434', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05434'}
arxiv
\section{Introduction} Building on the theory of causal discovery from observational data, we propose a method to learn linear non-Gaussian structural equation models with hidden variables. Importantly, we allow each hidden variable to be a parent of multiple of the observed variables, and we represent this graphically via {\em multi-directed} edges. Therefore, given observational data, we seek to find an acyclic mixed graph whose vertices correspond to the observed variables, and which has directed and multi-directed edges. \begin{figure}[H] \centering \begin{subfigure}[b]{0.31\textwidth} \centering \includegraphics[width=1.1\textwidth]{ExampleDAG.pdf} \caption{Example DAG.} \label{fig:1a} \end{subfigure} \hfill \begin{subfigure}[b]{0.31\textwidth} \centering \includegraphics[width=0.82\textwidth]{MultiDAG.pdf} \caption{Mixed graph.} \label{fig:1b} \end{subfigure} \hfill \begin{subfigure}[b]{0.31\textwidth} \centering \includegraphics[width=0.65\textwidth]{BidirectedDAG.pdf} \caption{Mixed graph.} \label{fig:1c} \end{subfigure} \caption{The graph in Figure~\ref{fig:1a} is directed acyclic. After marginalization of vertices 1 and 5, the resulting mixed graph with directed and bidirected edges only is that in Figure~\ref{fig:1c}. If we allow multidirected edges, we can capture the hidden variable structure better via the graph in Figure~\ref{fig:1b}, which also has a 3-directed edge.} \label{fig:1} \end{figure} Consider an acylic mixed graph $G = (V, \mathcal D, \mathcal H)$, where $V = \{1, \ldots, p\}$ is the set of vertices, $\mathcal D$ is the set of directed edges, and $\mathcal H$ is the set of multi-directed edges, i.e., $\mathcal H$ consists of tuples of vertices such that the vertices in each tuple have a hidden common cause. The graph in Figure~\ref{fig:1c} has only directed and bidirected edges, while the one in Figure~\ref{fig:1b} also has a 3-directed edge. Both of these mixed graphs represent the directed acyclic graph in Figure~\ref{fig:1a} with the variables 1 and 5 unobserved. Representing hidden variables via such edges is quite commonly used for causal discovery~\cite{handbook}. We restrict our attention to the class of {\em Linear Structural Equation Models (LSEMs)}. A mixed graph $G$ gives rise to a linear structural equation model, which is the set of all joint distributions of a random vector $X=(X_1,\ldots, X_p)$ such that the variable $X_i$ associated to vertex $i$ is a linear function of a noise term $\epsilon_i$ and the variables $X_j$, as $j$ varies over the set of parents of $i$, denoted pa$(i)$, (i.e., the set of all vertices $j$ such that $j\to i \in E$). Thus, $$X_i = \sum_{j\in\text{pa}(i)} b_{ij}X_j + \varepsilon_i, \,\, i\in V.$$ When the variables $X_1,\ldots, X_p$ are Gaussian, we are only able to recover the mixed graph up to Markov equivalence from observational data~\cite{handbook, Lauritzen}. When the variables are non-Gaussian, however, it is possible to recover the full graph from observational data. This line of work originated with the paper~\cite{Shimizu2006} by Shimizu et al. in which a linear non-Gaussian structural equation model corresponding to a direced acyclic graph (DAG), i.e., a graph without confounders, can be identified from observational data using independent component analysis (ICA). Instead of ICA, the subsequent DirectLiNGAM~\cite{Shimizu2011} and Pairwise LiNGAM~\cite{PairwiseLiNGAM} methods use an iterative procedure to estimate a causal ordering; Wang and Drton~\cite{WangDrton} give a modified method that is also consistent in high-dimensional settings in which the number of variables $p$ exceeds the sample size $n$. Hoyer et al.~\cite{Hoyer} consider the setting where the data is generated by a linear non-Gaussian acyclic model (LiNGAM), but some variables are unobserved. Their method, like ours, recovers an acyclic mixed graph with multidirected edges. However, it uses overcomplete ICA and requires the number of latent variables in the model to be known in advance. Furthermore, current implementations of overcomplete ICA algorithms often suffer from local optima and can't guarantee convergence to a global one. To avoid using overcomplete ICA while still identifying unobserved confounders, Tashiro et al.~\cite{Parcellingam} propose a procedure, called ParcelLiNGAM, which tests subsets of observed variables. Wang and Drtong~\cite{BANG}, however, show that this procedure works whenever the graph is ancestral, and propose a new procedure, called BANG, which uses patterns in higher-order moment data, and can identify {\em bow-free acyclic mixed graphs}, a set of mixed graphs much larger than the set of ancestral graphs. The BANG algorithm, however, recovers a mixed graph which only contains directed and bidirected edges. Our method builds on the BANG procedure. We can identify a bow-free acyclic mixed graph, and, in addition, join bidirected edges together into a multi-directed edge whenever more than two of the observed variables have a hidden common cause. The rest of the paper is organized as follows. In Section~\ref{sec:2} we give the necessary background on mixed graphs, linear structural equation models, and multi-treks. In Section~\ref{sec:3}, we present our algorithm (MBANG) and we prove that it recovers the correct graph as long as the empirical moments are close enough the the population moments. In Section 4 we present numerical results, including simulations of different graphs and error distributions, and an application of our algorithm to a real dataset. We conclude with a short discussion in Section 5. \section{Background}\label{sec:2} In this section we introduce the key concepts that we use throughout the paper, including mixed graphs with multi-directed edges, linear structural equation models, multi-treks and cumulants. \subsection{Mixed graphs with multi-directed edges} The notion of a mixed graph is widely used in graphical modelling, where bidirected edges depict unobserved confounding. In this paper a mixed graph is also allowed to contain multi-directed edges to depict slightly more complicated unobserved confounding. \begin{definition} (a). We call $G = (V, \mathcal D, \mathcal H)$ a {\em mixed graph}, where $V = \{1,\ldots, p\}$ is the set of vertices, $\mathcal D\subseteq V\times V$ is the set of directed edges, and $\mathcal H$ is the set of multi-directed edges (all $k$-directed edges for $k\geq 2$). (see part (b)). (b). For $k\geq 2$, a {\em $k$-directed} (or {\em multi-directed}) edge between distinct nodes $i_1,\ldots, i_k\in V$, denoted by $(i_1,\ldots, i_k)$, is the union of $k$ directed edges with the same hidden source and sinks $i_1,\ldots, i_k$ respectively. Multi-directed edges are unordered. \begin{figure}[H] \begin{subfigure}{0.5\textwidth} \begin{center} \vspace{0.35cm} \includegraphics[width=0.6\textwidth]{bidirectedEdge.pdf} \caption{A 2-directed (or bidirected) edge between $i_1,i_2$.} \label{fig:2-edge} \end{center} \end{subfigure} \begin{subfigure}{0.5\textwidth} \begin{center} \includegraphics[width=0.6\textwidth]{4-directedEdge.pdf} \caption{A 4-directed edge between $i_1,i_2,i_3,i_4$.} \label{fig:4-edge} \end{center} \end{subfigure} \caption{Examples of multi-directed edges.} \end{figure} \end{definition} Our method is able to recover {\em bow-free} {\em acyclic} mixed graphs. A mixed graph is bow-free if it does not contain a {\em bow}, and a bow consists of two vertices $i,j\in V$ such that there is both a directed and a multidirected edge between $i$ and $j$. In other words, $i\to j\in\mathcal D$ and there exists $h\in\mathcal H$ such that $i,j\in h$. A mixed graph is acyclic if it does not contain any {\em directed cycles}, where a directed cycle is a sequence of directed edges of the form $i_1\to i_2, i_2\to i_3,\ldots, i_\ell \to i_1$. \begin{figure}[H] \begin{subfigure}{0.5\textwidth} \begin{center} \includegraphics[width=0.4\textwidth]{bow.pdf} \caption{A bow between $i$ and $j$.} \label{fig:bow} \end{center} \end{subfigure} \begin{subfigure}{0.5\textwidth} \begin{center} \includegraphics[width=0.4\textwidth]{cycle.pdf} \caption{A cycle.} \label{fig:cycle} \end{center} \end{subfigure} \caption{Examples of a bow and a cycle.} \end{figure} Acyclic mixed graphs with potential multidirected edges are all one can hope to recover from observational data. Suppose for a moment that we have data coming from a directed acyclic graph (DAG) where a subset of the variables is unobserved, e.g., consider the DAG in Figure~\ref{fig:originalModel}, where we only observe variables 1, 4, and 5. Hoyer et al.~\cite{Hoyer} show that any directed acyclic graphical model in which some of the variables are unobserved is observationally and causally equivalent to a unique {\em canonical model}, where a canonical model is a non-Gaussian Linear Structural Equation Model corresponding to an acyclic mixed graph $G=(V, \mathcal D, \mathcal H)$ such that none of the latent variables have any parents, and each latent variable has at least two children. This means, that the distribution of the observed variables in the original model is identical to that in the canonical model, and causal relationships of observed variables in both models are identical. Therefore, we can focus our attention on the set of canonical models, which can be represented precisely by acyclic mixed graphs with multi-directed edges. The graph in Figure~\ref{fig:canonical} is the canonical model corresponding to the one in Figure~\ref{fig:originalModel}. \begin{figure}[H] \begin{subfigure}{0.5\textwidth} \begin{center} \includegraphics[scale = 0.6]{canonical1.pdf} \caption{Original model}\label{fig:originalModel} \label{fig: origin} \end{center} \end{subfigure} \begin{subfigure}{0.5\textwidth} \begin{center} \includegraphics[scale = 0.6]{canonical2.pdf} \caption{Canonical model} \label{fig:canonical} \end{center} \end{subfigure} \caption{An example of two observationally and causally equivalent models from~\cite{Hoyer}.} \label{fig:canonExample} \end{figure} \subsection{Linear Structural Equation Models} Let $G=(V, \mathcal D, \mathcal H)$ be an acyclic mixed graph as defined in the previous section. It induces a statistical model, called a {\em linear structural equation model}, or {\em LSEM}, for the joint distribution of a collection of random variables $(X_i, i \in V )$, indexed by the graph’s vertices. The model hypothesizes that each variable is a linear function of its parent variables and a noise term $\varepsilon_i$: \begin{align}\label{LSEM}X_i = b_{0i} + \sum_{j\in\text{pa}(i)} b_{ji}X_j + \varepsilon_i , i \in V, \end{align} where $\text{pa}(i) = \{j\in V: j\to i\in\mathcal D\}$ is the set of parents of vertex $i$. The variables $\varepsilon_i, i\in V$ are assumed to have mean 0, and the coefficients $b_{0i}$ and $b_{ji}$ are unknown real parameters. Since we can center the variables $X_i$, we assume that the coefficients $b_{0i}$ are all equal to 0. In addition, the multi-directed edge structure of $G$ defines dependencies between the noise terms $\varepsilon_i$, that is, if $i$ and $j$ are not connected by a multi-directed edge, then $\varepsilon_i$ and $\varepsilon_j$ are independent variables. In particular, if $G$ is a DAG (directed acyclic graph), i.e., it does not have any multi-directed edges, then all noise terms $\varepsilon_i$ are mutually independent. Typically termed a system of structural equations, the system~\eqref{LSEM} specifies cause-effect relations whose straightforward interpretability explains the wide-spread use of the models~\cite{Pearl, SGS00}. We can rewrite the system~\eqref{LSEM} as $$X = BX + \varepsilon,$$ where $X = (X_1,\ldots, X_p)^T$, $B = (b_{ij})$ is the coefficient matrix satisfying $b_{ij} = 0$ whenever $i\to j\not\in \mathcal D$, and $\varepsilon$ is the noise vector. Note that since $G$ is assumed to be acyclic, we can permute the coefficient matrix $B$ so that it is a lower triangular matrix. Therefore, the matrix $I-B$ is invertible, and the system~\eqref{LSEM} can further be rewritten as $$X = (I-B)^{-1}\varepsilon.$$ \subsection{Cumulants and the multi-trek rule} We recall the notion of a cumulant tensor for a random vector~\cite{ComonJutten}. \begin{definition} Let ${Z}=(Z_1,\cdots,Z_p)$ be a random vector of length $p$. The $k$-th cumulant tensor of ${Z}$ is defined to be a $p\times \cdots\times p$ ($k$ times) table, $\mathcal C^{(k)}$, whose entry at position $(i_1,\cdots, i_k)$ is \begin{align*} \mathcal C^{(k)}_{i_1,\ldots, i_k}=\sum_{(A_1,\cdots,A_L)}(-1)^{L-1}(L-1)!\, \mathbb{E}\left[\prod_{j\in A_i}Z_j\right]\cdots\mathbb{E}\left[\prod_{j\in A_L}Z_j\right], \end{align*} where the sum is taken over all partitions $(A_1,\cdots, A_L)$ of the set $\{i_1,\cdots, i_k\}$. \end{definition} Note that if each of the variables $Z_i$ has zero mean, then we can restrict the summing over partitions for which each $A_i$ has size at least two. For example: \begin{align*} \mathcal C^{(4)}_{i_1,i_2,i_3,i_4}&=\mathbb{E}(Z_{i_1}Z_{i_2}Z_{i_3}Z_{i_4})-\mathbb{E}(Z_{i_1}Z_{i_2})\mathbb{E}(Z_{i_3}Z_{i_4})-\mathbb{E}(Z_{i_1}Z_{i_3})\mathbb{E}(Z_{i_2}Z_{i_4})+\\ &\quad \mathbb{E}(Z_{i_1}Z_{i_4})\mathbb{E}(Z_{i_2}Z_{i_3}) \end{align*} We now recall the notion of a multi-trek from~\cite{multiTrek}. \begin{definition} A $k$-trek in a mixed graph $G=(V, \mathcal D, \mathcal H)$ between $k$ nodes $i_1,i_2,\cdots, i_k$ is an ordered collection of $k$ directed paths $(P_1,\cdots, P_k)$ where $P_j$ has sink $i_j$ and either $P_1,\cdots, P_k$ have the same source of vertex, or there exists a multi-directed edge $h\in\mathcal H$ such that the sources of $P_1,\ldots, P_k$ all lie in $h$. \end{definition} \begin{figure}[H] \begin{subfigure}{0.5\textwidth} \centering \includegraphics[width=0.5\textwidth]{4-trek.pdf} \caption{A 4-trek between $i_1,i_2,i_3,i_4$.} \label{fig:my_label} \end{subfigure} \begin{subfigure}{0.5\textwidth} \centering \includegraphics[width=0.45\textwidth]{4-trekHidden.pdf} \caption{A 4-trek between $i_1,i_2,i_3,i_4$.} \label{fig:my_label} \end{subfigure} \caption{Examples of multi-treks.} \end{figure} The following consequence of the {\em multi-trek rule}~\cite{multiTrek} connects cumulants of LSEMs to multi-treks. \begin{theorem}[\cite{multiTrek}]\label{thm:multiTrek} Let $G = (V, \mathcal D, \mathcal H)$ be an acyclic mixed graph, and let $i_1,\ldots, i_k\in V$. Then, $$\mathcal C^{(k)}_{i_1,\ldots, i_k} = 0$$ for the $k$-th cumulant tensor $\mathcal C^{(k)}$ of any random vector whose distribution lies in the LSEM corresponding to $G$ if and only if there is no $k$-trek between $i_1,\ldots, i_k$ in $G$. \end{theorem} \section{Main Result}\label{sec:3} In this section we present our algorithm and we show that it recovers the correct graph given enough samples. In the chart below we illustrate how the algorithm works when applied to observational data coming from the graph in Figure~\ref{fig:1a}. \begin{figure}[] \centering \centering \includegraphics[scale = 0.6]{flowChart.pdf} \caption{} \label{fig: flow} \end{figure} Given a $p\times n$ data matrix $Y$ whose columns are i.i.d. sampels from a LSEM on an unknown bow-free acyclic mixed graph $G=(V, \mathcal D, \mathcal H)$ with an unknown direct effects matrix $B$, we aim to recover the graph $G$ and the matrix $B$. The first step is to apply the BANG procedure~\cite{BANG} and obtain the coefficient matrix $B$ together with a bow-free acyclic mixed graph $G_1 = (V, \mathcal D, \mathcal B)$ which contains directed and bidirected edges only. The bidirected edges $\mathcal B$ are obtained from $\mathcal H$ by replacing each multi-directed edge $h=(i_1,\ldots, i_k)\in\mathcal H$ by $\binom k2$ bidirected eges, one for each pair $i_s, i_t\in\{i_1,\ldots, i_k\}$. We call such a set $\mathcal B$ the {\em bidirected subdivision} of $\mathcal H$. We then, "remove" the directed edges by removing the direct effects given by $B$. This is done by replacing the original data matrix $Y$ with $X = Y-BY$. This new matrix $X$ can be thought of as observations from a LSEM corresponding to the acyclic mixed graph $G'=(V, \emptyset, \mathcal H)$ which is the same as $G$ with the directed edges removed. However, we only know the bidirected subdivision $\mathcal B$ of $\mathcal H$. Finally, using the higher order cumulants of $X$ and a clique-finding algorithm on the graph $G_1' = (V, \emptyset, \mathcal B)$, we identify all multi-directed edges in $\mathcal H$. The algorithm is summarized below. \begin{algorithm}[H] \caption{MBANG procedure}\label{Alg:1} \begin{algorithmic}[1] \STATE Input: $Y\in \mathbb{R}^{p\times n}$ arising from an unknown LSEM on $G=(V, \mathcal D, \mathcal H)$ with unknown direct effects matrix $B$. \STATE Apply the BANG procedure to estimate the coefficient matrix $B$ and the mixed graph $G_1=(V, \mathcal D, \mathcal B)$. \STATE Let $X=Y-BY$ be the new observation matrix, corresponding to the graph $G'=(V, \emptyset, \mathcal H)$ which has no directed edges. \STATE Initiate $R=Q=\varnothing$, $P=\{1,2,...,p\}$. \STATE Apply {Algorithm~\ref{alg:2}} to $X, G_1' = (V, \emptyset, \mathcal B), R,P$ and $Q$ to recover the set $\mathcal H$ of multidirected edges. \STATE Output: the graph $G = (V, \mathcal D, \mathcal H)$ and the matrix $B$. \end{algorithmic} \end{algorithm} Algorithm~\ref{alg:2} finds those multi-directed edges that contain the most vertices and are consistent with the cumulant structure of the data matrix $X$. It is based on the Bron-Kerbosh algorithm~\cite{BronKerbosch} for finding all cliques in an undirected graph, applied to the bidirected edges in $G_1' = (V, \emptyset, \mathcal B)$. \subsection{The BANG procedure} In this section we briefly describe the {BANG Procedure}~\cite{BANG}. It is an algorithm which takes as input a $p\times n$ data matrix $Y$, and returns a \textit{bow-free acyclic mixed graph} $G$ which contains directed and bidirected edges only, consistent with $Y$ as well as a direct effects matrix $B$. \par Suppose the observed data is drawn from a LSEM whose corresponding graph is the one in Figure~\ref{fig:bangExample}. Figure \ref{fig:bangFlowChart} shows how the {BANG algorithm} works. It first identifies sibling and ancestor relations, and then it distinguishes parent and non-parent ancestors. Recall that two vertices are {\em siblings} if there is a multi-directed edge between them, a vertex $i$ is a {\em parent} of a vertex $j$ if there is a directed edge $i\to j$, and a vertex $i$ is an {\em ancestor} of a vertex $j$ if there is a direted path $i\to i_0\to\cdots\to i_k\to j$. \begin{figure}[H] \centering \begin{subfigure}{0.25\textwidth} \vspace{5cm} \hspace{-0.2cm} \hspace{0.5cm}\includegraphics[width=0.6\textwidth]{bangExample.pdf} \caption{Graph example} \label{fig:bangExample} \end{subfigure} \begin{subfigure}{0.65\textwidth} \hspace{1cm}\includegraphics[width=0.95\textwidth]{bangFlowChart.pdf} \caption{BANG flowchart} \label{fig:bangFlowChart} \end{subfigure} \caption{BANG algorithm example} \end{figure} However, the {BANG algorithm} returns {bow-free acyclic mixed graphs} in which the latent variable structure is recorded using bidirected edges only, i.e., it recovers the bidirected subdivision of the true set of multi-directed edges $\mathcal H$. This means it cannot determine whether more than two vertices have a common cause. We resolve this problem using cumulant information. \begin{figure}[] \begin{subfigure}{\linewidth} \centering \includegraphics[scale = 0.5]{bangExample2.pdf} \caption{Case 1} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[scale = 0.5]{bangExample1.pdf} \caption{Case 2} \end{subfigure} \caption{The same bidirected edge structure depicts two different hidden variable models.} \label{fig: bangLimit} \end{figure} \subsection{Finding the multidirected edge structure} Consider the two models in Figure \ref{fig: bangLimit}. By Theorem \ref{thm:multiTrek}, we know that $\mathcal{C}^{(3)}_{2,3,4}=0$ in Case 1 whereas $\mathcal{C}^{(3)}_{2,3,4}\neq 0$ in Case 2. In other words, the exact model can be recovered by testing whether $\mathcal{C}^{(3)}_{2,3,4}=0$. \par More generally, as depicted in Figure~\ref{fig: flow}, we first apply the BANG algorithm to the data marix $Y\in\mathbb R^{p\times n}$ arising from a LSEM on $G=(V, \mathcal D, \mathcal H)$, to obtain an estimate of the direct effects matrix $B$ and the bow-free acyclic mixed graph $G_1=(V, \mathcal D, \mathcal B)$ with directed and bidirected edges only, where there is a bidirected edge between $i$ and $j$ in $G_1$ if and only if there is a multidirected edge in $G$ containing both $i$ and $j$, i.e., $\mathcal B$ is the bidirected subdivision of $\mathcal H$. Then, we form a new data matrix $X=Y-BY$ and we consider the graph $G' = (V, \emptyset, \mathcal H)$ which contains only multi-directed edges. In other words, the data matrix $X$ can be thought of as a matrix of samples coming from a LSEM on the graph $G'$. However, we only know the graph $G_1' = (V, \emptyset, \mathcal B)$. The bidirected edges $\mathcal B$ recovered by the BANG algorithm can now be "merged" together to obtain the true multi-directed edge structure $\mathcal H$. Since $G_1'$ contains only bidirected edges, we look for all cliques (of bidirected edges) $\{i_1,\ldots, i_k\}$ in $G'$ such that $\mathcal C^{(k)}_{i_1,\ldots, i_k}\neq 0$, where $\mathcal C^{(k)}$ is the $k$-th cumulant of $X$. We do this by adapting the Bron-Kerbosch algorithm~\cite{BronKerbosch}, which is used for finding all cliques in an undirected graph. \begin{algorithm}[H] \caption{Determine Multidirected Edges} \label{alg:2} \begin{algorithmic}[1] \STATE Input: $X\in \mathbb{R}^{p\times n}, G_1'=(V, \emptyset, \mathcal B), R,P$ and $Q$. Denote the elements of $R$ to be $i_1,...,i_k$. \IF{$P$ and $Q$ are both empty} \STATE Report $R$ as a multidirected edge. \ENDIF \FORALL{vertex $v\in P$} \IF{$N(v) \neq \varnothing$, where $N(v)$ is the set of vertices adjacent to $v$ in $\mathcal B$} \IF{$\mathcal{C}^{(k+1)}_{i_1,\cdots,i_k,v} \neq 0$ or $\exists$ $j \in \{i_1,\cdots,i_k\}$ s.t. $\mathcal{C}^{(k+2)}_{i_1,\cdots,i_k,v,j}\neq 0$}\label{lst: line: condition} \STATE call Algorithm~\ref{alg:2}$(X, R\cup \{v\}, P\cap N(v),Q\cap N(v))$ \ENDIF \ENDIF \STATE $P=P\backslash \{v\}$ \STATE $Q = Q\cup \{v\}$ \ENDFOR \end{algorithmic} \label{alg:multiedge} \end{algorithm} Algorithm~\ref{alg:2} is a direct modification of the Bron-Kerbosch algorithm~\cite{BronKerbosch}. It is a recursive algorithm, that maintains three disjoint sets of vertices $R, P, Q \subset V$, and aims to output all cliques in the graph which contain all vertices in $R$, do not contain any of the vertices in $Q$, and could contain some of the vertices in $P$. The only addition to the Bron-Kerbosch algorithm that Algorithm~\ref{alg:2} does is the test of whether or not specific cumulants are nonzero in Line 7. In practice, since Theorem \ref{thm:multiTrek} holds for generic distributions, sometimes random variables consistent with a model that has a multi-directed edge between $i_1,\ldots, i_k$ may still have a zero cumulant. For example, if $i_1$, $i_2$, and $i_3$ are all caused by a hidden parent variable whose distribution is symmetric around $0$, then $\mathcal{C}^{(3)}_{i_1,i_2,i_3}=0$. To solve this problem, we relax the criterion $\mathcal{C}^{(k)}_{i_1,\cdots,i_k} \neq 0$. In our implementation, we also check if there exists $j\in\{i_1,\ldots, i_k\}$ such that $\mathcal{C}^{(k+1)}_{i_1,\cdots,i_k,j}\neq 0$. If there is a multidirected edge $h$ such that $i_1,\ldots, i_k\in h$ but due to non-genericity of the model $\mathcal C^{k}_{i_1,\ldots, i_k} =0$, we find that often times $\mathcal{C}^{(k+1)}_{i_1,\cdots,i_k,j}\neq 0$ which allows us to reach the correct conclusion. \subsection{Theoretical results} In this section we show that Algorithm~\ref{Alg:1} recovers the correct bow-free acyclic mixed graph given enough samples. We begin with a population moment result. \begin{theorem}\label{thm: alg} Suppose $Y$ is generated from a linear structural equation model corresponding to a bow-free acyclic mixed graph $G=(V, \mathcal D, \mathcal H)$. Then for a generic choice of the coefficient matrix $B$ and generic error moments, when given the population moments of $Y$, Algorithm~\ref{Alg:1} produces the correct graph $G$. \end{theorem} \begin{proof} Algorithm~\ref{Alg:1} first apples the BANG procedure to produce a \textit{bow-free acyclic mixed graph} $G_1 = (V, \mathcal D, \mathcal B)$ containing bi-directed edges and directed edges only as well as the coefficient matrix $B$. In~\cite{BANG} the authors show that the BANG algorithm recovers the correct bow-free acyclic mixed graph (with directed and bidirected edges only) and the correct coefficient matrix $B$. Note that this means that the graph $G_1$ will have a bidirected edge $b\in \mathcal B$ between two nodes $i$ and $j$ which are part of a multi-directed edge $h\in\mathcal H$ in $G$. Consider the data matrix $X=Y-BY$ which corresponds to a graph $G' = (V, \emptyset, \mathcal H)$ obtained by removing all directed edges in $G$, and the graph $G_1'=(V, \emptyset, \mathcal B)$ obtained from $G_1$ by removing all directed edges. Our task is to merge together some of the bidirected edges in $G_1'$ in order to obtain the graph $G'$. There is a multi-directed edge between $i_1,\ldots, i_k$ in $G'$ (or, equivalently, in $G$), if and only if any two of $i_1,\ldots, i_k$ are joined by a bidirected edge in $G_1'$, i.e., they will form a clique, AND \begin{align}\label{eq:nonZeroCumulant} \mathcal{C}^{(k)}_{i_1,\cdots, i_k}\neq 0, \end{align} where $\mathcal{C}^{(k)}$ is the $k$-th cumulant of $X$ (assuming the distribution of $X$ is generic). Therefore, finding all multi-directed edges is equivalent to finding all maximal cliques in $G_1'$ for which~\eqref{eq:nonZeroCumulant} holds. This is precisely what Algorithm~\ref{alg:2} does -- it applies the Bron-Kerbosch algorithm for finding all cliques in an undirected graph (which can equally well be applied to the graph $G_1'$ since it only has bidirected edges) and for each such clique it checks whether~\eqref{eq:nonZeroCumulant} holds. Therefore, Algorithm~\ref{Alg:1} produces the correct graph $G$. \end{proof} \begin{theorem} Suppose $Y_1,Y_2,\cdots,Y_n$ are generated by a linear structural equation model which corresponds to a bow-free acyclic mixed graph $G=(V, \mathcal D, \mathcal H)$. Then, for generic choices of the effects coefficient matrix $B$, and generic error moments, there exist $\delta_1,\delta_2, \delta_3>0$ such that if the sample moments are within a $\delta_1$ ball of the population moments of $Y$, then Algorithm~\ref{Alg:1} will produce the correct graph $G$ when comparing the absolute value of the sample statistics to $\delta_2$ as a proxy for the independence tests in the BANG procedure and when comparing the absolute value of the cumulants to $\delta_3$ as a proxy in the tests for the vanishing of cumulants in Algorithm~\ref{alg:2}. \end{theorem} \begin{proof} First, consider the data matrix $X=Y-BY$. Note that by definition the cumulants of $X$ have the form \begin{align*} \mathcal C^{(k)}_{i_1,\ldots,i_k} := cum\left(X_{i_1},\cdots,X_{i_k}\right)=\sum_{(A_1,\cdots,A_L)}(-1)^{L-1}(L-1)!\,\mathbb{E}\left[\prod_{j\in A_1}X_j\right]\cdots\mathbb{E}\left[\prod_{j\in A_L}X_j\right], \end{align*} which is a rational function of the moments of $X$, which are rational functions of the moments of $Y$ and of the matrix $B$. Thus, it is also a continuous function of the population moments of $Y$. For the population cumulants $\mathcal{PC}^{(k)}$ of $X$ let \begin{align*} \delta_3 = \frac12 \min_{\mathcal{PC}^{(k)}_{i_1,\cdots,i_k}\neq 0}\,\left|\mathcal{PC}^{(k)}_{i_1,\cdots,i_k}\right|,\quad 1\leq k\leq p. \end{align*} Thus, there exists $\delta'>0$ such that whenever the empirical moments of $Y$ are within a $\delta'$ ball of its population moments and the estimated $B$ is within $\delta'$ of the true one, all of the estimated cumulant entries of $X$ are within an $\delta_3$ ball of the entries of its population cumulants $\mathcal C^{(k)}$. Next, we know from~\cite{BANG} that there exist $\delta,\delta_2 > 0$ such that if the sample moments are within a $\delta$ ball of the population moments BANG will output the correct graph $G_1=(V, \mathcal D, \mathcal B)$ (where $\mathcal B$ is the bidirected subdivision of $ \mathcal H$) if it uses $\delta_2$ as a proxy for its independence tests. Furthermore, if the sample moments are within a $\delta$ ball of the population moments, the estimated directed effects matrix $B$ will be within a $\delta'$ ball from the true direct effects matrix. This is because the estimated matrix $B$ is a rational function of the sample moments~\cite{BANG}. Thus, choosing $\delta_1 = \min(\delta, \delta')$, we see that if the sample moments of $Y$ are within $\delta_1$ of its population moments, and if we use $\delta_2$ as a proxy for its independence tests in BANG and $\delta_3$ as as a proxy in the tests for vanishing cumulants, Algorithm~\ref{Alg:1} will yield the correct graph $G=(V, \mathcal D, \mathcal H)$. \end{proof} \section{Numerical Results}\label{sec:4} In this section we examine how well Algorithm~\ref{Alg:1} performs numerically. \subsection{Simulations} We carried out a number of simulations using four different types of error distributions: the uniform distribution on $[-10,10]$; the student's $t$-distribution with 10 degrees of freedom; the Gamma distribution with shape $=2$ and rate $=4$; and the chi-squared distribution with 2 degrees of freedom. We shift these distributions to have zero mean. The $t$-distribution is used to test the performance of the algorithm in cases when the distribution resembles the Gaussian distribution. \par We generate random bow-free acyclic mixed graphs as follows. First, we uniformly select a prescribed number of directed edges from the set $\{(i,j)|i<j\}$, and we choose the direct effect coefficients for each edge uniformly from $(-1,-0.6)\cup(0.6, 1)$. Afterwards, some of the vertices of this directed acyclic graph which have no parents are regarded as unobserved variables, and bow structures caused by marginalizing these vertices are removed from the graph. The resulting graph is a bow-free acyclic mixed graph with potential multidirected edges.\par To evaluate the performance of our method, we calculate the proportion of time that the algorithm recovers the true graph. We generate graphs with 7 vertices, and after some of them are made hidden, the final graphs usually contain 5 or 6 observed variables. We test three settings with different levels of sparsity. Sparse graphs have 5 directed edges before marginalization, medium graphs have 8, and dense graphs have 12. We do not restrict the number of multidirected edges, however, almost all dense graphs have multidirected edges, and most of the medium graphs have at least one multidirected edge.\par In the first step of our algorithm, we perform the BANG procedure, and we set all the nominal levels of the hypothesis test to $\alpha = 0.01$, as suggested by the authors of the BANG algorithm\cite{BANG}. The tolerance value used in our cumulant tests we use is $0.05$.\par For each of the three settings: sparse, medium, and dense, we tested 100 graphs by taking different numbers of samples: 10000, 25000 and 50000. In Figure~\ref{fig:test_edge_percent}, we show the percent of correctly identified bidirected and multidirected edges for each setting. The $x$ axis represents the sample size and the $y$ axis represents the percentage.\par In Figure \ref{fig:test_edge_total}, we show the proportion of graphs that were recovered precisely by the BANG and MBANG algorithms. For the BANG algorithm, we recognize each multidirected edge as the corresponding set of bidirected edges. In practice, we normalize the data matrix $X$ by dividing each row by its standard deviation before initiating Algorithm~\ref{alg:2} in order to control the variability of its cumulants. \begin{figure}[H] \centering \includegraphics[width=\textwidth]{test1.png} \caption{Random Graph Results - Correct Multidirected Edges} \label{fig:test_edge_percent} \end{figure} \begin{figure}[] \centering \includegraphics[width=\textwidth]{test2.png} \caption{Random Graph Results - Correct Graphs} \label{fig:test_edge_total} \end{figure} Among all $3600$ graphs we tested in this data set, the BANG algorithm recoverd $1883$ correctly, and the MBANG algorithm recovered $1774$ correctly. Hence, given that the BANG result was correct, the MBANG algorithm identified $94.2\%$ of the graphs correctly. Among all dense graphs, this proportion is reduced to $88.0\%$. However, this drop in accuracy might be expected because in our simulation dense graphs contain more multi-directed edges. \subsection{A Real Data Set} In a paper by Grace et al. \cite{Grace}, a LSEM was used to examine the relationships between land productivity and the richness of plant diversity, the full model of which is shown in Figure~\ref{fig:Grace}. Wang and Drton~\cite{BANG} choose a subset of the variables and consider the model in Figure~\ref{fig:targetBAP} as the ground truth model. Figure \ref{fig:discovered} shows the graphical model they discover using the BANG procedure with nominal test level 0.01. Since this is a real data set, it is possible that some of the hidden variables affect more than one bidirected edge, or there exist other hidden variables that can affect the hidden variables detected in the BANG procedure. After applying our MBANG algorithm with 0.05 tolerance, we found that all bidirected edges can be grouped in three 3-directed edges: ("PlotSoilSuit", "PlotProd", "SiteBiomass"), ("PlotSoilSuit", "SiteBiomass", "SiteProd"), and ("PlotSoilSuit", "SiteBiomass", "SiteProd"), see Figure~\ref{fig:discoveredMBANG}. \begin{figure}[H] \hspace{-0.6cm} \begin{subfigure}{0.4\textwidth} \centering \includegraphics[width=0.9\textwidth]{Grace.PNG} \caption{Full model from \cite{Grace}} \label{fig:Grace} \end{subfigure} \hspace{0.1cm} \begin{subfigure}{0.6\textwidth} \centering \vspace{1.6cm} \begin{tikzpicture}[->,shorten >=1pt, auto, main node/.style={rounded corners,inner sep=0pt,fill=gray!20,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95}] \node[main node] (Pprod) [right = 0cm] {Pl Prod}; \node[main node] (Pbio) [right = 2cm] {Pl Bio}; \node[main node] (Shade) [right =4cm] {Pl Shade}; \node[main node] (Prich) [right = 6cm] {Pl Rich}; \node[main node] (Sprod) [above = 1.1 cm,right = 0cm] {St Prod}; \node[main node] (Sbio) [above = 1.1cm,right = 2cm] {St Bio}; \node[main node] (Srich) [above = 1.1cm, right = 6cm] {St Rich}; \node[main node] (Suit) [right = 8cm] {Pl Suit}; \tikzset{>=latex} \path[color=black!20!blue,style={->}] (Sprod) edge node {} (Pprod) (Sprod) edge node {} (Pbio) (Sprod) edge node {} (Prich) (Sbio) edge node {} (Prich) (Sbio) edge node {} (Pbio) (Sbio) edge node {} (Pprod) (Srich) edge node {} (Pprod) (Srich) edge node {} (Pbio) (Srich) edge node {} (Prich) (Pbio) edge node {} (Shade) (Shade) edge node {} (Prich) (Shade) edge node {} (Prich) (Prich) edge[bend left = 20] node {} (Pprod) (Suit) edge node {} (Prich); \path[color=black!20!red,style={<->}] (Suit) edge node {} (Srich) (Sprod) edge[bend left = 15] node {} (Srich) (Sbio) edge node {} (Srich) (Sprod) edge node {} (Sbio); \end{tikzpicture} \caption[Data example: BAP respresentation from Grace et al. (2016)]{\label{fig:targetBAP}A subset of the model from \cite{Grace} used in~\cite{BANG}} \end{subfigure} \caption{True model} \end{figure} \begin{figure}[H] \centering \begin{tikzpicture}[->,shorten >=1pt, auto, main node/.style={rounded corners,inner sep=0pt,fill=gray!20,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95}] \node[main node] (Pprod) [right = 0cm] {Pl Prod}; \node[main node] (Pbio) [right = 2cm] {Pl Bio}; \node[main node] (Shade) [right =4cm] {Pl Shade}; \node[main node] (Prich) [right = 6cm] {Pl Rich}; \node[main node] (Sprod) [above = 1.1 cm,right = 0cm] {St Prod}; \node[main node] (Sbio) [above = 1.1cm,right = 2cm] {St Bio}; \node[main node] (Srich) [above = 1.1cm, right = 6cm] {St Rich}; \node[main node] (Suit) [right = 8cm] {Pl Suit}; \tikzset{>=latex} \path[color=black!20!blue,style={->}] (Suit) edge node {} (Srich) (Pprod) edge node {} (Srich) (Pbio) edge node {} (Shade) (Sbio) edge node {} (Pbio) (Sbio) edge node {} (Prich) (Srich) edge node {} (Prich) (Sprod) edge node {} (Pprod) (Sprod) edge node {} (Prich) (Sprod) edge node {} (Shade) (Shade) edge node {} (Prich) (Pbio) edge node {} (Pprod) ; \path[color=black!20!red, style={<->}] (Suit) edge[bend left = 20] node {} (Pprod) (Suit) edge[bend right = 5] node {} (Sbio) (Suit) edge node {} (Sprod) (Srich) edge[bend right = 20] node {} (Sprod) (Srich) edge node {} (Sbio) (Sbio) edge node {} (Pprod) (Sprod) edge node {} (Sbio) ; \end{tikzpicture} \caption[Data example: model discovered by BANG]{\label{fig:discovered}Model discovered by BANG~\cite{BANG}.} \end{figure} \begin{figure}[H] \centering \begin{tikzpicture}[->,shorten >=1pt, auto, main node/.style={rounded corners,inner sep=0pt,fill=gray!20,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95}] \node[main node] (Pprod) [right = 0cm] {Pl Prod}; \node[main node] (Pbio) [right = 2cm] {Pl Bio}; \node[main node] (Shade) [right =4cm] {Pl Shade}; \node[main node] (Prich) [right = 6cm] {Pl Rich}; \node[main node] (Sprod) [above = 1.1 cm,right = 0cm] {St Prod}; \node[main node] (Sbio) [above = 1.1cm,right = 2cm] {St Bio}; \node[main node] (Srich) [above = 1.1cm, right = 6cm] {St Rich}; \node[main node] (Suit) [right = 8cm] {Pl Suit}; \node[rounded corners,dotted,inner sep=0pt,fill=gray!10,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95] (Hidden) [below=1.5cm, right =4cm] {Hidden}; \node[rounded corners,dotted,inner sep=0pt,fill=gray!10,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95] (Hidden2) [above=2.5cm, right =6cm] {Hidden}; \node[rounded corners,dotted,inner sep=0pt,fill=gray!10,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95] (Hidden3) [above=2.5cm, right =2cm] {Hidden}; \tikzset{>=latex} \path[color=black!20!blue,style={->}] (Suit) edge node {} (Srich) (Pprod) edge node {} (Srich) (Pbio) edge node {} (Shade) (Sbio) edge node {} (Pbio) (Sbio) edge node {} (Prich) (Srich) edge node {} (Prich) (Sprod) edge node {} (Pprod) (Sprod) edge node {} (Prich) (Sprod) edge node {} (Shade) (Shade) edge node {} (Prich) (Pbio) edge node {} (Pprod) ; \path[color=black!20!red, style={<->}] ; \path[color=black!20!yellow, thick,style={->}] (Hidden) edge node {} (Suit) (Hidden) edge node {} (Pprod) (Hidden) edge node {} (Sbio) (Hidden2) edge node {} (Suit) (Hidden2) edge node {} (Sbio) (Hidden2) edge node {} (Sprod) (Hidden3) edge node {} (Srich) (Hidden3) edge node {} (Sbio) (Hidden3) edge node {} (Sprod) ; ` \end{tikzpicture} \caption[Data example: model discovered by MBANG]{\label{fig:discoveredMBANG}Model discovered by MBANG.} \end{figure} \section{Further Discussion}\label{sec:5} In this paper we proposed a high-order cumulant based algorithm for discovering hidden variable structure in non-Gaussian LSEMs. Note that our Algorithm~\ref{alg:2} can be used on top of any procedure that recovers a mixed graph $G=(V, \mathcal D, \mathcal B)$ with directed and bidirected edges only and an estimate of the direct effects matrix $B$. We chose the BANG algorithm as this first step since it applies to a large class of graphs: bow-free acyclic mixed graphs. Second, the performance of our algorithm is closely related to the error distribution, and the density and size of the graph. For example, when the errors are unif($-5,\, 5$) and the number of vertices is 7, as the edge number increases from 8 to 20, the correct rate drops from $78\%$ to $1\%$. Also, if the density is medium, as the number of vertices increases from 5 to 7, the correct rate drops from $78\%$ to about $40\%$. Compared to the uniform distribution, the exponential distribution has a much milder drop in correct rate. For example, when the sample size is 50000, the correct rate for exp(1) drops from $70\%$ to $61\%$ as the graph density increases from sparse to very dense (almost complete). Note, however, that this drop is also present in the output of the BANG algorithm itself. Last, while we proved that Algorithm~\ref{Alg:1} finds the true graph given enough samples, it would be interesting to know the exact amount of samples needed in both BANG and Algorithm~\ref{alg:2}, as well as the nominal levels for the independence tests in BANG and in our cumulant tests. \section*{Acknowledgements} We thank Mathias Drton and Samuel Wang for helpful discussions regarding their algorithm~\cite{BANG}. We also thank Jean-Baptiste Seby for a helpful discussion at an early stage of the project. ER was supported by an NSERC Discovery Grant (DGECR-2020-00338). YL was supported by a WLIURA in the summer of 2020. \bibliographystyle{alpha} \section{Introduction} Building on the theory of causal discovery from observational data, we propose a method to learn linear non-Gaussian structural equation models with hidden variables. Importantly, we allow each hidden variable to be a parent of multiple of the observed variables, and we represent this graphically via {\em multi-directed} edges. Therefore, given observational data, we seek to find an acyclic mixed graph whose vertices correspond to the observed variables, and which has directed and multi-directed edges. \begin{figure}[H] \centering \begin{subfigure}[b]{0.31\textwidth} \centering \includegraphics[width=1.1\textwidth]{ExampleDAG.pdf} \caption{Example DAG.} \label{fig:1a} \end{subfigure} \hfill \begin{subfigure}[b]{0.31\textwidth} \centering \includegraphics[width=0.82\textwidth]{MultiDAG.pdf} \caption{Mixed graph.} \label{fig:1b} \end{subfigure} \hfill \begin{subfigure}[b]{0.31\textwidth} \centering \includegraphics[width=0.65\textwidth]{BidirectedDAG.pdf} \caption{Mixed graph.} \label{fig:1c} \end{subfigure} \caption{The graph in Figure~\ref{fig:1a} is directed acyclic. After marginalization of vertices 1 and 5, the resulting mixed graph with directed and bidirected edges only is that in Figure~\ref{fig:1c}. If we allow multidirected edges, we can capture the hidden variable structure better via the graph in Figure~\ref{fig:1b}, which also has a 3-directed edge.} \label{fig:1} \end{figure} Consider an acylic mixed graph $G = (V, \mathcal D, \mathcal H)$, where $V = \{1, \ldots, p\}$ is the set of vertices, $\mathcal D$ is the set of directed edges, and $\mathcal H$ is the set of multi-directed edges, i.e., $\mathcal H$ consists of tuples of vertices such that the vertices in each tuple have a hidden common cause. The graph in Figure~\ref{fig:1c} has only directed and bidirected edges, while the one in Figure~\ref{fig:1b} also has a 3-directed edge. Both of these mixed graphs represent the directed acyclic graph in Figure~\ref{fig:1a} with the variables 1 and 5 unobserved. Representing hidden variables via such edges is quite commonly used for causal discovery~\cite{handbook}. We restrict our attention to the class of {\em Linear Structural Equation Models (LSEMs)}. A mixed graph $G$ gives rise to a linear structural equation model, which is the set of all joint distributions of a random vector $X=(X_1,\ldots, X_p)$ such that the variable $X_i$ associated to vertex $i$ is a linear function of a noise term $\epsilon_i$ and the variables $X_j$, as $j$ varies over the set of parents of $i$, denoted pa$(i)$, (i.e., the set of all vertices $j$ such that $j\to i \in E$). Thus, $$X_i = \sum_{j\in\text{pa}(i)} b_{ij}X_j + \varepsilon_i, \,\, i\in V.$$ When the variables $X_1,\ldots, X_p$ are Gaussian, we are only able to recover the mixed graph up to Markov equivalence from observational data~\cite{handbook, Lauritzen}. When the variables are non-Gaussian, however, it is possible to recover the full graph from observational data. This line of work originated with the paper~\cite{Shimizu2006} by Shimizu et al. in which a linear non-Gaussian structural equation model corresponding to a direced acyclic graph (DAG), i.e., a graph without confounders, can be identified from observational data using independent component analysis (ICA). Instead of ICA, the subsequent DirectLiNGAM~\cite{Shimizu2011} and Pairwise LiNGAM~\cite{PairwiseLiNGAM} methods use an iterative procedure to estimate a causal ordering; Wang and Drton~\cite{WangDrton} give a modified method that is also consistent in high-dimensional settings in which the number of variables $p$ exceeds the sample size $n$. Hoyer et al.~\cite{Hoyer} consider the setting where the data is generated by a linear non-Gaussian acyclic model (LiNGAM), but some variables are unobserved. Their method, like ours, recovers an acyclic mixed graph with multidirected edges. However, it uses overcomplete ICA and requires the number of latent variables in the model to be known in advance. Furthermore, current implementations of overcomplete ICA algorithms often suffer from local optima and can't guarantee convergence to a global one. To avoid using overcomplete ICA while still identifying unobserved confounders, Tashiro et al.~\cite{Parcellingam} propose a procedure, called ParcelLiNGAM, which tests subsets of observed variables. Wang and Drtong~\cite{BANG}, however, show that this procedure works whenever the graph is ancestral, and propose a new procedure, called BANG, which uses patterns in higher-order moment data, and can identify {\em bow-free acyclic mixed graphs}, a set of mixed graphs much larger than the set of ancestral graphs. The BANG algorithm, however, recovers a mixed graph which only contains directed and bidirected edges. Our method builds on the BANG procedure. We can identify a bow-free acyclic mixed graph, and, in addition, join bidirected edges together into a multi-directed edge whenever more than two of the observed variables have a hidden common cause. The rest of the paper is organized as follows. In Section~\ref{sec:2} we give the necessary background on mixed graphs, linear structural equation models, and multi-treks. In Section~\ref{sec:3}, we present our algorithm (MBANG) and we prove that it recovers the correct graph as long as the empirical moments are close enough the the population moments. In Section 4 we present numerical results, including simulations of different graphs and error distributions, and an application of our algorithm to a real dataset. We conclude with a short discussion in Section 5. \section{Background}\label{sec:2} In this section we introduce the key concepts that we use throughout the paper, including mixed graphs with multi-directed edges, linear structural equation models, multi-treks and cumulants. \subsection{Mixed graphs with multi-directed edges} The notion of a mixed graph is widely used in graphical modelling, where bidirected edges depict unobserved confounding. In this paper a mixed graph is also allowed to contain multi-directed edges to depict slightly more complicated unobserved confounding. \begin{definition} (a). We call $G = (V, \mathcal D, \mathcal H)$ a {\em mixed graph}, where $V = \{1,\ldots, p\}$ is the set of vertices, $\mathcal D\subseteq V\times V$ is the set of directed edges, and $\mathcal H$ is the set of multi-directed edges (all $k$-directed edges for $k\geq 2$). (see part (b)). (b). For $k\geq 2$, a {\em $k$-directed} (or {\em multi-directed}) edge between distinct nodes $i_1,\ldots, i_k\in V$, denoted by $(i_1,\ldots, i_k)$, is the union of $k$ directed edges with the same hidden source and sinks $i_1,\ldots, i_k$ respectively. Multi-directed edges are unordered. \begin{figure}[H] \begin{subfigure}{0.5\textwidth} \begin{center} \vspace{0.35cm} \includegraphics[width=0.6\textwidth]{bidirectedEdge.pdf} \caption{A 2-directed (or bidirected) edge between $i_1,i_2$.} \label{fig:2-edge} \end{center} \end{subfigure} \begin{subfigure}{0.5\textwidth} \begin{center} \includegraphics[width=0.6\textwidth]{4-directedEdge.pdf} \caption{A 4-directed edge between $i_1,i_2,i_3,i_4$.} \label{fig:4-edge} \end{center} \end{subfigure} \caption{Examples of multi-directed edges.} \end{figure} \end{definition} Our method is able to recover {\em bow-free} {\em acyclic} mixed graphs. A mixed graph is bow-free if it does not contain a {\em bow}, and a bow consists of two vertices $i,j\in V$ such that there is both a directed and a multidirected edge between $i$ and $j$. In other words, $i\to j\in\mathcal D$ and there exists $h\in\mathcal H$ such that $i,j\in h$. A mixed graph is acyclic if it does not contain any {\em directed cycles}, where a directed cycle is a sequence of directed edges of the form $i_1\to i_2, i_2\to i_3,\ldots, i_\ell \to i_1$. \begin{figure}[H] \begin{subfigure}{0.5\textwidth} \begin{center} \includegraphics[width=0.4\textwidth]{bow.pdf} \caption{A bow between $i$ and $j$.} \label{fig:bow} \end{center} \end{subfigure} \begin{subfigure}{0.5\textwidth} \begin{center} \includegraphics[width=0.4\textwidth]{cycle.pdf} \caption{A cycle.} \label{fig:cycle} \end{center} \end{subfigure} \caption{Examples of a bow and a cycle.} \end{figure} Acyclic mixed graphs with potential multidirected edges are all one can hope to recover from observational data. Suppose for a moment that we have data coming from a directed acyclic graph (DAG) where a subset of the variables is unobserved, e.g., consider the DAG in Figure~\ref{fig:originalModel}, where we only observe variables 1, 4, and 5. Hoyer et al.~\cite{Hoyer} show that any directed acyclic graphical model in which some of the variables are unobserved is observationally and causally equivalent to a unique {\em canonical model}, where a canonical model is a non-Gaussian Linear Structural Equation Model corresponding to an acyclic mixed graph $G=(V, \mathcal D, \mathcal H)$ such that none of the latent variables have any parents, and each latent variable has at least two children. This means, that the distribution of the observed variables in the original model is identical to that in the canonical model, and causal relationships of observed variables in both models are identical. Therefore, we can focus our attention on the set of canonical models, which can be represented precisely by acyclic mixed graphs with multi-directed edges. The graph in Figure~\ref{fig:canonical} is the canonical model corresponding to the one in Figure~\ref{fig:originalModel}. \begin{figure}[H] \begin{subfigure}{0.5\textwidth} \begin{center} \includegraphics[scale = 0.6]{canonical1.pdf} \caption{Original model}\label{fig:originalModel} \label{fig: origin} \end{center} \end{subfigure} \begin{subfigure}{0.5\textwidth} \begin{center} \includegraphics[scale = 0.6]{canonical2.pdf} \caption{Canonical model} \label{fig:canonical} \end{center} \end{subfigure} \caption{An example of two observationally and causally equivalent models from~\cite{Hoyer}.} \label{fig:canonExample} \end{figure} \subsection{Linear Structural Equation Models} Let $G=(V, \mathcal D, \mathcal H)$ be an acyclic mixed graph as defined in the previous section. It induces a statistical model, called a {\em linear structural equation model}, or {\em LSEM}, for the joint distribution of a collection of random variables $(X_i, i \in V )$, indexed by the graph’s vertices. The model hypothesizes that each variable is a linear function of its parent variables and a noise term $\varepsilon_i$: \begin{align}\label{LSEM}X_i = b_{0i} + \sum_{j\in\text{pa}(i)} b_{ji}X_j + \varepsilon_i , i \in V, \end{align} where $\text{pa}(i) = \{j\in V: j\to i\in\mathcal D\}$ is the set of parents of vertex $i$. The variables $\varepsilon_i, i\in V$ are assumed to have mean 0, and the coefficients $b_{0i}$ and $b_{ji}$ are unknown real parameters. Since we can center the variables $X_i$, we assume that the coefficients $b_{0i}$ are all equal to 0. In addition, the multi-directed edge structure of $G$ defines dependencies between the noise terms $\varepsilon_i$, that is, if $i$ and $j$ are not connected by a multi-directed edge, then $\varepsilon_i$ and $\varepsilon_j$ are independent variables. In particular, if $G$ is a DAG (directed acyclic graph), i.e., it does not have any multi-directed edges, then all noise terms $\varepsilon_i$ are mutually independent. Typically termed a system of structural equations, the system~\eqref{LSEM} specifies cause-effect relations whose straightforward interpretability explains the wide-spread use of the models~\cite{Pearl, SGS00}. We can rewrite the system~\eqref{LSEM} as $$X = BX + \varepsilon,$$ where $X = (X_1,\ldots, X_p)^T$, $B = (b_{ij})$ is the coefficient matrix satisfying $b_{ij} = 0$ whenever $i\to j\not\in \mathcal D$, and $\varepsilon$ is the noise vector. Note that since $G$ is assumed to be acyclic, we can permute the coefficient matrix $B$ so that it is a lower triangular matrix. Therefore, the matrix $I-B$ is invertible, and the system~\eqref{LSEM} can further be rewritten as $$X = (I-B)^{-1}\varepsilon.$$ \subsection{Cumulants and the multi-trek rule} We recall the notion of a cumulant tensor for a random vector~\cite{ComonJutten}. \begin{definition} Let ${Z}=(Z_1,\cdots,Z_p)$ be a random vector of length $p$. The $k$-th cumulant tensor of ${Z}$ is defined to be a $p\times \cdots\times p$ ($k$ times) table, $\mathcal C^{(k)}$, whose entry at position $(i_1,\cdots, i_k)$ is \begin{align*} \mathcal C^{(k)}_{i_1,\ldots, i_k}=\sum_{(A_1,\cdots,A_L)}(-1)^{L-1}(L-1)!\, \mathbb{E}\left[\prod_{j\in A_i}Z_j\right]\cdots\mathbb{E}\left[\prod_{j\in A_L}Z_j\right], \end{align*} where the sum is taken over all partitions $(A_1,\cdots, A_L)$ of the set $\{i_1,\cdots, i_k\}$. \end{definition} Note that if each of the variables $Z_i$ has zero mean, then we can restrict the summing over partitions for which each $A_i$ has size at least two. For example: \begin{align*} \mathcal C^{(4)}_{i_1,i_2,i_3,i_4}&=\mathbb{E}(Z_{i_1}Z_{i_2}Z_{i_3}Z_{i_4})-\mathbb{E}(Z_{i_1}Z_{i_2})\mathbb{E}(Z_{i_3}Z_{i_4})-\mathbb{E}(Z_{i_1}Z_{i_3})\mathbb{E}(Z_{i_2}Z_{i_4})+\\ &\quad \mathbb{E}(Z_{i_1}Z_{i_4})\mathbb{E}(Z_{i_2}Z_{i_3}) \end{align*} We now recall the notion of a multi-trek from~\cite{multiTrek}. \begin{definition} A $k$-trek in a mixed graph $G=(V, \mathcal D, \mathcal H)$ between $k$ nodes $i_1,i_2,\cdots, i_k$ is an ordered collection of $k$ directed paths $(P_1,\cdots, P_k)$ where $P_j$ has sink $i_j$ and either $P_1,\cdots, P_k$ have the same source of vertex, or there exists a multi-directed edge $h\in\mathcal H$ such that the sources of $P_1,\ldots, P_k$ all lie in $h$. \end{definition} \begin{figure}[H] \begin{subfigure}{0.5\textwidth} \centering \includegraphics[width=0.5\textwidth]{4-trek.pdf} \caption{A 4-trek between $i_1,i_2,i_3,i_4$.} \label{fig:my_label} \end{subfigure} \begin{subfigure}{0.5\textwidth} \centering \includegraphics[width=0.45\textwidth]{4-trekHidden.pdf} \caption{A 4-trek between $i_1,i_2,i_3,i_4$.} \label{fig:my_label} \end{subfigure} \caption{Examples of multi-treks.} \end{figure} The following consequence of the {\em multi-trek rule}~\cite{multiTrek} connects cumulants of LSEMs to multi-treks. \begin{theorem}[\cite{multiTrek}]\label{thm:multiTrek} Let $G = (V, \mathcal D, \mathcal H)$ be an acyclic mixed graph, and let $i_1,\ldots, i_k\in V$. Then, $$\mathcal C^{(k)}_{i_1,\ldots, i_k} = 0$$ for the $k$-th cumulant tensor $\mathcal C^{(k)}$ of any random vector whose distribution lies in the LSEM corresponding to $G$ if and only if there is no $k$-trek between $i_1,\ldots, i_k$ in $G$. \end{theorem} \section{Main Result}\label{sec:3} In this section we present our algorithm and we show that it recovers the correct graph given enough samples. In the chart below we illustrate how the algorithm works when applied to observational data coming from the graph in Figure~\ref{fig:1a}. \begin{figure}[] \centering \centering \includegraphics[scale = 0.6]{flowChart.pdf} \caption{} \label{fig: flow} \end{figure} Given a $p\times n$ data matrix $Y$ whose columns are i.i.d. sampels from a LSEM on an unknown bow-free acyclic mixed graph $G=(V, \mathcal D, \mathcal H)$ with an unknown direct effects matrix $B$, we aim to recover the graph $G$ and the matrix $B$. The first step is to apply the BANG procedure~\cite{BANG} and obtain the coefficient matrix $B$ together with a bow-free acyclic mixed graph $G_1 = (V, \mathcal D, \mathcal B)$ which contains directed and bidirected edges only. The bidirected edges $\mathcal B$ are obtained from $\mathcal H$ by replacing each multi-directed edge $h=(i_1,\ldots, i_k)\in\mathcal H$ by $\binom k2$ bidirected eges, one for each pair $i_s, i_t\in\{i_1,\ldots, i_k\}$. We call such a set $\mathcal B$ the {\em bidirected subdivision} of $\mathcal H$. We then, "remove" the directed edges by removing the direct effects given by $B$. This is done by replacing the original data matrix $Y$ with $X = Y-BY$. This new matrix $X$ can be thought of as observations from a LSEM corresponding to the acyclic mixed graph $G'=(V, \emptyset, \mathcal H)$ which is the same as $G$ with the directed edges removed. However, we only know the bidirected subdivision $\mathcal B$ of $\mathcal H$. Finally, using the higher order cumulants of $X$ and a clique-finding algorithm on the graph $G_1' = (V, \emptyset, \mathcal B)$, we identify all multi-directed edges in $\mathcal H$. The algorithm is summarized below. \begin{algorithm}[H] \caption{MBANG procedure}\label{Alg:1} \begin{algorithmic}[1] \STATE Input: $Y\in \mathbb{R}^{p\times n}$ arising from an unknown LSEM on $G=(V, \mathcal D, \mathcal H)$ with unknown direct effects matrix $B$. \STATE Apply the BANG procedure to estimate the coefficient matrix $B$ and the mixed graph $G_1=(V, \mathcal D, \mathcal B)$. \STATE Let $X=Y-BY$ be the new observation matrix, corresponding to the graph $G'=(V, \emptyset, \mathcal H)$ which has no directed edges. \STATE Initiate $R=Q=\varnothing$, $P=\{1,2,...,p\}$. \STATE Apply {Algorithm~\ref{alg:2}} to $X, G_1' = (V, \emptyset, \mathcal B), R,P$ and $Q$ to recover the set $\mathcal H$ of multidirected edges. \STATE Output: the graph $G = (V, \mathcal D, \mathcal H)$ and the matrix $B$. \end{algorithmic} \end{algorithm} Algorithm~\ref{alg:2} finds those multi-directed edges that contain the most vertices and are consistent with the cumulant structure of the data matrix $X$. It is based on the Bron-Kerbosh algorithm~\cite{BronKerbosch} for finding all cliques in an undirected graph, applied to the bidirected edges in $G_1' = (V, \emptyset, \mathcal B)$. \subsection{The BANG procedure} In this section we briefly describe the {BANG Procedure}~\cite{BANG}. It is an algorithm which takes as input a $p\times n$ data matrix $Y$, and returns a \textit{bow-free acyclic mixed graph} $G$ which contains directed and bidirected edges only, consistent with $Y$ as well as a direct effects matrix $B$. \par Suppose the observed data is drawn from a LSEM whose corresponding graph is the one in Figure~\ref{fig:bangExample}. Figure \ref{fig:bangFlowChart} shows how the {BANG algorithm} works. It first identifies sibling and ancestor relations, and then it distinguishes parent and non-parent ancestors. Recall that two vertices are {\em siblings} if there is a multi-directed edge between them, a vertex $i$ is a {\em parent} of a vertex $j$ if there is a directed edge $i\to j$, and a vertex $i$ is an {\em ancestor} of a vertex $j$ if there is a direted path $i\to i_0\to\cdots\to i_k\to j$. \begin{figure}[H] \centering \begin{subfigure}{0.25\textwidth} \vspace{5cm} \hspace{-0.2cm} \hspace{0.5cm}\includegraphics[width=0.6\textwidth]{bangExample.pdf} \caption{Graph example} \label{fig:bangExample} \end{subfigure} \begin{subfigure}{0.65\textwidth} \hspace{1cm}\includegraphics[width=0.95\textwidth]{bangFlowChart.pdf} \caption{BANG flowchart} \label{fig:bangFlowChart} \end{subfigure} \caption{BANG algorithm example} \end{figure} However, the {BANG algorithm} returns {bow-free acyclic mixed graphs} in which the latent variable structure is recorded using bidirected edges only, i.e., it recovers the bidirected subdivision of the true set of multi-directed edges $\mathcal H$. This means it cannot determine whether more than two vertices have a common cause. We resolve this problem using cumulant information. \begin{figure}[] \begin{subfigure}{\linewidth} \centering \includegraphics[scale = 0.5]{bangExample2.pdf} \caption{Case 1} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[scale = 0.5]{bangExample1.pdf} \caption{Case 2} \end{subfigure} \caption{The same bidirected edge structure depicts two different hidden variable models.} \label{fig: bangLimit} \end{figure} \subsection{Finding the multidirected edge structure} Consider the two models in Figure \ref{fig: bangLimit}. By Theorem \ref{thm:multiTrek}, we know that $\mathcal{C}^{(3)}_{2,3,4}=0$ in Case 1 whereas $\mathcal{C}^{(3)}_{2,3,4}\neq 0$ in Case 2. In other words, the exact model can be recovered by testing whether $\mathcal{C}^{(3)}_{2,3,4}=0$. \par More generally, as depicted in Figure~\ref{fig: flow}, we first apply the BANG algorithm to the data marix $Y\in\mathbb R^{p\times n}$ arising from a LSEM on $G=(V, \mathcal D, \mathcal H)$, to obtain an estimate of the direct effects matrix $B$ and the bow-free acyclic mixed graph $G_1=(V, \mathcal D, \mathcal B)$ with directed and bidirected edges only, where there is a bidirected edge between $i$ and $j$ in $G_1$ if and only if there is a multidirected edge in $G$ containing both $i$ and $j$, i.e., $\mathcal B$ is the bidirected subdivision of $\mathcal H$. Then, we form a new data matrix $X=Y-BY$ and we consider the graph $G' = (V, \emptyset, \mathcal H)$ which contains only multi-directed edges. In other words, the data matrix $X$ can be thought of as a matrix of samples coming from a LSEM on the graph $G'$. However, we only know the graph $G_1' = (V, \emptyset, \mathcal B)$. The bidirected edges $\mathcal B$ recovered by the BANG algorithm can now be "merged" together to obtain the true multi-directed edge structure $\mathcal H$. Since $G_1'$ contains only bidirected edges, we look for all cliques (of bidirected edges) $\{i_1,\ldots, i_k\}$ in $G'$ such that $\mathcal C^{(k)}_{i_1,\ldots, i_k}\neq 0$, where $\mathcal C^{(k)}$ is the $k$-th cumulant of $X$. We do this by adapting the Bron-Kerbosch algorithm~\cite{BronKerbosch}, which is used for finding all cliques in an undirected graph. \begin{algorithm}[H] \caption{Determine Multidirected Edges} \label{alg:2} \begin{algorithmic}[1] \STATE Input: $X\in \mathbb{R}^{p\times n}, G_1'=(V, \emptyset, \mathcal B), R,P$ and $Q$. Denote the elements of $R$ to be $i_1,...,i_k$. \IF{$P$ and $Q$ are both empty} \STATE Report $R$ as a multidirected edge. \ENDIF \FORALL{vertex $v\in P$} \IF{$N(v) \neq \varnothing$, where $N(v)$ is the set of vertices adjacent to $v$ in $\mathcal B$} \IF{$\mathcal{C}^{(k+1)}_{i_1,\cdots,i_k,v} \neq 0$ or $\exists$ $j \in \{i_1,\cdots,i_k\}$ s.t. $\mathcal{C}^{(k+2)}_{i_1,\cdots,i_k,v,j}\neq 0$}\label{lst: line: condition} \STATE call Algorithm~\ref{alg:2}$(X, R\cup \{v\}, P\cap N(v),Q\cap N(v))$ \ENDIF \ENDIF \STATE $P=P\backslash \{v\}$ \STATE $Q = Q\cup \{v\}$ \ENDFOR \end{algorithmic} \label{alg:multiedge} \end{algorithm} Algorithm~\ref{alg:2} is a direct modification of the Bron-Kerbosch algorithm~\cite{BronKerbosch}. It is a recursive algorithm, that maintains three disjoint sets of vertices $R, P, Q \subset V$, and aims to output all cliques in the graph which contain all vertices in $R$, do not contain any of the vertices in $Q$, and could contain some of the vertices in $P$. The only addition to the Bron-Kerbosch algorithm that Algorithm~\ref{alg:2} does is the test of whether or not specific cumulants are nonzero in Line 7. In practice, since Theorem \ref{thm:multiTrek} holds for generic distributions, sometimes random variables consistent with a model that has a multi-directed edge between $i_1,\ldots, i_k$ may still have a zero cumulant. For example, if $i_1$, $i_2$, and $i_3$ are all caused by a hidden parent variable whose distribution is symmetric around $0$, then $\mathcal{C}^{(3)}_{i_1,i_2,i_3}=0$. To solve this problem, we relax the criterion $\mathcal{C}^{(k)}_{i_1,\cdots,i_k} \neq 0$. In our implementation, we also check if there exists $j\in\{i_1,\ldots, i_k\}$ such that $\mathcal{C}^{(k+1)}_{i_1,\cdots,i_k,j}\neq 0$. If there is a multidirected edge $h$ such that $i_1,\ldots, i_k\in h$ but due to non-genericity of the model $\mathcal C^{k}_{i_1,\ldots, i_k} =0$, we find that often times $\mathcal{C}^{(k+1)}_{i_1,\cdots,i_k,j}\neq 0$ which allows us to reach the correct conclusion. \subsection{Theoretical results} In this section we show that Algorithm~\ref{Alg:1} recovers the correct bow-free acyclic mixed graph given enough samples. We begin with a population moment result. \begin{theorem}\label{thm: alg} Suppose $Y$ is generated from a linear structural equation model corresponding to a bow-free acyclic mixed graph $G=(V, \mathcal D, \mathcal H)$. Then for a generic choice of the coefficient matrix $B$ and generic error moments, when given the population moments of $Y$, Algorithm~\ref{Alg:1} produces the correct graph $G$. \end{theorem} \begin{proof} Algorithm~\ref{Alg:1} first apples the BANG procedure to produce a \textit{bow-free acyclic mixed graph} $G_1 = (V, \mathcal D, \mathcal B)$ containing bi-directed edges and directed edges only as well as the coefficient matrix $B$. In~\cite{BANG} the authors show that the BANG algorithm recovers the correct bow-free acyclic mixed graph (with directed and bidirected edges only) and the correct coefficient matrix $B$. Note that this means that the graph $G_1$ will have a bidirected edge $b\in \mathcal B$ between two nodes $i$ and $j$ which are part of a multi-directed edge $h\in\mathcal H$ in $G$. Consider the data matrix $X=Y-BY$ which corresponds to a graph $G' = (V, \emptyset, \mathcal H)$ obtained by removing all directed edges in $G$, and the graph $G_1'=(V, \emptyset, \mathcal B)$ obtained from $G_1$ by removing all directed edges. Our task is to merge together some of the bidirected edges in $G_1'$ in order to obtain the graph $G'$. There is a multi-directed edge between $i_1,\ldots, i_k$ in $G'$ (or, equivalently, in $G$), if and only if any two of $i_1,\ldots, i_k$ are joined by a bidirected edge in $G_1'$, i.e., they will form a clique, AND \begin{align}\label{eq:nonZeroCumulant} \mathcal{C}^{(k)}_{i_1,\cdots, i_k}\neq 0, \end{align} where $\mathcal{C}^{(k)}$ is the $k$-th cumulant of $X$ (assuming the distribution of $X$ is generic). Therefore, finding all multi-directed edges is equivalent to finding all maximal cliques in $G_1'$ for which~\eqref{eq:nonZeroCumulant} holds. This is precisely what Algorithm~\ref{alg:2} does -- it applies the Bron-Kerbosch algorithm for finding all cliques in an undirected graph (which can equally well be applied to the graph $G_1'$ since it only has bidirected edges) and for each such clique it checks whether~\eqref{eq:nonZeroCumulant} holds. Therefore, Algorithm~\ref{Alg:1} produces the correct graph $G$. \end{proof} \begin{theorem} Suppose $Y_1,Y_2,\cdots,Y_n$ are generated by a linear structural equation model which corresponds to a bow-free acyclic mixed graph $G=(V, \mathcal D, \mathcal H)$. Then, for generic choices of the effects coefficient matrix $B$, and generic error moments, there exist $\delta_1,\delta_2, \delta_3>0$ such that if the sample moments are within a $\delta_1$ ball of the population moments of $Y$, then Algorithm~\ref{Alg:1} will produce the correct graph $G$ when comparing the absolute value of the sample statistics to $\delta_2$ as a proxy for the independence tests in the BANG procedure and when comparing the absolute value of the cumulants to $\delta_3$ as a proxy in the tests for the vanishing of cumulants in Algorithm~\ref{alg:2}. \end{theorem} \begin{proof} First, consider the data matrix $X=Y-BY$. Note that by definition the cumulants of $X$ have the form \begin{align*} \mathcal C^{(k)}_{i_1,\ldots,i_k} := cum\left(X_{i_1},\cdots,X_{i_k}\right)=\sum_{(A_1,\cdots,A_L)}(-1)^{L-1}(L-1)!\,\mathbb{E}\left[\prod_{j\in A_1}X_j\right]\cdots\mathbb{E}\left[\prod_{j\in A_L}X_j\right], \end{align*} which is a rational function of the moments of $X$, which are rational functions of the moments of $Y$ and of the matrix $B$. Thus, it is also a continuous function of the population moments of $Y$. For the population cumulants $\mathcal{PC}^{(k)}$ of $X$ let \begin{align*} \delta_3 = \frac12 \min_{\mathcal{PC}^{(k)}_{i_1,\cdots,i_k}\neq 0}\,\left|\mathcal{PC}^{(k)}_{i_1,\cdots,i_k}\right|,\quad 1\leq k\leq p. \end{align*} Thus, there exists $\delta'>0$ such that whenever the empirical moments of $Y$ are within a $\delta'$ ball of its population moments and the estimated $B$ is within $\delta'$ of the true one, all of the estimated cumulant entries of $X$ are within an $\delta_3$ ball of the entries of its population cumulants $\mathcal C^{(k)}$. Next, we know from~\cite{BANG} that there exist $\delta,\delta_2 > 0$ such that if the sample moments are within a $\delta$ ball of the population moments BANG will output the correct graph $G_1=(V, \mathcal D, \mathcal B)$ (where $\mathcal B$ is the bidirected subdivision of $ \mathcal H$) if it uses $\delta_2$ as a proxy for its independence tests. Furthermore, if the sample moments are within a $\delta$ ball of the population moments, the estimated directed effects matrix $B$ will be within a $\delta'$ ball from the true direct effects matrix. This is because the estimated matrix $B$ is a rational function of the sample moments~\cite{BANG}. Thus, choosing $\delta_1 = \min(\delta, \delta')$, we see that if the sample moments of $Y$ are within $\delta_1$ of its population moments, and if we use $\delta_2$ as a proxy for its independence tests in BANG and $\delta_3$ as as a proxy in the tests for vanishing cumulants, Algorithm~\ref{Alg:1} will yield the correct graph $G=(V, \mathcal D, \mathcal H)$. \end{proof} \section{Numerical Results}\label{sec:4} In this section we examine how well Algorithm~\ref{Alg:1} performs numerically. \subsection{Simulations} We carried out a number of simulations using four different types of error distributions: the uniform distribution on $[-10,10]$; the student's $t$-distribution with 10 degrees of freedom; the Gamma distribution with shape $=2$ and rate $=4$; and the chi-squared distribution with 2 degrees of freedom. We shift these distributions to have zero mean. The $t$-distribution is used to test the performance of the algorithm in cases when the distribution resembles the Gaussian distribution. \par We generate random bow-free acyclic mixed graphs as follows. First, we uniformly select a prescribed number of directed edges from the set $\{(i,j)|i<j\}$, and we choose the direct effect coefficients for each edge uniformly from $(-1,-0.6)\cup(0.6, 1)$. Afterwards, some of the vertices of this directed acyclic graph which have no parents are regarded as unobserved variables, and bow structures caused by marginalizing these vertices are removed from the graph. The resulting graph is a bow-free acyclic mixed graph with potential multidirected edges.\par To evaluate the performance of our method, we calculate the proportion of time that the algorithm recovers the true graph. We generate graphs with 7 vertices, and after some of them are made hidden, the final graphs usually contain 5 or 6 observed variables. We test three settings with different levels of sparsity. Sparse graphs have 5 directed edges before marginalization, medium graphs have 8, and dense graphs have 12. We do not restrict the number of multidirected edges, however, almost all dense graphs have multidirected edges, and most of the medium graphs have at least one multidirected edge.\par In the first step of our algorithm, we perform the BANG procedure, and we set all the nominal levels of the hypothesis test to $\alpha = 0.01$, as suggested by the authors of the BANG algorithm\cite{BANG}. The tolerance value used in our cumulant tests we use is $0.05$.\par For each of the three settings: sparse, medium, and dense, we tested 100 graphs by taking different numbers of samples: 10000, 25000 and 50000. In Figure~\ref{fig:test_edge_percent}, we show the percent of correctly identified bidirected and multidirected edges for each setting. The $x$ axis represents the sample size and the $y$ axis represents the percentage.\par In Figure \ref{fig:test_edge_total}, we show the proportion of graphs that were recovered precisely by the BANG and MBANG algorithms. For the BANG algorithm, we recognize each multidirected edge as the corresponding set of bidirected edges. In practice, we normalize the data matrix $X$ by dividing each row by its standard deviation before initiating Algorithm~\ref{alg:2} in order to control the variability of its cumulants. \begin{figure}[H] \centering \includegraphics[width=\textwidth]{test1.png} \caption{Random Graph Results - Correct Multidirected Edges} \label{fig:test_edge_percent} \end{figure} \begin{figure}[] \centering \includegraphics[width=\textwidth]{test2.png} \caption{Random Graph Results - Correct Graphs} \label{fig:test_edge_total} \end{figure} Among all $3600$ graphs we tested in this data set, the BANG algorithm recoverd $1883$ correctly, and the MBANG algorithm recovered $1774$ correctly. Hence, given that the BANG result was correct, the MBANG algorithm identified $94.2\%$ of the graphs correctly. Among all dense graphs, this proportion is reduced to $88.0\%$. However, this drop in accuracy might be expected because in our simulation dense graphs contain more multi-directed edges. \subsection{A Real Data Set} In a paper by Grace et al. \cite{Grace}, a LSEM was used to examine the relationships between land productivity and the richness of plant diversity, the full model of which is shown in Figure~\ref{fig:Grace}. Wang and Drton~\cite{BANG} choose a subset of the variables and consider the model in Figure~\ref{fig:targetBAP} as the ground truth model. Figure \ref{fig:discovered} shows the graphical model they discover using the BANG procedure with nominal test level 0.01. Since this is a real data set, it is possible that some of the hidden variables affect more than one bidirected edge, or there exist other hidden variables that can affect the hidden variables detected in the BANG procedure. After applying our MBANG algorithm with 0.05 tolerance, we found that all bidirected edges can be grouped in three 3-directed edges: ("PlotSoilSuit", "PlotProd", "SiteBiomass"), ("PlotSoilSuit", "SiteBiomass", "SiteProd"), and ("PlotSoilSuit", "SiteBiomass", "SiteProd"), see Figure~\ref{fig:discoveredMBANG}. \begin{figure}[H] \hspace{-0.6cm} \begin{subfigure}{0.4\textwidth} \centering \includegraphics[width=0.9\textwidth]{Grace.PNG} \caption{Full model from \cite{Grace}} \label{fig:Grace} \end{subfigure} \hspace{0.1cm} \begin{subfigure}{0.6\textwidth} \centering \vspace{1.6cm} \begin{tikzpicture}[->,shorten >=1pt, auto, main node/.style={rounded corners,inner sep=0pt,fill=gray!20,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95}] \node[main node] (Pprod) [right = 0cm] {Pl Prod}; \node[main node] (Pbio) [right = 2cm] {Pl Bio}; \node[main node] (Shade) [right =4cm] {Pl Shade}; \node[main node] (Prich) [right = 6cm] {Pl Rich}; \node[main node] (Sprod) [above = 1.1 cm,right = 0cm] {St Prod}; \node[main node] (Sbio) [above = 1.1cm,right = 2cm] {St Bio}; \node[main node] (Srich) [above = 1.1cm, right = 6cm] {St Rich}; \node[main node] (Suit) [right = 8cm] {Pl Suit}; \tikzset{>=latex} \path[color=black!20!blue,style={->}] (Sprod) edge node {} (Pprod) (Sprod) edge node {} (Pbio) (Sprod) edge node {} (Prich) (Sbio) edge node {} (Prich) (Sbio) edge node {} (Pbio) (Sbio) edge node {} (Pprod) (Srich) edge node {} (Pprod) (Srich) edge node {} (Pbio) (Srich) edge node {} (Prich) (Pbio) edge node {} (Shade) (Shade) edge node {} (Prich) (Shade) edge node {} (Prich) (Prich) edge[bend left = 20] node {} (Pprod) (Suit) edge node {} (Prich); \path[color=black!20!red,style={<->}] (Suit) edge node {} (Srich) (Sprod) edge[bend left = 15] node {} (Srich) (Sbio) edge node {} (Srich) (Sprod) edge node {} (Sbio); \end{tikzpicture} \caption[Data example: BAP respresentation from Grace et al. (2016)]{\label{fig:targetBAP}A subset of the model from \cite{Grace} used in~\cite{BANG}} \end{subfigure} \caption{True model} \end{figure} \begin{figure}[H] \centering \begin{tikzpicture}[->,shorten >=1pt, auto, main node/.style={rounded corners,inner sep=0pt,fill=gray!20,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95}] \node[main node] (Pprod) [right = 0cm] {Pl Prod}; \node[main node] (Pbio) [right = 2cm] {Pl Bio}; \node[main node] (Shade) [right =4cm] {Pl Shade}; \node[main node] (Prich) [right = 6cm] {Pl Rich}; \node[main node] (Sprod) [above = 1.1 cm,right = 0cm] {St Prod}; \node[main node] (Sbio) [above = 1.1cm,right = 2cm] {St Bio}; \node[main node] (Srich) [above = 1.1cm, right = 6cm] {St Rich}; \node[main node] (Suit) [right = 8cm] {Pl Suit}; \tikzset{>=latex} \path[color=black!20!blue,style={->}] (Suit) edge node {} (Srich) (Pprod) edge node {} (Srich) (Pbio) edge node {} (Shade) (Sbio) edge node {} (Pbio) (Sbio) edge node {} (Prich) (Srich) edge node {} (Prich) (Sprod) edge node {} (Pprod) (Sprod) edge node {} (Prich) (Sprod) edge node {} (Shade) (Shade) edge node {} (Prich) (Pbio) edge node {} (Pprod) ; \path[color=black!20!red, style={<->}] (Suit) edge[bend left = 20] node {} (Pprod) (Suit) edge[bend right = 5] node {} (Sbio) (Suit) edge node {} (Sprod) (Srich) edge[bend right = 20] node {} (Sprod) (Srich) edge node {} (Sbio) (Sbio) edge node {} (Pprod) (Sprod) edge node {} (Sbio) ; \end{tikzpicture} \caption[Data example: model discovered by BANG]{\label{fig:discovered}Model discovered by BANG~\cite{BANG}.} \end{figure} \begin{figure}[H] \centering \begin{tikzpicture}[->,shorten >=1pt, auto, main node/.style={rounded corners,inner sep=0pt,fill=gray!20,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95}] \node[main node] (Pprod) [right = 0cm] {Pl Prod}; \node[main node] (Pbio) [right = 2cm] {Pl Bio}; \node[main node] (Shade) [right =4cm] {Pl Shade}; \node[main node] (Prich) [right = 6cm] {Pl Rich}; \node[main node] (Sprod) [above = 1.1 cm,right = 0cm] {St Prod}; \node[main node] (Sbio) [above = 1.1cm,right = 2cm] {St Bio}; \node[main node] (Srich) [above = 1.1cm, right = 6cm] {St Rich}; \node[main node] (Suit) [right = 8cm] {Pl Suit}; \node[rounded corners,dotted,inner sep=0pt,fill=gray!10,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95] (Hidden) [below=1.5cm, right =4cm] {Hidden}; \node[rounded corners,dotted,inner sep=0pt,fill=gray!10,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95] (Hidden2) [above=2.5cm, right =6cm] {Hidden}; \node[rounded corners,dotted,inner sep=0pt,fill=gray!10,draw,font=\sffamily, minimum width = 1.5cm, minimum height = .5cm, scale=0.95] (Hidden3) [above=2.5cm, right =2cm] {Hidden}; \tikzset{>=latex} \path[color=black!20!blue,style={->}] (Suit) edge node {} (Srich) (Pprod) edge node {} (Srich) (Pbio) edge node {} (Shade) (Sbio) edge node {} (Pbio) (Sbio) edge node {} (Prich) (Srich) edge node {} (Prich) (Sprod) edge node {} (Pprod) (Sprod) edge node {} (Prich) (Sprod) edge node {} (Shade) (Shade) edge node {} (Prich) (Pbio) edge node {} (Pprod) ; \path[color=black!20!red, style={<->}] ; \path[color=black!20!yellow, thick,style={->}] (Hidden) edge node {} (Suit) (Hidden) edge node {} (Pprod) (Hidden) edge node {} (Sbio) (Hidden2) edge node {} (Suit) (Hidden2) edge node {} (Sbio) (Hidden2) edge node {} (Sprod) (Hidden3) edge node {} (Srich) (Hidden3) edge node {} (Sbio) (Hidden3) edge node {} (Sprod) ; ` \end{tikzpicture} \caption[Data example: model discovered by MBANG]{\label{fig:discoveredMBANG}Model discovered by MBANG.} \end{figure} \section{Further Discussion}\label{sec:5} In this paper we proposed a high-order cumulant based algorithm for discovering hidden variable structure in non-Gaussian LSEMs. Note that our Algorithm~\ref{alg:2} can be used on top of any procedure that recovers a mixed graph $G=(V, \mathcal D, \mathcal B)$ with directed and bidirected edges only and an estimate of the direct effects matrix $B$. We chose the BANG algorithm as this first step since it applies to a large class of graphs: bow-free acyclic mixed graphs. Second, the performance of our algorithm is closely related to the error distribution, and the density and size of the graph. For example, when the errors are unif($-5,\, 5$) and the number of vertices is 7, as the edge number increases from 8 to 20, the correct rate drops from $78\%$ to $1\%$. Also, if the density is medium, as the number of vertices increases from 5 to 7, the correct rate drops from $78\%$ to about $40\%$. Compared to the uniform distribution, the exponential distribution has a much milder drop in correct rate. For example, when the sample size is 50000, the correct rate for exp(1) drops from $70\%$ to $61\%$ as the graph density increases from sparse to very dense (almost complete). Note, however, that this drop is also present in the output of the BANG algorithm itself. Last, while we proved that Algorithm~\ref{Alg:1} finds the true graph given enough samples, it would be interesting to know the exact amount of samples needed in both BANG and Algorithm~\ref{alg:2}, as well as the nominal levels for the independence tests in BANG and in our cumulant tests. \section*{Acknowledgements} We thank Mathias Drton and Samuel Wang for helpful discussions regarding their algorithm~\cite{BANG}. We also thank Jean-Baptiste Seby for a helpful discussion at an early stage of the project. ER was supported by an NSERC Discovery Grant (DGECR-2020-00338). YL was supported by a WLIURA in the summer of 2020. \bibliographystyle{alpha}
{'timestamp': '2020-10-13T02:24:16', 'yymm': '2010', 'arxiv_id': '2010.05306', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05306'}
arxiv
\section{Introduction} Melanoma is the most deadly form of skin cancer, but it can be cured with minor surgery if caught early enough. Fast and accurate diagnosis could tremendously benefit doctors and patients. Recent advancements in deep learning based computer vision have pushed model performance to be close to (or exceed in some cases) human expert level in many medical fields. Besides accuracy, model based diagnosis has the advantage of easy scaling up and could be more accessible than doctors in certain regions. At a minimum, it could be a great assistance in a dermatologist's toolbox. In SIIM-ISIC Melanoma Classification challenge, competitors are asked to build models to identify melanoma using images of skin lesions and metadata. More than 3300 teams participated in the competition. In this paper, we present our winning solution. For a deep learning model to work well, it usually requires three things: (1) large amount of data, (2) big models, (3) competitive model design and training techniques. Our solution addresses point 1 by using both image data and metadata from both last year and this year's competitions. Point 2 is answered by a diverse group of state-of-the-art models (mostly EfficientNets \cite{efficientnet}) trained with various input sizes and setup. Finally, we solve point 3 by good choices of validation strategy and classification target. In section 2, we explain the validation strategy in more details. Model architecture and the use of metadata are discussed in section 3. We then describe our augmentations and training setup in section 4. Lastly, the ensemble and scores are presented in section 5. \section{Validation strategy} In any machine learning project, it is critical to set up a trustworthy validation scheme, in order to properly evaluate and compare models. This is especially true if the dataset is small to medium size, or the evaluation metric is unstable, which is the case of this competition. There are 33k images in train data. However, only 1.76\% are positive samples (i.e., malignant). The small number of positives causes the AUC metric to be very unstable, even with 5-fold cross validation. Our solution to this problem is to use both last year (including 2018 and 2019) and this year's data (2020), and do 5-fold cross validation on the combined data. Even though last year's data is smaller (25k), it has 10 times (17.85\%) the positive sample ratio, making the AUC much more stable. We refer to this metric as $\textbf{cv\_all}$. For each experiment, we also track $\textbf{cv\_2020}$ as a sanity check. It is calculated on the 2020 data only (even though the model is trained on combined data). The unstable score problem is even worse on public leaderboard (LB), with its data size being only one tenth of the training set. Throughout the competition, we did not use public LB score feedback in any way when developing models. In fact, we found that the public LB scores are so noisy that its correlation with $\textbf{cv\_all}$ is essentially 0 for the single models we had submitted. For ensembles, this problem is alleviated to a certain degree, as the noise from single models are averaged out. The bigger the ensemble, the more stable the LB score. \section{Model architecture and metadata} For a typical image classification problem, the standard approach is to take a deep CNN model (such as the most popular EfficientNet) trained on ImageNet, replace the last layer so that the output dimension equals the target's dimension, and fine tune it on the specific dataset. Our winning solution follows the same road map with two twists: using diagnosis as target and adding metadata in some models. The target to predict in this year's competition is binary---benign (i.e. no melanoma) or malignant (i.e. melanoma). We noticed that the target information is included in the diagnosis column: target is malignant if and only if diagnosis is melanoma. But diagnosis column is more granular when an image is benign. We believed using diagnosis as target to train the model could give the model more information. The fact that diagnosis was the target to predict in last year's competition makes this choice more logical. There is a small problem though. The set of diagnosis is different between this year and last year. We solved it by mapping this year's diagnosis to last year's according to the descriptions on last year's website\footnote{https://challenge2019.isic-archive.com/}. See Table \ref{tab:targets} for the mapping. There are 9 target values in most of our models. In one model, we only used 4 target values (NV, MEL, BKL and Unknown) by mapping the other five (*) to Unknown.\\ \begin{table*}[ht] \begin{center} \begin{tabular}{lll} \toprule 2019 Diagnosis & 2020 Diagnosis & Target \\ \toprule NV & nevus & NV \\ \hline MEL & melanoma & MEL \\ \hline BCC & & BCC* \\ \hline \multirow{4}{*}{BKL} & seborrheic keratosis & \multirow{4}{*}{BKL} \\ & lichenoid keratosis & \\ & solar lentigo & \\ & lentigo NOS & \\ \hline AK & & AK* \\ \hline SCC & & SCC* \\ \hline VASC & & VASC* \\ \hline DF & & DF* \\ \hline & cafe-au-lait macule & \multirow{2}{*}{Unknown} \\ & atypical melanocytic proliferation & \\ \bottomrule \end{tabular} \caption{\textbf{Mapping from diagnosis to targets.} }\label{tab:targets} \end{center} \end{table*} This means that the last layer of our classification model has 9-dimensional output. It is trained with cross entropy loss. When calculating AUC score and making submission, we take the MEL class's probability. The second twist in the CNN model is the addition of 14 metadata features in some models: $\textbf{sex}$, $\textbf{age\_approx}$, 10 one-hot encoded $\textbf{anatom\_site\_general\_challenge}$ features, $\textbf{image\_size}$ in bytes and $\textbf{n\_images}$, where $\textbf{n\_images}$ is the number of all images of that patient in the data. The metadata go through two fully connected layers before being concatenated with the CNN features, which then go to the final fully connected layer. The model architecture with metadata is illustrated in Figure \ref{fig:model}. In three of four metadata models, the two hidden layers have dimensions 512 and 128 as in the figure. In another metadata model, they are 128 and 32. We observe that models with images only perform better than metadata models overall, but the addition of of metadata models in the ensemble provides good model diversity. \begin{figure}[] \centering \includegraphics[width=1\textwidth]{meta_NN.png} \caption{\textbf{Model architecture of metadata models.} } \label{fig:model} \end{figure} \section{Augmentations and training setup} In small to medium sized datasets, image augmentation is important to prevent overfit. We used in our pipeline the following augmentations from the popular and powerful Pytorch augmentation library Albumentations \cite{albu} : Transpose, Flip, Rotate, RandomBrightness, RandomContrast, MotionBlur, MedianBlur, GaussianBlur, GaussNoise, OpticalDistortion, GridDistortion, ElasticTransform, CLAHE, HueSaturationValue, ShiftScaleRotate, Cutout\cite{cutout}. Figure \ref{fig:aug} is an illustration of the before-after of these augmentations. \begin{figure}[] \centering \includegraphics[width=1\textwidth]{augmentations.png} \caption{Training augmentation of 6 random images. Top row: original images; bottom row: augmented images.} \label{fig:aug} \end{figure} For training schedule, we used cosine annealing with one warm up epoch \cite{cosine}. The total number of epochs is 15 for most models. The initial learning rate of the cosine cycle is tuned for each model, which ranges from $1e-4$ to $3e-4$. The learning rate in the warm up epoch is always one tenth of the initial learning rate of the cosine cycle. Batch size is 64 for all models. All training were done on NVIDIA Tesla V100 GPUs in mixed precision. Up to 8 GPUs were used in parallel. \section{Ensemble} In order to make the ensemble stronger, we trained a variety of diverse models. 18 models were selected to comprise the final ensemble as listed in Table \ref{tab:score}. The model diversity comes from multiple angles. \begin{itemize} \item Backbones: EfficientNet B3, B4, B5, B6, B7, SE-ResNeXt-101 \cite{senet}, ResNeSt-101 \cite{resnest} \item Different targets: Model 9 has only 4 classes \item 5 folds are split differently among models \item Resized image input sizes: 384, 448, 512, 576, 640, 768 and 896 \item 4 of the 18 models used metadata with different hidden layer dimensions \end{itemize} The scores of the 18 single models demonstrate that the stability of the 4 metrics are: $\textbf{cv\_all} > \textbf{cv\_2020} > \textbf{private\_LB} > \textbf{public\_LB}$, as measured by their respective standard deviations 0.0012, 0.0043, 0.0060, 0.0093. The final ensemble is a simple average of the 18 models' probability ranks. In other words, we transform each model's probability predictions to uniform [0,1] before averaging them. \begin{table*}[ht] \begin{center} \small \setlength\tabcolsep{1.5pt} \begin{tabular}{clcccccccccc} \toprule \multicolumn{1}{l}{Model} & Backbone & Target & \multicolumn{1}{l}{Input} & \multicolumn{1}{l}{Resize} & Metadata & \multicolumn{1}{l}{Init lr} & \multicolumn{1}{l}{Epochs} & \multicolumn{1}{l}{cv\_all} & \multicolumn{1}{l}{cv\_2020} & \multicolumn{1}{l}{private\_LB} & \multicolumn{1}{l}{public\_LB} \\ \hline 1 & B3 & 9c & 768 & 512 & yes & 3e-5 & 18 & 0.9762 & 0.9300 & 0.9305 & 0.9182 \\ 2 & B4 & 9c & 768 & 640 & & 3e-5 & 15 & 0.9767 & 0.9400 & 0.9299 & 0.9342 \\ 3 & B4 & 9c & 768 & 768 & & 3e-5 & 15 & 0.9771 & 0.9408 & 0.9264 & 0.9251 \\ 4 & B4 & 9c & 768 & 640 & yes & 3e-5 & 15 & 0.9765 & 0.9408 & 0.9302 & 0.9221 \\ 5 & B4 & 9c & 1024 & 896 & & 2e-5 & 15 & 0.9744 & 0.9390 & 0.9320 & 0.9281 \\ 6 & B4 & 9c & 512 & 448 & & 3e-5 & 15 & 0.9748 & 0.9307 & 0.9213 & 0.9002 \\ 7 & B5 & 9c & 512 & 384 & yes & 3e-5 & 15 & 0.9752 & 0.9329 & 0.9167 & 0.9350 \\ 8 & B5 & 9c & 768 & 640 & & 1.5e-5 & 15 & 0.9771 & 0.9428 & 0.9291 & 0.9216 \\ 9 & B5 & 4c & 768 & 640 & & 1.5e-5 & 15 & 0.9765 & 0.9384 & 0.9362 & 0.9260 \\ 10 & B5 & 9c & 512 & 448 & & 3e-5 & 15 & 0.9751 & 0.9397 & 0.9363 & 0.9387 \\ 11 & B6 & 9c & 768 & 640 & & 3e-5 & 15 & 0.9756 & 0.9444 & 0.9408 & 0.9283 \\ 12 & B6 & 9c & 768 & 576 & & 3e-5 & 15 & 0.9761 & 0.9443 & 0.9266 & 0.9245 \\ 13 & B6 & 9c & 512 & 448 & & 3e-5 & 15 & 0.9742 & 0.9383 & 0.9261 & 0.9154 \\ 14 & B7 & 9c & 512 & 384 & yes & 3e-5 & 15 & 0.9748 & 0.9394 & 0.9193 & 0.9170 \\ 15 & B7 & 9c & 768 & 576 & & 1e-5 & 15 & 0.9764 & 0.9432 & 0.9260 & 0.9271 \\ 16 & B7 & 9c & 768 & 640 & & 1e-5 & 15 & 0.9754 & 0.9440 & 0.9304 & 0.9115 \\ 17 & SE\_X101 & 9c & 768 & 640 & & 3e-5 & 15 & 0.9739 & 0.9428 & 0.9295 & 0.9337 \\ 18 & Nest101 & 9c & 768 & 640 & & 2e-5 & 15 & 0.9728 & 0.9396 & 0.9320 & 0.9267 \\ \hline \multicolumn{1}{l}{Ensemble} & & & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \textbf{0.9845 } & \textbf{0.9600} & \textbf{0.9490} & \textbf{0.9442} \\ \bottomrule \end{tabular} \caption{\textbf{Model configuration and scores.} Model 1 to 16 are EfficientNets. Model 17 is SE-ResNext101. Model 18 is ResNest101. All models have 9 classes except model 9 which has 4 classes. Images of dimension ``Input'' are read from the disk then resized into ``Resize'' dimension before being fed to the model. ``Init lr'' is the learning rate of warm up epoch. All models are trained for 15 epochs except for Model 1 which is trained for 18.}\label{tab:score} \end{center} \end{table*} \bibliographystyle{plain}
{'timestamp': '2020-10-13T02:25:51', 'yymm': '2010', 'arxiv_id': '2010.05351', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05351'}
arxiv
\section{Introduction} The Arabic language is customarily written without marking the diacritic characters that indicate vowels, their absence, long consonants etc. This results in numerous possible readings for individual word forms, which is a major challenge, for instance, in natural language processing. Additionally, this ambiguity poses difficulties for the non-native learners of the language who might not be aware of the correct pronunciation or lexeme in question when reading text. Having diacritics in place is beneficial for any endeavors in processing speech computationally. For text-to-speech applications, the missing diacritics and the phonemes they represent have to be predicted one way or another before vocalizing the text as synthesized speech. Furthermore, the inverted process of converting speech to text can benefit from data that has diacritics in place as it brings the textual representation closer to phonetic realization. Although diacritization of Modern Standard Arabic is a topic that has received quite some attention in the academic research, much less research has been conducted on historical Arabic. The dictionary data our research is based on is not linguistically very different from Modern Standard Arabic, but as it nevertheless represents an older variety, the differences are particularly pronounced in different lexicon and genre. Although Medieval Arabic and Modern Standard Arabic have a lot in common, capturing all the nuances with tools tailored for the modern language variant is not possible without tools that have been built specifically for historical data. As Medieval Arabic texts are becoming increasingly available in digital format, due to numerous projects involving their preservation and digitization, there is an increasing need for NLP applications that work within this domain as well. Furthermore, diacritization of Arabic text reduces the level of ambiguity of the tokens. This is useful for such applied NLP tasks where a high degree of ambiguity is an issue. For instance when studying word usage in historical texts any kind of noise or ambiguity in the data is undesirable. In a wider context, work on Arabic diacritization will also benefit other languages that have similar, largely ambiguous orthographies, such as Hebrew or Aramaic. Besides adding missing vowel characters, the task at hand is similar to adding other comparable information, i.e. historically motivated circumflexes in French or orthographically unmarked weight signs in Russian. From this point of view, the Arabic diacritization can be described as a task to recover linguistic information that is not fully encoded in the character-level orthographic representation. There are systematically different possible readings for individual word forms, and the correct reading must be disambiguated by using the surrounding context. How challenging this task ends up being is very language specific, but it can be concluded that with sufficient linguistic context the task must be possible, as the native speakers are able to perform it successfully in their daily lives. The best working model presented in this paper has been released in an easy to use Python library\footnote{https://github.com/mikahama/haracat} \citelanguageresource{alnajjar_khalid_2020_3677375} in order to facilitate the reuse of the language resource. This also makes it easier to compare other approaches directly with our model. \section{Related Work} \begin{figure*}[!htb] \center{\includegraphics[width=15cm] {network.png}} \caption{\label{fig:network} A high level illustration of the character-level NMT architecture} \end{figure*} Early statistical approaches employ a hidden Markov model for restoration of Arabic diacritics \cite{10.3115/1118637.1118641}. They train their model on the Quran. They show that using a bigram model can improve over an unigram baseline. In the past, one take on adding diacritics to Arabic text was to use WFSTs (weighted finite state transducers) \cite{nelken2005arabic}. They combine FSTs of several different levels of abstraction: word level, letter level, and simple morphology. This line of work presents the rule-based tradition that was strong in the past in the field of NLP. Maximum-entropy models have been used to predict diacritics in the Arabic Treebank data \cite{zitouni2009arabic}. They model the problem as a sequence classification task. They use three different types of features lexical, segment-based and part-of-speech (POS) features for the model. LSTM networks have been used to predict diacritics on modern text \cite{abandah2015automatic}, they approach the problem as a sequence labeling task. In their approach, they train the model on a word level to predict the corresponding diacritized word forms. One limitation with this approach is that the model is limited to only operating with the exact words that were present in the training data. A similar word level LSTM has also been proposed by \cite{belinkov2015arabic}. SVMs (support vector machines) have also been used relatively recently for predicting Arabic diacritics \cite{darwish2017arabic}. Their system is divided into two components, the first of which adds diacritics to the core word and the second of which adds diacritics to the morphological ending. Apart from focusing on a historical language variant, our work is different from the existing contemporary LSTM based approaches by two key ways. First, we tackle this problem on the character level, which makes it possible for the model to learn to generalize diacritics even for words not present in the vocabulary. Secondly, we train our models to fully diacrtizise the input text. This means not only to predict the diacritics when absolutely needed for ambiguity resolution, but to always predict them. Diacritization as a task is in many ways comparable to the normalization of historical or dialect texts, although there are also numerous differences. Our work with Medieval Arabic locates to the context of NLP with historical language, although our goal is to retrieve the original diacritization, instead of i.e. generating the corresponding Modern Standard Arabic equivalents. Similarly spoken representations of vowels often differ significantly from these variants, prediction of which is an entirely different task. This, naturally, leaves many open possibilities for future research. \section{Data and Preprocessing} For the purpose of diacritic prediction, we use the online version of the Medieval Arabic dictionary Al-Qāmūs l-Mu\d{h}ī\d{t}: \citelanguageresource{arabic-dict}. The dictionary contains text fields (henceforth we refer to these as sentences) for each lemma, and all of these sentences have all the diacritics in place, even in the unambiguous cases. The dictionary is distributed by alphabet in the Clarin Virtual Language Observatory infrastructure\footnote{https://vlo.clarin.eu/} \citelanguageresource{goosen2014virtual} in XML format. We download dictionaries for every alphabet and extract the sentences. We clear all the extracted sentences from any diacritics with a regular expression. This results in a parallel data set of sentences with and without diacritics. The data consists of over 58,000 sentences with a sentence length of 8 words, on the average. We shuffle and split the data so that 70\% is used for training, 15\% for validation and 15\% for evaluation. \begin{figure}[!htb] \center{\includegraphics[width=7cm] {corpus_ambiguity.png}} \caption{\label{fig:ambi} Degree of ambiguity in the corpus on type level} \end{figure} Figure \ref{fig:ambi} shows the degree of ambiguity of the tokens without diacritics within the corpus. This means that 82.6\% of the words (types) have only one single possibility for their diacritized variant. The maximum number of different diacritizations a word can get is 22, but this occurs only for two words in the corpus. Thus this problem is mostly a one-to-one mapping problem for most of the words. \begin{figure}[!htb] \center{\includegraphics[width=7cm] {corpus_token_ambiguity.png}} \caption{\label{fig:ambi2} Degree of ambiguity in the corpus on token level} \end{figure} However, Figure \ref{fig:ambi2} shows that on the token level, there is more ambiguity, as only 35.5\% of the tokens belong to the category of only one possible diacritization. It is more frequent on the token level to have multiple possible alternatives. This indicates that ambiguity resolution becomes important for the most frequent words. \section{Predicting Diacritics} \begin{table*}[!ht] \centering \small \begin{tabular}{|l|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline model & \begin{tabular}[c]{@{}c@{}}No \\ prediction\end{tabular} & baseline & \begin{tabular}[c]{@{}c@{}}1\\ word\end{tabular} & \begin{tabular}[c]{@{}c@{}}2\\ words\end{tabular} & \begin{tabular}[c]{@{}c@{}}3\\ words\end{tabular} & \begin{tabular}[c]{@{}c@{}}4\\ words\end{tabular} & \textbf{\begin{tabular}[c]{@{}c@{}}5\\ words\end{tabular}} & \begin{tabular}[c]{@{}c@{}}6\\ words\end{tabular} & \begin{tabular}[c]{@{}c@{}}7\\ words\end{tabular} & \begin{tabular}[c]{@{}c@{}}8\\ words\end{tabular} & \begin{tabular}[c]{@{}c@{}}9\\ words\end{tabular} & \begin{tabular}[c]{@{}c@{}}10\\ words\end{tabular} & \begin{tabular}[c]{@{}c@{}}whole \\ sentence\end{tabular} \\ \hline WER & 87.98 & 61.20 & 42.63 & 37.24 & 35.11 & 34.40 & \textbf{34.09} & 36.30 & 39.08 & 41.90 & 46.59 & 49.20 & 58.72 \\ \hline \end{tabular} \caption{Results of the models} \label{tab:results} \end{table*} As character-level neural machine translation (NMT) models have achieved good results before in a variety of similar tasks such as spelling normalization \cite{adouane2019normalising,partanen2019dialect} and OCR post-correction \cite{hamalainen2019paft}, we have decided to opt for a character-based approach on the task of diacritic prediction as well. Character level modeling makes it possible for the model to learn diacritization even for words that have not appeared in the training data as the unit of operation is a character rather than an entire word. We train an NMT model using a long short-term memory (LSTM) based bi-directional recurrent neural network (BRNN) architecture on a character level for modeling the problem. As opposed to a regular one-directional RNN, the BRNN model can benefit from both left and right contexts when predicting the diacritics, as the encoding takes place from both the beginning and end of the sequence. The architecture consists of two encoding layers and two decoding layers and the general global attention model \cite{luong2015effective}. The network is illustrated in Figure \ref{fig:network}. We train the models by using the OpenNMT Python package \cite{opennmt} by otherwise resorting to the default settings for training that are predefined in the package. This also means that the training is done for 100,000 steps. We experiment with multiple scenarios in terms of the length of the input sequence. We train models for predicting diacritics one word at a time, multiple words at a time and entire sentences. We experiment with chunk sizes from 1 to 10 tokens at a time. In this way, we attempt to find the optimal length of the sequence for predicting the diacritics. The longer the sequence, the more context it gives, on the one hand, and, on the other, long sequences tend to make the model perform worse \cite{partanen2019dialect}. We train all the models with the same random seed and same division between training, validation and testing data in order to make their intercomparison meaningful. When training the model, the words are split into characters that are separated by white spaces. This also means that diacritics appear as separate tokens on the target side. Word boundaries in the models that are trained with more than one word at a time, multi-word elements, are marked with underscores (\_). \novocalize \begin{table} \resizebox{\columnwidth}{!}{% \begin{tabular}{|c|r|} \hline Input & \begin{tabular}[c]{@{}l@{}}\begin{RLtext}wkAn Al.s.hAbT ytmAz.hwn .ht_A \end{RLtext} \\ \begin{RLtext}ytbAd.hwn bAlb.ty_h, f'i_dA .hzbhm\end{RLtext}\\ \begin{RLtext}'mr kAnwA hm AlrjAl '.s.hAb Al'mr \end{RLtext}\end{tabular} \\ \hline Prediction & \begin{tabular}[c]{@{}l@{}}\begin{RLtext}wkAna Al.sxxa.hAbaTu yatamaAza.huwna .ht_A \end{RLtext}\\ \begin{RLtext}yatbAda.hwna bAlbi.txxiy_h, f'i_dA .hazabahum"\end{RLtext} \\ \begin{RLtext}'m"ruN kAnwA humu AlrxxijAlu '.s".hAbu Al"'am"ri \end{RLtext} \end{tabular} \\ \hline Correct & \begin{tabular}[c]{@{}l@{}}\begin{RLtext}wkAn Al.s.hAbTu ytmAza.hwna .ht_A \end{RLtext}\\ \begin{RLtext}yatbAda.hwna bAlbi.txxiy_hi, f'i_dA .hazabahum" \end{RLtext}\\ \begin{RLtext}'m"ruN kAnwA humu AlrxxijAla '.s.hAba Al"'am"ri\end{RLtext}\end{tabular} \\ \hline \end{tabular}% } \caption{An example of the input, output and gold data} \label{tab:example} \end{table} \section{Results \& Evaluation} In this section we report and discuss the results of the models. As a baseline, we use a popular online tool\footnote{http://www.tahadz.com/mishkal} for adding diacritics to Arabic script. We report the word error rates\footnote{WER is counted with an open source tool https://github.com/nsmartinez/WERpp} (WER) for each model. The lower the word error rate, the better the model is at predicting the diacritics. WER is a common metric derived from Levenshtein edit distance \cite{Levenshtein66Binary}, and it takes into account the number of deletions $D$, substitutions $S$, insertions $I$ and the number of correct words $C$. It is calculated per sentence with the following formula: \begin{equation} WER = \frac{S + D + I}{S + D + C} \end{equation} It is important to note that we are not counting diacritic error rate, as such an evaluation metric can easily give overly positive looking results as even partially correctly predicted diacritics for a word would lower the error rate. When focusing on WER, only word with fully correctly predicted diacritics will be considered as correct, any partially wrong predictions will lead to the entire word as counted erroneous. In this respect our evaluation method differs from commonly used metrics such as DER (Diacritic Error Rate), but in our opinion WER gives the most realistic picture about the accuracy. In downstream tasks where the model could be used it would customarily be very important that complete words are diacritized correctly. Table \ref{tab:results} shows the results of the models. The first column named \textit{No prediction} shows the WER when no diacritics are added to the words at all. This means comparing sentences without diacritics to the ones with diacritics. All of our NMT models outperform the baseline system. Table \ref{tab:example} shows an example sentence with diacritics predicted by the five word character level model. The results suggest that having five words at a time when predicting the diacritics is optimal for the model. It gives enough contextual cues without making the sequences overly long. The results get progressively worse by removing or adding more words. The best performing character based method reduces the WER by 53.89. Although the accuracy reached still leaves space for further experimentation, the reduction in WER is still very large and considerable. Further work is certainly needed to improve the model, and, for instance, better handling of errorenous predictions would be useful, but already the work presented here improves significantly from the previous baseline. \section{Conclusions and Future Work} In this paper we have approached the challenging problem of dealing with a Medieval language form of Arabic in terms of its full diacritization. Our character based NMT approach can also deliver diacritization for words not found in the in the vocabulary, as the model learns mappings from characters rather than words. Needless to say, it would be interesting in the future to attempt combining word- and character-level methods. We have released the model trained on chunks of five words as a Python library. We have put special care in making the library as easy to use as possible so that it is not just a research resource that is difficult to install, but a library that is easy to plugin to any Python based code with next to no prior knowledge on NLP required. The library can be installed by using pip\footnote{pip install haracat}, the defacto tool for managing Python libraries, since it is distributed on PyPi with full versioning and releases uploaded automatically to Zenodo for permanent storage. As we have used only openly available resources and infrastructure, it is easy to extend to work with further resources and experiments. An important finding that has not been studied to a satisfactory degree in the literature is the effect the number of words has on the results. With shorter chunks of words, the model does not see enough context to reach a feasible amount of accurate predictions, while with longer chunks the model sees too much context and loses its meaningfulness to the prediction. The optimal number of words for the performance seems to be five. In the future, however, it would be interesting to see if this is specific to the NMT architecture used in this paper or specific to the data set the model was trained on, or whether it is a tendency observable across architectures and data sets. In this vein, there is also the possibility that different tasks are just linguistically difficult to process in different degrees, and in this context various results can contain important information about linguistic complexity. As these are tasks a human agent with sufficient linguistic knowledge is able to perform, the conditions under which neural networks are able to learn similar processing may tell about contextual window necessary for various tasks. \section{Bibliographical References}\label{reference} \bibliographystyle{lrec}
{'timestamp': '2020-10-13T02:22:54', 'yymm': '2010', 'arxiv_id': '2010.05269', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05269'}
arxiv
\section{Introduction}\label{sec:intro} Point-cloud representations provide detailed information of objects and environments. The development of novel acquisition techniques, such as laser scanning, digital photogrammetry, light detection and ranging (LIDAR), 3D scanners, structure-from-motion (SFM), among others, has increased the interest of using point cloud representation in various applications such as digital preservation, surveying, autonomous driving~\cite{LIDAR_3d_object_detection}, 3D gaming, robotics~\cite{roomba:2002}, and virtual reality~\cite{3d_tracking_AR}. In return, this new interest has fueled the development of machine learning frameworks that use point clouds as input. Historically, early methods used a preprocessing stage that extracted meticulously hand-crafted features from the point cloud, which were subsequently fed to a neural network~\cite{visualSimilarity:2003,RusuBlodow:2008,RusuBlodow:2009,wave_kernel:2011}, or they relied on voxelization of the geometry~\cite{3DShapeRetrieval:2017,ShapeNets:2015,Riegler_2017_CVPR,VoxNet:2015}. The pointNet architecture~\cite{PointNet:2017} was the first to handle raw point cloud data directly and learn features on the fly. This work has spawned several related approaches, aiming to attenuate drawbacks from the original methodology, such as pointNet++~\cite{PointNet++}, or to increase the accuracy and range of application \cite{Wang_2019_CVPR,DGCNN:2020,PointCNN,RS-CNN:2019}. Even though such methods have been quite successful for machine learning problems, they rely on an assumption of locality, which may produce large errors when the underlying task at hand exhibits long-range interactions (LRIs). To capture such interactions using standard convolutional layers, one can use wider window sizes, deeper networks, and/or a large number of features, which may increase the computational cost significantly. Several approaches have been proposed to efficiently capture such interactions in tasks such as semantic segmentation, of which the ideas we briefly summarize below. In the multi-scale type of approaches, features are progressively processed and merged. Within this family, there exist several variants, where the underlying neural networks can be either recursive neural networks~\cite{Ye_2018_ECCV}, convolutional layers \cite{MSGCNN:2019,SpiderCNN} or autoencoders \cite{FoldNet,Deng_2018_ECCV}. Some works have proposed skip connections, following an U-net~\cite{U-Net} type architecture~\cite{VoxelNet:2018,PointNet++}, while others have focused on using a tree structure for the clustering of the points~\cite{KD-nets:2017,3DContextNet:2019,MRTN3D:2018}, or using an reference permutohedral lattices to compute convolutions~\cite{bilateralNN:cvpr:2016} whose results are interpolated back to the point cloud~\cite{splatnet:2018}. Another line of work, relies on interpreting the point cloud as a graph and use spectral convolutions~\cite{Spectral_networks,CNN_fast_CNN}. In applications of machine learning to scientific computing, several classical multilevel matrix factorizations have been rewritten in the context of machine learning~\cite{kondor_2016}, which have been adapted to handle long-range interactions in the context of end-to-end maps using voxelized geometries in~\cite{MNNH,MNNH2,Khoo_YingSwitchNet:2019,FanYing:RTE} resulting in architectures similar to U-nets~\cite{U-Net}, which have been extended to point clouds in~\cite{FMMNetwork}. The efficient treatment of LRI for point clouds is also a prominent problem in many physical applications such as molecular modeling and molecular dynamics simulation. While long-range electrostatic interactions are omnipresent, it has been found that effectively short-ranged models can already describe the $N$-body potential and the associated force field~\cite{BehlerParrinello2007,zhang2018deep, zhang2018end} for a wide range of physical systems. There have also been a number of recent works aiming at more general systems beyond this regime of effective short-range interactions, such as the work of Ceriotti and co-workers~\cite{Andrea:long-range,Grisafi:multiscale,Jigyasa:Recursive,Rossi}, as well as related works~\cite{Kun:TensorMol,Ko:nonlocal,Matthew:wavelet,rupp2012fast,HuoRupp:UR,DengChen,Tristan,Zhang:DRI}. The general strategy is to build parameterized long-range interactions into the kernel methods or neural network models, so that the resulting model can characterize both short-range, as well as long-range electrostatic interactions. In the neural network context, the computational cost of treating the LRI using these methods can grow superlinearly with the system size. The idea of this work is aligned with the approaches in the molecular modeling community, which constructs a neural network layer to directly describe the LRI. In particular, we present a new \emph{long-range convolutional} (LRC)-layer, which performs a global convolutional operation in nearly-linear time with respect to number of units in the layer. By leveraging the non-uniform Fourier transform (NUFFT)~\cite{Dutt_Rokhlin:NUFFT:1993,NUFFT:2004,FINUFFT:2019} technique, the LRC-layer\footnote{See \cite{LRC-layer} for a light-weight implementation.} implements a convolution with a point-wise multiplication in the frequency domain with trainable weights known as {\em Fourier multipliers}. The NUFFT is based on the regular fast Fourier transform (FFT)~\cite{Cooley_Tukey:1965} with a fast gridding algorithms, to allow for fast convolution on unstructured data. This new LRC-layer provides a new set of descriptors, which can be used in tandem with the descriptors provided by short-range convolutional layers to improve the performance of the neural network. Efficient training of a neural network with the LRC-layer for capturing the information of LRIs is another challenging problem. Short-range models can often be trained with data generated with a relatively small computational box (called the small-scale data), and they can be seamlessly deployed in large-scale systems without significantly increasing the generalization error. On the other hand, long-range models need to be trained directly with data generated in a large computational box (called the large-scale data), and the generation process of such large-scale data can be very expensive. For instance, in molecular modeling, the training data is often generated with highly accurate quantum mechanical methods, of which the cost can scale steeply as $\mathcal{O}(N^{\alpha})$, where $N$ is the system size and $\alpha\ge 3$. Therefore it is desirable to minimize the number of samples with a large system size. In many applications, the error of the effective short-range model is already modestly small. This motivates us to propose a \emph{two-scale training strategy} as follows. We first generate many small-scale data (cheaply and possibly in parallel), and train the network without the LRC-laye . Then we use a small number of large-scale data, and perform training with both the short- and long-range convolutional layers. In order to demonstrate the effectiveness of the LRC-layer and the two-scale training procedure, we apply our method to evaluate the energy and force associated with a model $N$-body potential that exhibit tunable short- and long-range interactions in one, two and three dimensions. Our result verifies that the computational cost of the long-range layer can be reduced from $\mathcal{O}(N^2)$ using a direct implementation, to $\mathcal{O}(N)$ (up to logarithmic factors) using NUFFT. Furthermore, we demonstrate that the force, i.e. the derivatives of the potential with respect to \emph{all} inputs can be evaluated with $\mathcal{O}(N)$ cost (up to logarithmic factors). In terms of sample efficiency, we find that for the model problem under study here, the two-scale training strategy can effectively reduce the number of large-scale samples by over an order of magnitude to reach the target accuracy. \section{Long-range Convolutional Layer} \label{sec:nufft} Convolutional layers are perhaps the most important building-block in machine learning, due to their great success in image processing and computer vision. A convolutional layer convolves the input, usually an array, with a rectangular mask containing the trainable parameters. When the mask can be kept small (for example while extracting localized features), the convolution layer is highly efficient and effective. A different way for computing a convolution is to use the convolutional theorem as follows: (1) compute the Fourier transform of the input, (2) multiply with the Fourier transform of the mask, i.e.m the Fourier multiplier, and (3) inverse Fourier transform back. In this case, the trainable parameters are the DOFs of the Fourier multipliers and the Fourier transforms are computed using the fast Fourier transform (FFT). This alternative approach is particularly attractive for smooth kernels with large support (i.e., smooth long-range interactions) because the computational cost does not increase with the size of the mask. To the best of our knowledge, this direction has not been explored for LRIs and below we detail now to apply this to point clouds. Given a point cloud $\{x_i\}_{i=1}^{N} \subset \mathbb{R}^d$ and scalar weights $\{f_i\}_{i=1}^{N}$, we consider the problem of computing the quantity $u_i:= \sum_{j=1}^{N} \phi_\theta(x_i-x_j) f_j$ for each $i$. Here the function $\phi_\theta(\cdot)$ is the kernel with a \emph{generic} trainable parameter $\theta$. At first glance the cost of this operation scales as $\mathcal{O}(N^2)$: we need to evaluate $u_i$ for each point $x_i$, which requires $\mathcal{O}(N)$ work per evaluation. By introducing a generalized function $f(y)=\sum_if_i\cdot \delta(y-x_i)$ and defining a function $u(x) = \int \phi_\theta(x-y) f(y) dy$, one notices that $u_i$ is the value of $u(x)$ at $x=x_i$. The advantage of this viewpoint is that one can now invoke the connection between convolution and Fourier transform \begin{equation} \label{eq:kernel_application} \hat{u}(k) = \hat{\phi}_\theta(k) \cdot \hat{f}(k), \end{equation} where $\hat{\phi}_\theta(k)$ is a trainable Fourier multiplier. This approach is suitable for point clouds since the trainable parameters are decoupled from the geometry of the point cloud. To make this approach practical, one needs to address two issues: (1) the non-uniform distribution of the point cloud and (2) how to represent the multiplier $\hat{\phi}_{\theta}(k)$. {\bf Non-uniform distribution of the point cloud } Equation \ref{eq:kernel_application} suggests that one can compute the convolution directly using the convolution theorem, which typically relies on the FFT to obtain a low-complexity algorithm. Unfortunately, $\{x_i\}_{i= 1}^{N}$ do not form a regular grid, thus FFT can not be directly used. We overcome this difficulty by invoking the NUFFT\footnote{See Appendix \ref{appendix:nufft} for further details.}~\cite{Dutt_Rokhlin:NUFFT:1993}, which serves as the corner-stone of the LRC-layer. \begin{algorithm}[h] \caption{Long-range convolutional layer} \label{alg:nufft_layer} \begin{algorithmic}[1] \Statex Input: $\{x_i\}_{i =1} ^{N}$, $\{f_i\}_{i =1} ^{N}$ \Statex Output: $u_i = \sum_{j=1 }^{N} f_j \phi_\theta(x_i - x_j), \,\, \text{for } i=1,...,N$. \State Define the generalized function: $f (x) = \sum_{j=1}^{N} f_j \delta(x- x_j)$ \State Mollify the Dirac deltas: $f_{\tau}(x) = \sum_{j=1}^{N} f_j g_{\tau}(x- x_j)$, where $g_{\tau}$ is defined in Appendix \ref{appendix:nufft} \State Sample in a regular grid: $ f_{\tau}(x_{\ell}) = \sum_{j=1}^{N} g_{\tau}(x_{\ell} - x_j)$ for $x_\ell$ in grid of size $L_{\texttt{FFT}}$ in each dim \State Compute FFT: $F_\tau(k) = \mathcal{FFT}(f_{\tau})(k)$ \State Re-scale the signal: $F(k)=\sqrt{\frac{\pi}{\tau}} e^{k^{2} \tau} F_{\tau}(k)$ \State Multiply by Fourier multipliers: $\hat{v}(k) = \hat{\phi}_\theta (k)\cdot F(k)$ % \State Re-scale the signal: $\hat{v}_{-\tau}(k) = \sqrt{\frac{\pi}{\tau}} e^{k^{2} \tau} \hat{v}(k) $ \State Compute IFFT: $u_{-\tau}(x_\ell) = \mathcal{FFT}^{-1}(\hat{v}_{-\tau})(x)$ for $x_\ell$ on the regular grid \State Interpolate to the point cloud: $u_i = u(x_i) = u_{-\tau} * g_{\tau}(x_i)$ \end{algorithmic} \end{algorithm} The LRC-layer is summarized in Alg.~\ref{alg:nufft_layer}, where $\tau$ is chosen following~\cite{Dutt_Rokhlin:NUFFT:1993}. The inputs of this layer are the point cloud $\{x_i\}_{i=1}^{N}$ and the corresponding weights $\{f_i\}_{i=1}^{N}$. The outputs are $u_i\equiv u(x_i)$ for $i = 1, ..., N$. The number of elements in the underlying grid $N_{\texttt{FFT}}=L_{\texttt{FFT}}^d$ is chosen such that the kernel is adequately sampled and the complexity remains low. The LRC-layer is composed of three steps: (1) It computes the Fourier transform from the point cloud to a regular grid using the NUFFT algorithm (lines $2-5$ in Alg.~\ref{alg:nufft_layer}). (2) It multiplies the result by a set of trainable Fourier multipliers (line $6$ in Alg.~\ref{alg:nufft_layer}). (3) It computes the inverse Fourier transform from the regular grid back to the point cloud (lines $7-9$ in Alg.~\ref{alg:nufft_layer}). Within the LRC-layer in Alg.~\ref{alg:nufft_layer}, the only trainable component is the parameter $\theta$ of the Fourier multiplier $\hat{\phi}_{\theta}(k)$. The remaining components, including the mollifier $g_\tau(\cdot)$ and the Cartesian grid size, are taken to be fixed. One can in principle train them as well, but it comes with a much higher cost. Among the steps of Alg.~\ref{alg:nufft_layer}, the sampling operator, the rescaling operator, the interpolation operator, and the Fourier transforms, are all {\em linear and non-trainable}. Therefore, derivative computations of backpropagation just go through them directly. Alg.~\ref{alg:nufft_layer} is presented in terms of only one single channel or feature dimension, i.e., $f_j\in \mathbf{R}$ and $u_i\in \mathbf{R}$. However, it can be easily generalized to multiple channels, for example $f_j\in \mathbf{R}^{d_1}$ and $u_i\in\mathbf{R}^{d_2}$. In this case, the Fourier multiplier $\hat{\phi}_{\theta}(k)$ at each point $k$ is a $d_2 \times d_1$ matrix, and all Fourier transforms are applied component-wise. {\bf Representation of the Fourier multiplier } A useful feature of the LRC-layer is that it is quite easy to impose symmetries on the Fourier multipliers. For example, if the convolution kernel $\phi_\theta(\cdot)$ is constrained to have parity symmetry, rotational symmetry, smoothness or decay properties, these constraints can be imposed accordingly on the coefficients of the Fourier multipliers $\hat{\phi}_{\theta}(k)$. When the size of the training data is limited, it is often necessary to reduce the number of trainable parameters in order to regularize the kernel. For example, we may parametrize the Fourier multiplier as a linear combination of several predetermined functions on the Fourier grid. This is the procedure used in molecular modeling \cite{Andrea:long-range,Kun:TensorMol,Ko:nonlocal}, and also in our numerical examples in \eqref{eq:parametrization}. We also remark that the LRC-layer described here can be applied to point clouds a way similar to a standard convolution layer applied to images and multiple LRC-layers can be composed on top of each other. \section{Learning the $N$-body potential} To demonstrate the effectiveness of the LRC-layer, we consider the problem of learning the energy and force associated with a model $N$-body potential in the context of molecular modelling. As mentioned in Section \ref{sec:intro}, the potential evaluation often invokes expensive ab-initio calculations that one would like to bypass for efficiency reasons. The setup of this learning problem is as follows. First, we assume access to a \emph{black-box} model potential, which consists of both short- and long-range interactions. However, internal parameters of the potential are inaccessible to the training architecture and algorithm. A set of training samples are generated by the model, where each sample consists of a configuration of the points $\{x_i\}$ along with the potential and force. Second, we set up a deep neural network that includes (among other components) the LRC-layer for addressing the long-range interaction. This network is trained with stochastic gradient type of algorithms using the collected dataset and the trained network can be used for predicting the potential and forces for new point cloud configurations. These two components are described in the following two subsections in detail. \subsection{Model problem and Data Generation} \label{section:model} \textbf{Model } We suppose that $\Omega = [0,L]^d$, and we denote the point cloud by $ \mathbf{x} = \{ x_i\}_{i =1}^{N} \subset \Omega \subset \mathbb{R}^d$, for $d = 1, 2,$ or $3$. We define the total energy, the local potential and the forces acting on particle $j$ by \begin{equation}\label{eqn:psi} U = \sum_{1\le i <j\le N} \psi (x_i-x_j), \qquad U_j(x) = \sum_{i\neq j} \psi (x_i-x),\qquad \text{and} \qquad F_j = - \partial_x U_j(x)|_{x=x_j}, \end{equation} respectively, where the interaction kernel $\psi(r)$ is a smooth function, besides a possible singularity at the origin and decreases as $\|r\| \rightarrow \infty$. \textbf{Sampling } We define a snapshot as one {\it configuration}\footnote{For the sake of clarity, we suppose that the number of particles at each configuration is the same.} of particles, $\mathbf{x}^{\ell} = \{x_j^{[\ell]}\}_{j = 1}^{N}$, together with the global energy $U^{[\ell]}$ and the forces $F^{[\ell]}$, where $\ell$ is the index representing the number in the training/testing set. We sample the configuration of particles $\mathbf{x}^{\ell}$ randomly, with the restriction that two particles can not be closer than a predetermined value $\delta_{\texttt{min}}$ in order to avoid the singularity. After an admissible configuration is computed we generate the energy and forces following Appendix \ref{appendix:data_generation}. This process is repeated until obtaining $N_{\texttt{sample}}$ snapshots. \subsection{Architecture} \label{sec:interactions} Our network architecture consists of separate descriptors for the short- interactions and long-range interactions, respectively. To capture the short-range interaction, we compute a local convolution using for each point only its neighboring points within a ball of predetermined radius. For the long-range interactions, we compute an all-to-all convolution using the LRC-layer introduced in Section \ref{sec:nufft}, whose output is distributed to each particle and then fed to a sequence of subsequent layers. \textbf{Short-range descriptor } For a given particle $x_i$, and an interaction radius $R$, we define $\mathcal{I}_i$, the interaction list of $x_i$, as the indices $j$ such that $\| x_i - x_j \| < R$, i.e., the indices of the particles that are inside a ball of radius $R$ centered at $x_i$. Thus for each particle $x_i$ we build the generalized coordinates $s_{i,j} = x_i - x_j$, and the short-range descriptor \begin{equation} \label{eq:localDescriptor} \mathcal{D}_{\texttt{sr}}^i = \sum_{j \in \mathcal{I}_i} f_{\theta}(s_{i,j}), \end{equation} where $f_{\theta}: \mathbb{R}^{d} \rightarrow \mathbb{R}^{m_{\texttt{sr}}}$ is a function represented by a neural network specified in Appendix~\ref{appeddix:descriptor}, where $m_{\texttt{sr}}$ is the number of short-range features. By construction $f_{\theta}(s)$ is smooth and it satisfies $f_{\theta}(s) = 0$ for $\|s\|>R$. \textbf{Long-range descriptor } We feed the LRC-layer with the raw point cloud represented by $\{x_i \}_{i = 1}^{N}$ with weights $\{f_i \}_{i = 1}^{N}$, which for simplicity can be assumed to be equal to one here, i.e., $f_i=1$ for $i=1,...,N$. The output of the layer is a two-dimensional tensor $u^k(x_i)$ with $i=1,\ldots,N$ and $k=1,\ldots,K_{\texttt{chnls}}$. Then for each $x_i$, its corresponding slice given by the vector $[u^1(x_i), u^2(x_i),\cdots, u^{K_\texttt{chnls}}(x_i)]$, is fed to a function $g_\theta : \mathbb{R}^{K_{\texttt{chnls}}} \rightarrow \mathbb{R}^{m_{\texttt{lr}}}$, which is represented by a neural network with non-linear activation functions. Here $\theta$ is a generic set of trainable parameters and $m_{\texttt{lr}}$ is the number of long-range features. The descriptor for particle $x_i$, which depends on all the other particles thanks to the LRC-layer, is defined by \begin{equation} \label{eq:nonlocalDescriptor} \mathcal{D}^i_{\texttt{lr}} = g_{\theta}(u^1(x_i), u^2(x_i), \cdots, u^{K_{\texttt{chnls}}}(x_i)) \end{equation} \textbf{Short-range network } When only the short-range interaction is present, the short-range descriptor for each particle is fed particle-wise to a fitting network $\mathcal{F}_{\texttt{sr}}: \mathbb{R}^{m_{\texttt{sr}}} \rightarrow \mathbb{R}$. In this case $\mathcal{F}_{\texttt{sr}}(\mathcal{D}_{\texttt{sr}}^i)$ only depends on particle $x_i$ and its neighbors. Finally, the contributions from each particle are accumulated so the short-range neural network (NN) energy and forces are given by \begin{equation} \label{eq:energy_forces_total} U^{\texttt{NN}}_{\texttt{sr}} = \sum_{ i = 1}^{N} \mathcal{F}_{\texttt{sr}}(\mathcal{D}_{\texttt{sr}}^i) \qquad \text{and} \qquad \left( F^{\texttt{NN}}_{\texttt{sr}} \right) _j = - \partial_{x_j} U^{\texttt{NN}}_{\texttt{sr}} \end{equation} respectively (see Fig.~\ref{fig:simplestructure}(left)). The derivatives are computed using Tensorflow~\cite{tensorflow2015} directly. This network as shown by \cite{zhang2018end} is rotation, translation, and permutation invariant~\cite{ZaheerKotturRavanbakhshEtAl2017}. \textbf{Full-range network }When both the short-range and long-range interactions are present, the long range descriptor and the local descriptor are combined and fed particle-wise to a fitting network $\mathcal{F}: \mathbb{R}^{m_{\texttt{sr}}+m_{\texttt{lr}} } \rightarrow \mathbb{R}$ to produce the overall neural network (NN) energy and forces \begin{equation} U^{\texttt{NN}} = \sum_{ i = 1}^{N} \mathcal{F}(\mathcal{D}^i_{\texttt{sr}}, \mathcal{D}^i_{\texttt{lr}}), \qquad \text{and} \qquad \left( F^{\texttt{NN}}\right) _j = - \partial_{x_j} U^{\texttt{NN}} \end{equation} respectively (see Fig.~\ref{fig:simplestructure}(right)). Following Section \ref{sec:nufft}, the long-range descriptor is translation invariant by design and can be easily made rotation invariant. Furthermore, it is well known~\cite{ZaheerKotturRavanbakhshEtAl2017} that this construction is permutation invariant. Further details on the implementation of the network can be found in Appendix \ref{appendix:long-range}. From the structures shown in Fig.~\ref{fig:simplestructure}\footnote{We provide more detailed schematics in Fig.~\ref{fig:localappendix} and Fig.~\ref{fig:nonlocalappendix} in Appendix \ref{appeddix:descriptor}}, it is clear that we can recover the first architecture from the second, by zeroing some entries at the fitting network, and removing the LRC-layer. \begin{figure} \centering \includegraphics[trim = 0mm 0mm 0mm 0mm, clip, width=0.48\linewidth]{localsimple2.jpg} \includegraphics[trim = 0mm 0mm 0mm 0mm, clip, width=0.48\linewidth]{nonlocalsimple2.jpg} \\ \caption{(left) The short-range network architecture. (right) The full-range network architecture. } \label{fig:simplestructure} \end{figure} Finally, let us comment on the inference complexity of the proposed network where, for simplicity we assume that $\mathcal{O}(K_{\texttt{chnls}}) =\mathcal{O}(m_{\texttt{sr}})=\mathcal{O}(m_{\texttt{lr}})=\mathcal{O}(1)$, and that the depth of the neural networks is $\mathcal{O}(1)$. The cost for computing $U^{\texttt{NN}}_{\texttt{sr}}$ is $\mathcal{O}(N)$, provided that each particle has a bounded number of neighbors. The complexity for computing the forces also scales linearly in $N$, albeit with higher constants. The complexity of computing both $U^{\texttt{NN}}$ and associated forces\footnote{See Appendix \ref{appendix:nufft} and \ref{appendix:long-range} for further details.} is $\mathcal{O}(N + N_{\texttt{FFT}} \log N_{\texttt{FFT}})$. \section{Numerical results}\label{section:numerical results} The loss function is the mean squared error of the forces $\frac{1}{N_{\texttt{sample}}} \sum_{\ell=1}^{N_{\texttt{sample}}} \sum_{i=1}^{N} \big \| F^{\texttt{NN}}_{\theta}(x^{[\ell]}_i)-F_i^{[\ell]} \big \|^{2} $, where the $i$-index runs on the points of each snapshot, and $\ell$ runs on the test samples. We also generate $100$ snapshots of data to test the performance of network. This particular loss could lead to shift the potential energy by up to a global constant, which can be subsequently fixed by including the error of the energy in the loss~\cite{zhang2018end}. For the testing stage of we use the relative $\ell^2$ error of the forces as metric, which is defined as $ \epsilon_{\texttt{rel}} := \sqrt{ \sum_{\ell, i} \| F_i^{[\ell]} -F_{\theta}^{\texttt{NN}}(x_i^{[\ell]}) \|^2 / \sum_{\ell, i} \| F_i^{[\ell]} \| ^2}$. The standard training parameters are listed in appendix \ref{appendix:trainstrategy}. The kernels $\psi$ used in the experiment typically exhibit two interaction lengths: $\psi(\cdot) \equiv \alpha_1 \psi^{\mu_1} (\cdot) + \alpha_2 \psi^{\mu_2} (\cdot)$, where each of $\psi^{\mu_1}$ and $\psi^{\mu_2}$ is either a simple exponential kernel or screened-Coulomb kernel (also known as the Yukawa kernel). For each of $\psi^{\mu_1}$ and $\psi^{\mu_2}$, the superscripts denote the reciprocal of the interaction length, i.e., length scale $\sim \mu_1^{-1}$ or $\sim \mu_2^{-1}$. Without loss of generality, $\mu_1 > \mu_2$, so that $\mu_1$ corresponds to the short-range scale and $\mu_2$ the long-range scale. We also assume that $0\le\alpha_2\le \alpha_1$ and $\alpha_1 + \alpha_2=1$, so that the effect of the long-range interaction can be smaller in magnitude compared to that of the short-range interaction. In the special case of $\alpha_2=0$, the kernel exhibits only a single scale $\sim \mu_1^{-1}$. The precise definition of the kernel depends on the spatial dimension and boundary conditions, which are explained in Appendix \ref{appendix:data_generation}. For a fixed set of kernel parameters ($\mu_1,\mu_2,\alpha_1,\alpha_2$), we consider two types of data: large- and small-scale data, generated in the domains $\Omega_{\texttt{lr}}$ and $\Omega_{\texttt{sr}}$ respectively (details to be defined in each experiment). The Fourier multiplier within the LRC-layer is parametrized as \begin{equation} \label{eq:parametrization} \hat{\phi}_{\beta,\lambda}(k) = \frac{4\pi\beta}{|k|^2 + \lambda^2}, \end{equation} where $\beta$ and $\lambda$ are trainable parameters. This is a simple parameterization, and a more complex model can be used as well with minimal changes to the procedure. For all experiments shown below, two kernel channels are used and as a result there are only four trainable parameters in the LRC-layer. The numerical results aim to show namely two properties: i) the LRC-layer is able to efficiently capture LRIs, and ii) the two-scale training strategy can reduce the amount of large-scale data significantly. To demonstrate the first property, we gradually increase the interaction length of the kernel. The accuracy of the short-range network with a fixed interaction radius is supposed to decrease rapidly, while using the LRC-layer improves the accuracy significantly. To show the second property, we generate data with two interaction lengths and train the full-range network using the one- and two-scale strategies. Finally, we also aim to demonstrate that the LRC-layer is competitive against a direct convolution in which the all-to-all computation is performed explicitly. \textbf{1D } In the first set of experiments, the domain $\Omega = [0,5]$, $N=20$ and $N_{\texttt{sample}}= 1000$. For the kernel, we set $\alpha_2$ and vary $\mu_1$ to generate datasets at different interaction lengths. For each dataset we train both short-range and full-range networks using the one-scale data. The results are summarized in Table~\ref{table:1dcompare}, where we can observe that as the characteristic interaction length increases, the accuracy of the short-range network decreases while using the full-range network can restore the accuracy. \begin{table} \caption{Relative testing error for trained screened-Coulomb type $1$D models with $\alpha_1=1, \alpha_2=0$, and varying $\mu_1$. Notice that $\mu_2$ can be arbitrary here.} \label{table:1dcompare} \centering \begin{tabular}{cccccccccccc} \hline $\mu_1$ & 0.5 & 1.0 & 2.0 & 5.0 & 10.0 \\ \hline short-range network & 0.05119 & 0.02919& 0.00597&0.00079 & 0.00032\\ \hline full-range network & 0.00828 &0.00602 & 0.00336&0.00077 &0.00054 \\ \hline \end{tabular} \end{table} For the second set of experiments we used two sets of kernel parameters: one heavily biased towards a localized interaction length, and another in which both interaction lengths are equally weighted. For each set of kernel parameters, we generate $10,000$ small-scale snapshots using $\Omega_{\texttt{sr}} = [0,5]$ and $ N= 20$, and a large number of large-scale snapshots using $\Omega_{\texttt{lr}} = [0,50]$ and $ N= 200$ particles. The interaction radius $R =1.5$, $\delta_{\texttt{min}}=0.05$, and $N_{\texttt{FFT}}$ is $501$. We train the network with the one- and two-scale training strategies described in the prequel. Fig.~\ref{fig:retrain_1D} (left) depicts the advantage of using the two-scale training strategy: we obtain roughly the same accuracy at a fraction of the number of large-scale training samples. We compare the LRC-layer with a direct all-to-all computation We benchmark the wall time of both layers, with increasingly number of particles. To account for implementation effects we normalize the wall times in Fig.~\ref{fig:retrain_1D} (right) and the results corroborate the complexity claims made in Section \ref{sec:nufft}. \begin{figure} \centering \includegraphics[trim = 0mm 0mm 0mm 0mm, clip, width=0.48\linewidth]{1dmerge.png} \includegraphics[trim = 0mm 0mm 0mm 0mm, clip, width=0.48\linewidth]{time.png} \\ \caption{(left) Testing error of the trained 1D model with respect to the number of snapshots using the one- and two-scale training strategies using data generated with the screened-Coulomb potential and parameters $\mu_1=5.0$, $\mu_2=0.5$ (right) normalized wall-time for the LRC and the direct all-to-all computation. } \label{fig:retrain_1D} \end{figure} \textbf{2D } We perform the same experiments as in the one-dimensional case. We fix $\Omega=[0,15]^2$, $N=450$ and $N_{\texttt{sample}}=10000$. The results are summarized in Table~\ref{table:2dcompare}, which shows that as $\mu$ decreases, the full-range network outperforms the short-range one. \begin{table}[h] \caption{Relative testing error for trained screened-Coulomb type $2$D models with $\alpha_1=1, \alpha_2=0$, and varying $\mu_1$. Again $\mu_2$ can be arbitrary.} \label{table:2dcompare} \centering \begin{tabular}{cccccccccccc} \hline $\mu_1$ & 1.0 & 2.0 & 5.0 & 10.0 \\ \hline short-range network &0.07847 &0.02332 & 0.00433& 0.00242\\ \hline full-range network &0.00785 & 0.00526&0.00363 & 0.00181\\ \hline \end{tabular} \end{table} For the second set of experiments, $R = 1.5$, $\delta_{\texttt{min}}=0.05$, and $N_{\texttt{FFT}}$ is $31^2$. For the small-scale data, $\Omega_{\texttt{sr}} =[0, 3]^2$, $N = 18$, and $N_{\texttt{sample}}=10,000$. For the large-scale data, $\Omega_{\texttt{lr}} =[0, 15]^2$ , $N=450$. Similarly to the $1$D case, we train the networks with both strategies using different amounts of large-scale data. The results summarized in Fig.~\ref{fig:retrain_2D} show that the two-scale strategy efficiently captures the long-range interactions with only a small number of the long-range data. \begin{figure} \centering \includegraphics[trim = 0mm 0mm 0mm 0mm, clip, width=0.48\linewidth]{2d09.png} \includegraphics[trim = 0mm 0mm 0mm 0mm, clip, width=0.48\linewidth]{2d05.png} \caption{Testing error of the trained $2$D model with respect to the number of snapshots using the one- and two-scale training strategies using both screened-Coulomb and exponential potentials with $\mu_1=10$, $\mu_2=1$ : (left) $\alpha_1=0.9$, and $\alpha_2 =0.1$; and (right) $\alpha_1=0.5$, and $\alpha_2 =0.5$.} \label{fig:retrain_2D} \end{figure} \textbf{3D } We choose $\Omega=[0,3]^3$ with $27$ cells $2$ points each. The interaction radius $R = 1.0$, $\delta_{\texttt{min}}=0.1$, and $N_{\texttt{sample}} = 1000$. We select a Fourier domain and $N_{\texttt{FFT}} = 25^3$. Table \ref{table:3dmuconstrast} shows full-range network can restore the accuracy when the characteristic interactions length increases. \begin{table} \caption{Relative testing error for trained exponential type $3$D models with $\alpha_1=1, \alpha_2=0$, and varying $\mu_1$. Again $\mu_2$ can be arbitrary.}\label{table:3dmuconstrast} \centering \begin{tabular}{ccccccccc} \hline $\mu_1$ & 5 & 7.5 & 10 \\ \hline short-range network & 0.06249 & 0.01125 & 0.00175\\ \hline full-range network & 0.00971 & 0.00411 & 0.00151\\ \hline \end{tabular} \end{table} \par \section{Conclusion} We have presented an efficient long-range convolutional (LRC) layer, which leverages the non-uniform fast Fourier transform (NUFFT) to reduce the cost from quadratic to nearly-linear with respect to the number of degrees of freedom. We have also introduced a two-scale training strategy to effectively reduce the number of large-scale samples. This can be particularly important when the generation of these large-scale samples dominates the computational cost. While this paper demonstrates the effectiveness of the LRC-layer for computing the energy and force associated with a model $N$-body potential, we expect that the LRC-layer can be a useful tool for a wide range of machine learning (regression / classification) tasks as well. \subsubsection*{Acknowledgments} The work of L.L. is partially supported by the Department of Energy under Grant No. DE-SC0017867 and the CAMERA program, and by the National Science Foundation under Grant No. DMS-1652330. The work of L.Y. is partially supported by the U.S. Department of Energy, Office of Science, Office of Advanced Scientific Computing Research, Scientific Discovery through Advanced Computing (SciDAC) program and also by the National Science Foundation under award DMS1818449. The work of L.Z.-N. is partially supported by the National Science Foundation under the grant DMS-2012292, and by NSF TRIPODS award 1740707.
{'timestamp': '2020-10-13T02:24:06', 'yymm': '2010', 'arxiv_id': '2010.05295', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05295'}
arxiv
\section{Introduction} Recent years have witnessed a growing popularity of various 3D sensors such as LiDAR and Kinect in self-driving cars, robotics and AR/VR applications. As the direct outputs of these sensors, point cloud has drawn increasing attention. Point cloud is a compact and expressive 3D representation, which represents a shape using a set of unordered points and can capture arbitrary complex geometry. However, the irregular data format makes point clouds hard to be directly processed by deep neural networks (DNNs). To address this, PointNet \cite{qi2017pointnet} first uses multi-layer perceptrons (MLPs) to extract point-wise features and aggregate them with max-pooling. Since then, a number of studies \cite{qi2017pointnet++, wang2019dynamic, wu2019pointconv, liu2019relation} have been conducted to design 3D DNNs for point clouds and achieve tremendous progress. One limitation of DNNs is that they are vulnerable to adversarial attacks. By adding imperceptible perturbations to clean data, the generated adversarial examples can mislead victim models with high confidence. While numerous algorithms have been proposed in 2D attack and defense \cite{goodfellow2014explaining, carlini2017towards, xie2017mitigating, papernot2016distillation, moosavi2016deepfool, athalye2018synthesizing, moosavi2017universal}, only a little attention is paid to its 3D counterparts \cite{xiang2019generating, zhou2019dup, zheng2019pointcloud}. They show that point cloud networks such as PointNet \cite{qi2017pointnet} and PointNet++ \cite{qi2017pointnet++} are also sensitive to adversarial examples. Besides, recent works \cite{cao2019adversarial, tu2020physically} have conducted physically realizable point cloud attacks on autonomous driving and robotics tasks in real-world scenarios, posing severe threat to these safety-critical applications. By carefully examining existing 3D adversarial attack methods, we summarize their attack effects into two aspects as shown in Figure \ref{attack_effects}: \begin{enumerate} \renewcommand{\labelenumi}{\theenumi) } \item \emph{Point perturbation} changes the local geometry and point-wise sampling pattern, which moves the points either out of the surface to become noises or along the surface to change point distributions. This effect is similar to 2D adversarial attack, which adds noise over each pixel within a given budget to fool the classifier. \item \emph{Surface distortion} aims to modify the geometry of the point cloud more dramatically by either removing local parts or deforming the shape of the point cloud. In general, surface distortion is difficult to defend due to the significant change of the geometry, yet is also more perceptible by humans. \end{enumerate} \begin{figure*}[t] \centering \vspace{-16pt} \subfigure[Clean Point Cloud]{ \includegraphics[width=0.3\textwidth]{imgs/attack_effects/clean.pdf} } \qua \subfigure[Out-of-surface Perturbation]{ \includegraphics[width=0.3\textwidth]{imgs/attack_effects/outlier.pdf} } \qua \subfigure[On-surface Perturbation]{ \includegraphics[width=0.3\textwidth]{imgs/attack_effects/dist.pdf} } \qua \subfigure[Local Part Removal]{ \includegraphics[width=0.3\textwidth]{imgs/attack_effects/geo-1.pdf} } \qua \subfigure[Geometric Deformation]{ \includegraphics[width=0.3\textwidth]{imgs/attack_effects/geo-2.pdf} } \caption{The key effects of 3D adversarial attacks on point cloud summarized from existing works. We show (a) a clean point cloud, (b)(c) point perturbation, and (d)(e) surface distortion. In each subfigure, we show an entire shape and a local illustration. The blue curve is the object surface, the black points are clean points and the red points are attacked points.} \label{attack_effects} \vspace{-12pt} \end{figure*} While some methods have been proposed in recent years for 3D adversarial defense \cite{zhou2019dup, dong2020self}, they fail to simultaneously address both the two aspects. For example, DUP-Net \cite{zhou2019dup} uses a statistical outlier removal (SOR) pre-processor to address out-of-surface point perturbations, followed by an up-sampling network to generate denser point clouds. However, it cannot well recover the point distribution and restore the distorted surface. Gather-vector guidance (GvG) method \cite{dong2020self} learns to ignore noisy local features, which fails to defend the attacks by local part removal. As a result, these methods fail to protect the victim models from all the attacks, especially the latest ones, such as salient point dropping \cite{zheng2019pointcloud}, LG-GAN \cite{zhou2020lg} and AdvPC \cite{hamdi2020advpc}. In this paper, we propose a 3D adversarial point cloud defense algorithm named IF-Defense by learning to restore the clean point clouds from the attacked ones, which is more universal and simultaneously addresses both the attack effects. Figure \ref{method_pipeline} shows the pipeline of IF-Defense. We first employ SOR to pre-process the input point cloud following the existing work \cite{zhou2019dup}. Then, we directly optimize the coordinates of input points under the geometry-aware and distribution-aware constraints. The geometry-aware loss aims to remove out-of-surface geometric changes, such as Figure \ref{attack_effects}(b)(d)(e). Inspired by the recent success in deep implicit functions which reconstruct accurate surfaces even under partial observations \cite{park2019deepsdf, duan2020curriculum, mescheder2019occupancy, peng2020convolutional, chen2019learning}, we train an implicit function network on clean point clouds to estimate the object surfaces. The predicted surface is locally smooth due to the continuity of the output space of implicit functions \cite{mescheder2019occupancy, park2019deepsdf}, which relieves the effects of outliers. The distribution-aware loss aims to distribute points evenly and eliminate the on-surface point perturbation, as illustrated in Figure \ref{attack_effects}(c). We maximize the distance between each point and its $k$-nearest neighbors to encourage uniform point distribution. Experimental results show that IF-Defense consistently outperforms existing defense methods against various 3D adversarial attacks for PointNet, PointNet++, DGCNN, PointConv and RS-CNN. \section{Related Works} \textbf{Deep learning on point clouds.} The pioneering work PointNet \cite{qi2017pointnet} is the first deep learning algorithm that operates directly on 3D point clouds. After that, PointNet++ \cite{qi2017pointnet++} further improves the performance of PointNet by exploiting local information. Another representative work is Dynamic Graph CNN (DGCNN) \cite{wang2019dynamic}, which constructs $k$NN graphs and applies EdgeConv to capture local geometric structures. In recent years, there are more and more convolution based methods proposed in the literature \cite{wu2019pointconv, thomas2019kpconv, hermosilla2018monte, liu2019relation}, which run convolutions across neighboring points using a predicted kernel weight. Though these point cloud networks have achieved promising results, they are vulnerable to adversarial attacks and require defense methods to improve the robustness. \begin{figure*}[tb] \centering \includegraphics[width=\textwidth]{imgs/method_pipeline.pdf} \caption{The pipeline of our IF-Defense method. We first pre-process the input point cloud by SOR, and then we learn the point coordinates of the restored point cloud via implicit function based optimization guided by two losses. Finally, we send the restored point cloud to the classifier. \textit{Pert.} and \textit{Distort.} indicate Perturbation and Distortion, while \textit{Geo.} and \textit{Dist.} stand for Geometry and Distribution.} \label{method_pipeline} \vspace{-10pt} \end{figure*} \textbf{3D adversarial attack.} Existing 3D adversarial attack methods can be roughly divided into three classes: optimization based methods, gradient based methods and generation based methods. For optimization based methods, \cite{xiang2019generating} first proposed to generate adversarial point clouds using C\&W attack framework \cite{carlini2017towards} by point perturbation and adding. In contrast, \cite{tsai2020robust} proposed to add a $k$NN distance constraint, a clipping and a projection operation to generate adversarial point clouds that are resistant to defense. Besides, \cite{hamdi2020advpc} proposed AdvPC by utilizing a point cloud auto-encoder (AE) to improve the transferability of adversarial examples. Because of the limited budget, these attacks mainly introduce point perturbations. For gradient based methods, \cite{liu2019extending} extended the fast/iterative gradient method to perturb the point coordinates. Additionally, \cite{zheng2019pointcloud} developed a point dropping attack by constructing a gradient based saliency map, which would remove important local parts. LG-GAN \cite{zhou2020lg} is a generation based 3D attack method, which leverages GANs \cite{goodfellow2014generative} to generate adversarial point clouds guided by the input target labels. We summarize the correspondence between existing 3D attacks and the attack effects in Table \ref{attacks_corr_effects}. \begin{table}[tb] \caption{Correspondence between existing 3D attacks and attack effects. Out Pert., On Pert., LPR and GD stand for out-of-surface perturbation, on-surface perturbation, local part removal and geometric deformation, respectively. In the table, $\checkmark$ indicates the main effects of an attack while $\triangle$ shows the less significant ones.} \label{attacks_corr_effects} \centering \vspace{5pt} \renewcommand\arraystretch{1.2} \begin{tabular}{|c|p{1.3cm}<{\centering}|p{1.2cm}<{\centering}|p{1.1cm}<{\centering}|p{1.1cm}<{\centering}|} \hline \textbf{Attacks} & Out Pert. & On Pert. & LPR & GD\\ \hline \textbf{Perturb} & $\checkmark$ & $\triangle$ & & \\ \textbf{Add} & $\checkmark$ & $\triangle$ & & \\ \textbf{$k$NN} & $\triangle$ & $\checkmark$ & & \\ \textbf{AdvPC} & $\triangle$ & $\checkmark$ & & \\ \textbf{Drop} & & $\triangle$ & $\checkmark$ & \\ \textbf{LG-GAN} & $\triangle$ & $\checkmark$ & & $\checkmark$\\ \hline \end{tabular} \vspace{-15pt} \end{table} \textbf{3D adversarial defense.} \cite{liu2019extending} employed adversarial training to improve the robustness of models by training on both clean and adversarial point clouds. \cite{yang2019adversarial} proposed Gaussian noising and point quantization, which are adopted from 2D defense. They also introduced a Simple Random Sampling (SRS) method which samples a subset of points from the input point cloud. Recently, \cite{zhou2019dup} proposed a Statistical Outlier Removal (SOR) method that removes points with a large $k$NN distance. They also proposed DUP-Net, which is a combination of SOR and a point cloud up-sampling network PU-Net \cite{yu2018pu}. The non-differentiability of SOR also improves its robustness. Instead of designing a pre-processing module to recover adversarial examples, \cite{dong2020self} leveraged the intrinsic properties of point clouds and develop a variant of PointNet++ \cite{qi2017pointnet++} that can identify and discard adversarial local parts of an input. Although these defenses are effective against simple attacks \cite{xiang2019generating}, their performance against more complex methods \cite{tsai2020robust, zhou2020lg} is relatively poor, which is because they fail to simultaneously address the aforementioned two attack effects. \textbf{Implicit representation.} Different from the voxel-based, mesh-based and point-based methods that explicitly represent shape surface, implicit functions learn a continuous field and represent surface as the zeroth level-set. More recently, deep learning based methods use DNNs to approximate the occupancy field \cite{mescheder2019occupancy, chen2019learning} or signed distance function \cite{park2019deepsdf, michalkiewicz2019implicit, duan2020curriculum}, which capture more complex geometries. Apart from their strong representation power, previous works show that implicit models encode shape priors in the decoder space, which are able to reconstruct complete shapes from partial observations \cite{park2019deepsdf, duan2020curriculum}. Inspired by this, we propose an implicit function based method to learn to recover clean point clouds from the attacked ones. \begin{figure*}[tb] \centering \vspace{-0.2cm} \subfigure[Input Point Cloud]{ \includegraphics[width=0.17\textwidth]{imgs/remesh_vs_opt/input.pdf} } \hspace{0.4cm} \subfigure[Reconstruction]{ \includegraphics[width=0.19\textwidth]{imgs/remesh_vs_opt/remesh.pdf} } \hspace{0.4cm} \subfigure[Re-sampled Points]{ \includegraphics[width=0.18\textwidth]{imgs/remesh_vs_opt/re_re.pdf} } \hspace{0.4cm} \subfigure[Optimized Points]{ \includegraphics[width=0.18\textwidth]{imgs/remesh_vs_opt/de.pdf} } \caption{Comparison of the re-meshing and optimization based IF-Defense. Given the (a) input point cloud, the (b) reconstructed mesh using Marching Cubes according to the implicit field fails to capture the chair's legs. As a result, the (c) re-sampled point cloud is misclassified as a monitor by PointNet. In contrast, the (d) optimized point cloud successfully retain the legs and is classified correctly.} \label{remesh_vs_deform} \vspace{-10pt} \end{figure*} \section{Approach} In this section, we first introduce an intuitive point cloud restoration method by re-meshing and re-sampling. Then, we propose a learning algorithm to directly optimize the coordinates of input points to further improve the robustness of IF-Defense. Finally, we present the implementation details of our method. \subsection{Re-meshing based IF-Defense} In order to restore the clean point cloud from existing ones, an intuitive idea is to reconstruct meshes from noisy point cloud at first, and then re-sample points on the mesh. Inspired by the recent success of implicit functions, we employ Occupancy Networks (ONet) \cite{mescheder2019occupancy} and Convolutional Occupancy Networks (ConvONet) \cite{peng2020convolutional} for 3D shape reconstruction. The encoder of these networks takes a point cloud as input to obtain a shape latent code, while the decoder outputs the learned implicit fields by querying 3D coordinates. Using the trained implicit function networks, we estimate the implicit surface of the point cloud pre-processed by SOR. As the implicit model is pre-trained on clean data, the output space of the decoder lies on the complete and accurate shape manifold, which is beneficial to eliminate the attack of out-of-surface geometric changes. Given the implicit representation of the recovered surface, the next step is to restore the original clean point cloud which reverses the attack effects. We explicitly reconstruct the shape as a mesh using Marching Cubes \cite{lorensen1987marching} algorithm, and then sample from the mesh using the same point sampling method as in training data to get the restored point cloud. \subsection{Optimization based IF-Defense} The re-meshing based IF-Defense heavily relies on the quality of the reconstructed meshes, where we sample the restored point clouds. However, even for the recent implicit function based methods, it is still very challenging to reconstruct accurate meshes from the noisy point clouds. Previous studies show that some geometries such as slender parts of an object are difficult to be captured by implicit functions \cite{duan2020curriculum}. Also, the noise in the attacked point cloud may lead to imprecise shape latent codes, which further enlarge the reconstruction errors. For example, ONet \cite{mescheder2019occupancy} fails to reconstruct the legs of a chair in Figure \ref{remesh_vs_deform} (b). As a result, the re-sampled point cloud in Figure \ref{remesh_vs_deform} (c) is misclassified by PointNet as a monitor. This fact motivates us to design a learning based point cloud restoration algorithm that directly optimizes the coordinates of the points rather than a two-step process of re-meshing and re-sampling. More specifically, we first initialize the defense point cloud $\hat{X}$ as the input. Since the number of the input points may differ from the clean point clouds, we randomly duplicate or sub-sample points in $\hat{X}$ to maintain the same number of points as the training data. Then, instead of reconstructing meshes from the implicit field, we directly learn the coordinates of clean point clouds based on the predicted implicit surface by optimizing two losses: geometry-aware loss and distribution-aware loss. \begin{table*}[tb] \caption{Classification accuracy of ModelNet40 under various attack and defense methods on PointNet. We report the average Chamfer distance (CD) between clean point clouds and their adversarial counterparts for reference.} \label{pn_all_defense} \centering \vspace{5pt} \renewcommand\arraystretch{1.2} \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|} \hline \textbf{Defenses} & \textbf{Clean} & \textbf{Perturb} & \textbf{Add-CD} & \textbf{Add-HD} & \textbf{$k$NN} & \textbf{Drop-100} & \textbf{Drop-200} & \textbf{LG-GAN} & \textbf{AdvPC}\\ \hline CD ($\times10^{-3}$) & - & $0.87$ & $0.88$ & $1.26$ & $1.42$ & $1.65$ & $4.66$ & $8.65$ & $1.10$\\ \hline No defense & $\pmb{88.41\%}$ & $0.00\%$ & $0.00\%$ & $0.00\%$ & $8.51\%$ & $64.67\%$ & $40.24\%$ & $4.40\%$ & $0.00\%$\\ SRS & $87.44\%$ & $77.47\%$ & $76.34\%$ & $73.66\%$ & $57.41\%$ & $63.57\%$ & $39.51\%$ & $11.72\%$ & $49.01\%$\\ SOR & $87.88\%$ & $82.81\%$ & $82.58\%$ & $82.25\%$ & $76.63\%$ & $64.75\%$ & $42.59\%$ & $34.90\%$ & $75.45\%$\\ SOR-AE & $88.09\%$ & $79.86\%$ & $80.15\%$ & $79.58\%$ & $78.28\%$ & $72.53\%$ & $48.06\%$ & $38.56\%$ & $76.60\%$\\ Adv Training & $88.29\%$ & $25.37\%$ & $19.33\%$ & $15.69\%$ & $19.21\%$ & $70.14\%$ & $49.03\%$ & $4.95\%$ & $12.38\%$\\ DUP-Net & $87.76\%$ & $84.56\%$ & $83.63\%$ & $82.16\%$ & $80.31\%$ & $67.30\%$ & $46.92\%$ & $35.81\%$ & $77.55\%$\\ \hline \textbf{Ours-Mesh$^\dagger$} & $83.95\%$ & $83.31\%$ & $84.76\%$ & $83.79\%$ & $84.28\%$ & $\pmb{77.76\%}$ & $\pmb{66.94\%}$ & $50.00\%$ & $75.62\%$\\ \textbf{Ours-Opt$^\dagger$} & $87.07\%$ & $85.78\%$ & $85.94\%$ & $85.94\%$ & $86.18\%$ & $77.63\%$ & $65.28\%$ & $\pmb{52.10\%}$ & $80.14\%$\\ \textbf{Ours-Opt$^\ddagger$} & $87.64\%$ & $\pmb{86.30\%}$ & $\pmb{86.83\%}$ & $\pmb{86.75\%}$ & $\pmb{86.95\%}$ & $77.39\%$ & $64.63\%$ & $48.11\%$ & $\pmb{80.72\%}$\\ \hline \end{tabular} \vspace{-5pt} \end{table*} \begin{table*}[t] \caption{Classification accuracy of ModelNet40 under various attack and defense methods on PointNet++.} \label{pn2_all_defense} \centering \vspace{5pt} \renewcommand\arraystretch{1.2} \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|} \hline \textbf{Defenses} & \textbf{Clean} & \textbf{Perturb} & \textbf{Add-CD} & \textbf{Add-HD} & \textbf{$k$NN} & \textbf{Drop-100} & \textbf{Drop-200} & \textbf{LG-GAN} & \textbf{AdvPC}\\ \hline CD ($\times10^{-3}$) & - & $1.14$ & $2.78$ & $3.55$ & $1.93$ & $1.19$ & $2.67$ & $6.45$ & $1.54$\\ \hline No defense & $\pmb{89.34\%}$ & $0.00\%$ & $7.24\%$ & $6.59\%$ & $0.00\%$ & $80.19\%$ & $68.96\%$ & $10.12\%$ & $0.56\%$\\ SRS & $83.59\%$ & $73.14\%$ & $65.32\%$ & $43.11\%$ & $49.96\%$ & $64.51\%$ & $39.63\%$ & $7.94\%$ & $48.37\%$\\ SOR & $86.95\%$ & $77.67\%$ & $72.90\%$ & $72.41\%$ & $61.35\%$ & $74.16\%$ & $69.17\%$ & $11.11\%$ & $66.26\%$\\ SOR-AE & $88.45\%$ & $78.73\%$ & $73.38\%$ & $71.19\%$ & $78.73\%$ & $76.66\%$ & $68.23\%$ & $15.19\%$ & $68.29\%$\\ Adv Training & $89.10\%$ & $20.03\%$ & $12.27\%$ & $10.06\%$ & $8.63\%$ & $80.39\%$ & $67.14\%$ & $11.25\%$ & $6.49\%$\\ DUP-Net & $85.78\%$ & $80.63\%$ & $75.81\%$ & $72.45\%$ & $74.88\%$ & $76.38\%$ & $72.00\%$ & $14.76\%$ & $64.76\%$\\ \hline \textbf{Ours-Mesh$^\dagger$} & $83.27\%$ & $81.65\%$ & $77.71\%$ & $79.13\%$ & $72.57\%$ & $82.46\%$ & $72.93\%$ & $18.96\%$ & $65.97\%$\\ \textbf{Ours-Opt$^\dagger$} & $87.64\%$ & $85.21\%$ & $78.44\%$ & $73.87\%$ & $85.37\%$ & $79.38\%$ & $75.12\%$ & $\pmb{21.38\%}$ & $74.63\%$\\ \textbf{Ours-Opt$^\ddagger$} & $89.02\%$ & $\pmb{86.99\%}$ & $\pmb{80.19\%}$ & $\pmb{76.09\%}$ & $\pmb{85.62\%}$ & $\pmb{84.56\%}$ & $\pmb{79.09\%}$ & $17.52\%$ & $\pmb{77.06\%}$\\ \hline \end{tabular} \vspace{-10pt} \end{table*} \textbf{Geometry-aware loss} aims to encourage the optimized points to lie on the shape surface. At each time, we concatenate the shape latent code and the coordinate of a point as input to the implicit function, where the output shows the predicted occupancy probability at that point. Then, we employ the binary cross-entropy loss to force the optimized points to approach the surface as follows: \begin{equation} \mathcal{L}_G = \sum_{i=1}^N \mathcal{L}_{ce}(f_\theta(\bm{z}, \bm{x_i}), \tau), \end{equation} where $\bm{z}$ is the shape latent code extracted from the input point cloud, $\bm{x_i}$ is the point coordinate to be optimized, and $N$ is the number of points. $f_\theta(\bm{z}, \bm{x_i})$ is the implicit function that outputs the occupancy probability at location $\bm{x_i}$. $\tau$ is a hyper-parameter controlling the object boundary, which is used as the ground-truth occupancy probability of surface. For points in $\hat{X}$ that are close to surface, the gradient of geometry-aware loss drives them towards the object boundary. In contrast, for points initialized at the missing parts of the implicit field, the loss provides no gradient since the occupancy probabilities are nearly the same among those regions. Therefore, these points still remain in the missing parts which compensate the errors in the implicit surface. \textbf{Distribution-aware loss} maximizes the distance from a point to its $k$-nearest neighbors ($k$NN), which encourages a more uniform point distribution: \begin{equation} \mathcal{L}_{D} = \sum_{i=1}^N \sum_{\bm{x_j} \in knn(\bm{x_i}, k)} -||\bm{x_i} - \bm{x_j}|| \cdot e^{-||\bm{x_i} - \bm{x_j}||^2 / h^2}, \end{equation} where $knn(\bm{x_i}, k)$ denotes the $k$NN of a point $\bm{x_i}$. The exponential term especially punishes the points that are too close to each other, and $h$ is a hyper-parameter controlling the decay rate with respect to the distance. Similar penalization has also been proposed in the previous point up-sampling work \cite{yu2018pu}, known as the repulsion loss. We optimize the point coordinates $\bm{x_i}$ by minimizing the following objective function with a hyper-parameter $\lambda$ balancing the weights of two terms: \begin{equation} \label{optimize} \mathcal{L}(\hat{X}) = \mathcal{L}_G + \lambda \mathcal{L}_{D}. \end{equation} \subsection{Implementation Details} We implemented the implicit function network with the widely-used ONet \cite{mescheder2019occupancy} and ConvONet \cite{peng2020convolutional} in IF-Defense, which are trained on multiple categories without class labels. We first pre-trained them on the ShapeNet dataset \cite{chang2015shapenet} and then finetuned them on the ModelNet40 dataset \cite{wu20153d}. For the optimization based IF-Defense, we used $\tau=0.2$ as suggested by \cite{mescheder2019occupancy}. Parameters $h$ and $k$ were set to be $0.03$ and $5$ following \cite{yu2018pu}, and $\lambda$ was set as $500$. We optimized the coordinates of points for 200 iterations using the Adam \cite{kingma2014adam} optimizer with a learning rate equals to $0.01$. \begin{table*}[tb] \vspace{-2pt} \caption{Classification accuracy of ModelNet40 under various attack and defense methods on DGCNN.} \label{dgcnn_all_defense} \centering \vspace{5pt} \renewcommand\arraystretch{1.2} \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|} \hline \textbf{Defenses} & \textbf{Clean} & \textbf{Perturb} & \textbf{Add-CD} & \textbf{Add-HD} & \textbf{$k$NN} & \textbf{Drop-100} & \textbf{Drop-200} & \textbf{LG-GAN} & \textbf{AdvPC}\\ \hline CD ($\times10^{-3}$) & - & $2.50$ & $3.77$ & $6.97$ & $3.03$ & $1.42$ & $4.36$ & $9.61$ & $2.48$\\ \hline No defense & $\pmb{91.49\%}$ & $0.00\%$ & $1.46\%$ & $1.42\%$ & $20.02\%$ & $75.16\%$ & $55.06\%$ & $15.41\%$ & $9.23\%$\\ SRS & $81.32\%$ & $50.20\%$ & $63.82\%$ & $43.35\%$ & $41.25\%$ & $49.23\%$ & $23.82\%$ & $20.07\%$ & $41.62\%$\\ SOR & $88.61\%$ & $76.50\%$ & $72.53\%$ & $63.74\%$ & $55.92\%$ & $64.68\%$ & $59.36\%$ & $30.82\%$ & $56.49\%$\\ SOR-AE & $89.20\%$ & $79.05\%$ & $76.38\%$ & $66.25\%$ & $56.78\%$ & $66.78\%$ & $63.70\%$ & $32.96\%$ & $58.67\%$\\ Adv Training & $90.22\%$ & $11.87\%$ & $6.59\%$ & $6.33\%$ & $15.96\%$ & $75.45\%$ & $55.43\%$ & $15.21\%$ & $18.37\%$\\ DUP-Net & $53.54\%$ & $42.67\%$ & $44.94\%$ & $33.02\%$ & $35.45\%$ & $44.45\%$ & $36.02\%$ & $21.38\%$ & $29.38\%$\\ \hline \textbf{Ours-Mesh$^\dagger$} & $83.91\%$ & $81.56\%$ & $81.73\%$ & $67.50\%$ & $79.38\%$ & $78.97\%$ & $70.34\%$ & $46.09\%$ & $65.54\%$\\ \textbf{Ours-Opt$^\dagger$} & $88.25\%$ & $82.25\%$ & $81.77\%$ & $67.75\%$ & $82.29\%$ & $79.25\%$ & $\pmb{73.30\%}$ & $\pmb{53.08\%}$ & $76.01\%$\\ \textbf{Ours-Opt$^\ddagger$} & $89.22\%$ & $\pmb{85.53\%}$ & $\pmb{84.20\%}$ & $\pmb{72.93\%}$ & $\pmb{82.33\%}$ & $\pmb{83.43\%}$ & $73.22\%$ & $50.70\%$ & $\pmb{79.14\%}$\\ \hline \end{tabular} \vspace{-5pt} \end{table*} \begin{table*}[t] \caption{Classification accuracy of ModelNet40 under various attack and defense methods on PointConv.} \label{pc_all_defense} \centering \vspace{5pt} \renewcommand\arraystretch{1.2} \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|} \hline \textbf{Defenses} & \textbf{Clean} & \textbf{Perturb} & \textbf{Add-CD} & \textbf{Add-HD} & \textbf{$k$NN} & \textbf{Drop-100} & \textbf{Drop-200} & \textbf{LG-GAN} & \textbf{AdvPC}\\ \hline CD ($\times10^{-3}$) & - & $1.14$ & $1.22$ & $1.97$ & $2.27$ & $1.46$ & $4.31$ & $9.66$ & $4.43$\\ \hline No defense & $\pmb{88.49\%}$ & $0.00\%$ & $0.54\%$ & $0.68\%$ & $3.12\%$ & $77.96\%$ & $64.02\%$ & $4.42\%$ & $6.45\%$\\ SRS & $85.23\%$ & $76.22\%$ & $71.31\%$ & $61.98\%$ & $55.75\%$ & $69.45\%$ & $48.87\%$ & $5.10\%$ & $37.62\%$\\ SOR & $87.28\%$ & $79.25\%$ & $82.41\%$ & $72.73\%$ & $26.13\%$ & $77.63\%$ & $63.78\%$ & $5.48\%$ & $51.75\%$\\ SOR-AE & $87.40\%$ & $78.08\%$ & $77.27\%$ & $74.55\%$ & $56.50\%$ & $72.45\%$ & $60.37\%$ & $8.64\%$ & $50.96\%$\\ Adv Training & $88.90\%$ & $16.57\%$ & $8.32\%$ & $4.84\%$ & $15.64\%$ & $81.00\%$ & $72.33\%$ & $5.25\%$ & $16.20\%$\\ DUP-Net & $78.73\%$ & $68.84\%$ & $72.61\%$ & $61.14\%$ & $43.76\%$ & $70.75\%$ & $58.23\%$ & $5.02\%$ & $49.35\%$\\ \hline \textbf{Ours-Mesh$^\dagger$} & $82.78\%$ & $81.73\%$ & $81.85\%$ & $75.61\%$ & $77.15\%$ & $75.97\%$ & $68.44\%$ & $15.46\%$ & $53.81\%$\\ \textbf{Ours-Opt$^\dagger$} & $86.10\%$ & $83.55\%$ & $83.95\%$ & $76.86\%$ & $80.47\%$ & $78.85\%$ & $70.34\%$ & $\pmb{18.78\%}$ & $\pmb{61.77\%}$\\ \textbf{Ours-Opt$^\ddagger$} & $88.21\%$ & $\pmb{86.67\%}$ & $\pmb{85.62\%}$ & $\pmb{82.13\%}$ & $\pmb{81.08\%}$ & $\pmb{81.20\%}$ & $\pmb{74.51\%}$ & $16.55\%$ & $59.82\%$\\ \hline \end{tabular} \vspace{-10pt} \end{table*} \section{Experiments} We conducted all the experiments on the commonly used ModelNet40 shape classification benchmark \cite{wu20153d} which contains 12,311 CAD models from 40 man-made object classes. We used the official split with 9,843 shapes for training and 2,468 for testing. Following \cite{qi2017pointnet}, we uniformly sampled $1024$ points from the surface of each object and normalize them into a unit sphere. We applied PointNet \cite{qi2017pointnet}, PointNet++ \cite{qi2017pointnet++}, DGCNN \cite{wang2019dynamic}, PointConv \cite{wu2019pointconv} and RS-CNN \cite{liu2019relation} as the victim models, with the single scale grouping (SSG) strategy for PointNet++ and PointConv. For the attack methods, we employed the point perturbation and individual point adding attack \cite{xiang2019generating}, $k$NN attack \cite{tsai2020robust}, point dropping attack \cite{zheng2019pointcloud} as well as two recently proposed attacks LG-GAN \cite{zhou2020lg} and AdvPC \cite{hamdi2020advpc}. For the defense baselines, we employed SRS \cite{yang2019adversarial}, SOR \cite{zhou2019dup}, DUP-Net \cite{zhou2019dup} and adversarial training. For adversarial training, all victim models are trained on both clean data and adversarial examples generated by point perturbation. We also trained a point cloud AE \cite{achlioptas2018learning} with a SOR pre-processor as a baseline defense called SOR-AE. We include more details about the implementation of baseline methods in the appendix. Following previous works, we tested on targeted attack and reported the classification accuracy after defense, where higher accuracy indicates better defense. \begin{figure*}[tb] \centering \vspace{-0.2cm} \includegraphics[width=0.9\textwidth]{imgs/ablation/pert_convonet.pdf} \caption{Ablation study of $\lambda$. We show the defense accuracy of four victim models against point perturbation attack, where all four best results are achieved at $\lambda=500$. The defense module evaluated here is the optimization based IF-Defense with ConvONet.} \label{ablation_conv_paper} \vspace{-6pt} \end{figure*} \begin{table*}[tb] \caption{Classification accuracy of ModelNet40 under black-box attacks and defenses.} \label{transfer} \centering \vspace{5pt} \renewcommand\arraystretch{1.2} \begin{tabular}{|c|c|c|c|c|c|c|} \hline \textbf{Network} & \textbf{Defense} & \textbf{Add-CD} & \textbf{$k$NN} & \textbf{Drop-200} & \textbf{LG-GAN} & \textbf{AdvPC}\\ \hline \textbf{PointNet} & No defense & $0.00\%$ & $8.51\%$ & $40.24\%$ & $4.40\%$ & $0.00\%$\\ \hline \multirow{4}{*}{\textbf{PointNet++}} & No defense & $87.60\%$ & $80.47\%$ & $79.90\%$ & $24.18\%$ & $70.07\%$\\ & SOR & $87.13\%$ & $85.07\%$ & $74.84\%$ & $48.78\%$ & $74.09\%$\\ & DUP-Net & $87.12\%$ & $84.04\%$ & $73.06\%$ & $50.90\%$ & $72.94\%$\\ & \textbf{Ours-Opt$^\ddagger$} & $\pmb{88.17\%}$ & $\pmb{85.98\%}$ & $\pmb{79.98\%}$ & $\pmb{54.85\%}$ & $\pmb{80.59\%}$\\ \hline \multirow{4}{*}{\textbf{DGCNN}} & No defense & $78.24\%$ & $80.19\%$ & $73.14\%$ & $35.12\%$ & $74.51\%$\\ & SOR & $85.58\%$ & $87.16\%$ & $66.57\%$ & $40.23\%$ & $78.49\%$\\ & DUP-Net & $53.20\%$ & $49.47\%$ & $35.01\%$ & $20.35\%$ & $38.77\%$\\ & \textbf{Ours-Opt$^\ddagger$} & $\pmb{88.09\%}$ & $\pmb{88.01\%}$ & $\pmb{76.90\%}$ & $\pmb{62.13\%}$ & $\pmb{85.61\%}$\\ \hline \multirow{4}{*}{\textbf{PointConv}} & No defense & $84.81\%$ & $77.11\%$ & $76.26\%$ & $22.41\%$ & $64.19\%$\\ & SOR & $84.57\%$ & $82.43\%$ & $72.41\%$ & $47.52\%$ & $70.89\%$\\ & DUP-Net & $79.74\%$ & $75.20\%$ & $57.37\%$ & $32.15\%$ & $66.78\%$\\ & \textbf{Ours-Opt$^\ddagger$} & $\pmb{87.76\%}$ & $\pmb{86.55\%}$ & $\pmb{77.19\%}$ & $\pmb{56.25\%}$ & $\pmb{76.69\%}$\\ \hline \end{tabular} \vspace{-10pt} \end{table*} \subsection{Comparison with the State-of-the-art Methods} Table \ref{pn_all_defense} and Table \ref{pn2_all_defense} illustrate the classification accuracy under various attack and defense methods on PointNet and PointNet++. In the Tables, Ours-Mesh and Ours-Opt represent the re-meshing and optimization based IF-Defense, respectively. We use $\dagger$ and $\ddagger$ to show the results of two implicit function networks ONet and ConvONet. We observe that the optimization based method consistently outperforms the re-meshing based method, showing the effectiveness of our learning based point cloud restoration algorithm. Also, employing ConvONet usually leads to better or comparable accuracy compared with ONet because of the stronger representation capacity of ConvONet. Besides, although a point cloud AE can also project the distorted input data to the natural shape manifold \cite{hamdi2020advpc}, it fails to reconstruct point clouds with desired point distribution, and thus performs worse than IF-Defense. In addition, though adversarial training improves the robustness against point perturbation, other attack effects can still easily break it\footnote{Note that adversarial training is a white-box defense, while other methods are gray-box because attacker is unaware of the defense module.}. Overall, IF-Defense achieves relatively small improvements against point perturbation and adding attack compared with existing methods, because these attacks mainly result in out-of-surface perturbation and can be alleviated by SOR. However, our method boosts the performance significantly for $k$NN, point dropping, LG-GAN and AdvPC attack since they mainly introduce on-surface perturbation or significant surface distortion, while IF-Defense can recover natural shape surface via implicit function network and learn to restore point clouds with desired distribution. As shown in Table \ref{dgcnn_all_defense} and Table \ref{pc_all_defense}, we draw similar observations for DGCNN and PointConv. The optimization based IF-Defense still outperforms its re-meshing based counterpart, and ConvONet demonstrates competitive or superior performance compared with ONet. It is worth noticing that DUP-Net performs poorly on these two models. This is because DGCNN and PointConv are sensitive to local point distributions as they propagate features through $k$NN graphs. However, DUP-Net up-samples points to a much higher density, which largely affects the learned local graphs due to the difference in point distributions. Instead, the proposed IF-Defense learns uniform point distribution, which leads to better $k$NN graphs. Therefore, we achieve significantly better results than DUP-Net against all the attacks on DGCNN and PointConv. Due to the limited space, we leave the defense results on RS-CNN to the appendix, where we have a similar observation. \subsection{Ablation Study} \textbf{Distribution-aware loss weight.} In this part, we study the effect of the hyper-parameter $\lambda$ of the optimization based IF-Defense (Ours-Opt), where ConvONet is adopted as it achieves the best performance against most of the attacks. We varied $\lambda$ between $0$ and $1,000$ and recorded the accuracy of the victim models after defense. As shown in Figure \ref{ablation_conv_paper}, with the increase of $\lambda$, the accuracy first improves and then begins to decrease. In most cases, we observe that the best accuracy is achieved at $\lambda=500$. The distribution-aware loss enforces the points to distribute uniformly over the surface. The points are not able to cover the entire object uniformly with a small $\lambda$, while a large $\lambda$ fails to capture the surface precisely due to the ignorance of the geometry-aware loss. To this end, we select a proper $\lambda$ to balance the importance between accurate surfaces and uniform point distributions. More ablation studies on $\lambda$ using ONet or against other attacks are provided in the appendix. \begin{table}[tb] \footnotesize \caption{Classification accuracy of ModelNet40 under adaptive attack against IF-Defense.} \label{adaptive_attack} \centering \vspace{5pt} \renewcommand\arraystretch{1.2} \begin{tabular}{|c|c|c|c|c|} \hline \textbf{Defenses} & \textbf{PointNet} & \textbf{PointNet++} & \textbf{DGCNN} & \textbf{PointConv}\\ \hline \textbf{Ours-Mesh$^\dagger$} & $56.60\%$ & $52.71\%$ & $55.67\%$ & $52.27\%$\\ \textbf{Ours-Opt$^\dagger$} & $60.53\%$ & $56.20\%$ & $58.67\%$ & $55.67\%$\\ \textbf{Ours-Opt$^\ddagger$} & $\pmb{65.90\%}$ & $\pmb{63.80\%}$ & $\pmb{61.81\%}$ & $\pmb{60.07\%}$\\ \hline \end{tabular} \vspace{-15pt} \end{table} \begin{figure*}[t] \centering \vspace{-10pt} \includegraphics[width=0.98\textwidth]{imgs/main_paper_vis_defense.pdf} \caption{Visualization of different defense results. The labels under each point cloud are the prediction outputs of the victim models.} \label{vis_defense_main} \vspace{-10pt} \end{figure*} \textbf{Adaptive attack.} As pointed out by \cite{carlini2019evaluating}, it is not sufficient to evaluate a proposed defense only against existing attacks. Therefore, we designed an adaptive attack targeting on IF-Defense to study its worst-case bound. Since the SOR pre-processor and the optimization process are non-differentiable, we cannot perform gradient ascent using the cross-entropy loss over the output of the classifier. Instead, we utilize two loss terms to distort the implicit field predicted by the implicit function network. More details about our design are provided in the appendix. Table \ref{adaptive_attack} summarizes the defense results against the adaptive attack. We controlled the Chamfer distance between clean and adversarial point clouds to be around $2.00$. Comparing to existing attacks, the adaptive attack causes greater performance drop. Nonetheless, Ours-Opt with ConvONet still achieves classification accuracy higher than $60\%$ on all the four victim models. Though the adaptive attack perturbs the shape latent code extracted by the encoder of the implicit function network, the decoder can still project it back to a clean shape, mitigating the distortion. \subsection{Black-Box Attacks and Defenses} We explore the transferability of attacks and the performance of various defense methods in this black-box setting. Following previous works \cite{zhou2019dup, zhou2020lg}, we first generated adversarial examples against PointNet, and then transferred them to the other three victim models. We adopted the optimization based IF-Defense with ConvONet for comparison. The results are summarized in Table \ref{transfer}. As the attacked point clouds are generated against PointNet, they are less effective for other network architectures due to the limited transferability. We observe that our method consistently outperforms other defense methods. For SOR and DUP-Net, the classification accuracy even drops in some situations compared with directly using the attacked point clouds. Instead, our IF-Defense continuously boosts the performance, which demonstrates its effectiveness and robustness. \subsection{Qualitative Results} Figure \ref{vis_defense_main} illustrates two groups of defense results using SOR, DUP-Net and all three variants of IF-Defense. The first row shows the results under point dropping attack on PointNet, where the head of the airplane is discarded in the adversarial example. SOR fails to defend this adversary because it just removes more points from the point cloud. Although DUP-Net further up-samples the point cloud with PU-Net, the up-sampled points are all near the input points so that the missing part cannot be recovered. Instead, all three IF-Defense methods successfully restore the shape by extending the front end trying to form a head, which demonstrates its effectiveness in reconstructing the whole shapes under partial observations. The second row is the $k$NN attack on PointConv. Most of the points are perturbed along the surface because of the $k$NN constraint, resulting in significant changes in point distribution. DUP-Net fails to recover the original point distribution as it outputs a much denser point cloud. Ours-Mesh re-samples points from the reconstructed mesh using the same sampling strategy as clean data, and Ours-Opt outputs uniformly distributed points because of the distribution-aware loss. Consequently, PointConv correctly classifies the airplane in both cases. \section{Conclusion} In this paper, we have proposed a general framework called IF-Defense for adversarial defense in 3D point cloud, which simultaneously addresses point perturbation and surface distortion effects. Our IF-Defense learns to restore the clean point clouds by optimizing the coordinates of the attacked points according to geometry-aware and distribution-aware losses, so that the distortion on surfaces is recovered through implicit function and the perturbation on point distributions is eliminated via optimization. Extensive experiments show that IF-Defense consistently outperforms existing adversarial defense methods against various 3D point cloud adversarial attacks on PointNet, PointNet++, DGCNN, PointConv and RS-CNN. \section*{Acknowledgements} This research was supported by a Vannevar Bush Faculty Fellowship, a grant from the Stanford-Ford Alliance, NSF grant IIS-1763268, and gifts from Adobe, Amazon AWS, and Snap, Inc. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2021-03-19T01:22:40', 'yymm': '2010', 'arxiv_id': '2010.05272', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05272'}
arxiv
\section{Introduction} Audio and visual messages are pervasive in our daily-life. Their natural correspondence provides humans with rich semantic information to achieve effective multi-modal perception and learning~\cite{stein1993merging,proulx2014multisensory,Hu2020CrossTaskTF}, e.g., when in the street, we instinctively associate the talking sound with people nearby, and the roaring sound with vehicles passing by. In view of this, we want to question that can they also facilitate machine intelligence? To pursue the human-like audiovisual perception, the typical and challenging problem of visually sound localization is highly expected to be addressed, which aims to associate sounds with specific visual regions and rewards the visual perception ability in the absence of semantic annotations~\cite{soundloc99,izadinia2012multimodal,arandjelovic2017objects,senocak2018learning,vehicle}. A straightforward strategy is to encourage the visual features of sound source to take higher similarity with the sound embeddings, which has shown considerable performance in the simple scenarios with single sound~\cite{oquab2015object,avscene,senocak2018learning}. However, there are simultaneously multiple sounding objects as well as silent ones (i.e. The silent objects are considered capable of producing sound.). in our daily scenario, i.e., the cocktail-party, this simple strategy mostly fails to discriminatively localize different sound sources from mixed sound~\cite{hu2019deep}. Recently, audiovisual content modeling is proposed to excavate concrete audio and visual components in the scenario for localization. Yet, due to lack of sufficient semantic annotation, existing works have to resort to extra scene prior knowledge~\cite{hu2019deep,curriculum,qian2020multiple} or construct pretext task~\cite{zhao2018sop,som}. Even so, these methods cannot well deal with such complex cocktail-party scenario, i.e., not only answering \emph{where the sounding area is} but also answering \emph{what the sounding area is}. In this paper, we target to perform class-aware sounding object localization from their mixed sound, where the audiovisual scenario consists of multiple sounding objects and silent objects, as shown in Fig.~\ref{fig:teaser}. This interesting problem is quite challenging from two perspectives: \begin{wrapfigure}{r}{0.5\linewidth} \includegraphics[width=\linewidth]{teaser.jpg} \vspace{-3mm} \caption{An example of cocktail-party scenario, which contains sounding guitar, sounding cello and silent saxophone. We aim to discriminatively localize the sounding instruments and filter out the silent ones. Video: \url{https://www.youtube.com/watch?v=ebugBtNiDMI}.}\vspace{-3mm}\label{fig:teaser} \end{wrapfigure} 1) Discriminatively localizing objects belonging to different categories without resorting to semantic annotations of objects; 2) Determining whether a specific object is sounding or not, and filtering out silent ones from the corresponding mixed sound. When faced with these challenges, we want to know how do we human address them? Elman~\cite{elman1993learning} stated that human could transform these seemingly unlearnable tasks into learnable by starting from a simpler initial state then building on which to develop more complicated representations of structure. Inspired by this, we propose a two-stage framework, evolving from single sound scenario to the cocktail-party case. Concretely, we first learn potential object knowledge from sound localization in single source scenario, and aggregate them into a dictionary for pursuing robust representation for each object category. By referring to the dictionary, class-aware object localization maps are accordingly proposed for meeting the sounding object selection in multi-source scenario. Then, we reduce the sounding object localization task into a self-supervised audiovisual matching problem, where the sounding objects are selected by minimizing the category-level audio and visual distribution difference. With these evolved curriculums, we can filter out silent objects and achieve class-aware sounding object localization in a cocktail-party scenario. To summarize, our main contributions are as follows. \textbf{First}, we introduce an interesting and challenging problem, i.e., discriminatively localizing sounding objects in the cocktail-party scenario without manual annotation for objects. \textbf{Second}, we propose a novel step-by-step learning framework, which learns robust object representations from single source localization then further expands to the sounding object localization via taking audiovisual consistency as self-supervision for category distribution matching in the cocktail-party scenario. \textbf{Third}, we synthesize some cocktail-party videos and annotate sounding object bounding boxes for the evaluation of class-aware sounding object localization. Our method shows excellent performance on both synthetic and realistic data. \vspace{-3mm} \section{Related work} \vspace{-3mm} \textbf{Object localization} Weakly- and self-supervised object localization expect to achieve comparable performance to the supervised ones with limited annotations. Existing weakly-supervised methods take holistic image labels as supervision, where the salient image region evaluated by recognition scores are considered as the potential object location\cite{oquab2014learning,oquab2015object,bazzani2016self,zhou2016learning,grad-cam,grad-cam++}. For self-supervised models, Baek et al.~\cite{psynet} used point symmetric transformation as self-supervision to extract class-agnostic heat maps for object localization. These methods are purely based on visual features, while we propose to employ audiovisual consistency as self-supervision to achieve class-aware object localization. \textbf{Self-supervised audiovisual learning} The natural correspondence between sound and vision provides essential supervision for audiovisual learning~\cite{L3,arandjelovic2017objects,avscene,soundnet,soundsupv}. In~\cite{soundsupv,soundnet}, authors introduced to learn feature representations of one modality with the supervision from the other. In~\cite{L3,avscene}, authors adopted clip-level audiovisual correspondence and temporal synchronization as self-supervision to correlate audiovisual content. Hu et al.~\cite{hu2019deep,curriculum} associate latent sound-object pairs with clustered audiovisual components, but its performance greatly relies on predefined number of clusters. Alwassel et al.~\cite{alwassel2019self} created pseudo labels from clustering features to boost multi-modal representation learning. While in our work, we alternatively use audiovisual correspondence and pseudo labels from clustering to boost audiovisual learning and learn object representations. \textbf{Sounding object localization in visual scenes} Recent methods for localizing sound source in visual context mainly focus on joint modeling of audio and visual modalities~\cite{arandjelovic2017objects,avscene,senocak2018learning,ave,hu2019deep,som,zhao2018sop}. In~\cite{arandjelovic2017objects,avscene}, authors adopted \emph{Class Activation Map} (CAM)~\cite{zhou2016learning} or similar methods to measure the correspondence score between audio and visual features on each spatial grid to localize sounding objects. Senocak et al.~\cite{senocak2018learning} proposed an attention mechanism to capture primary areas in a semi-supervised or unsupervised setting. Tian et al.~\cite{ave} leveraged audio-guided visual attention and temporal alignment to find semantic regions corresponding to sound sources. These methods tend to perform well in single source scenes, but comparatively poor for mixed sound localization. Zhao et al.~\cite{zhao2018sop,som} employed a sound-based mix-then-separate framework to associate the audio and visual feature maps, where the sound source position is given by the sound energy of each pixel. Hu et al.~\cite{hu2019deep} established audiovisual clustering to associate sound centers with corresponding visual sources, but it requires the prior of the number of sound sources, and the specific category of the clustering result remains unknown. In contrast, our method can discriminatively localize sounding objects in cocktail-party by employing established object dictionary to generate class-aware object localization maps, and referring to the audiovisual localization map to filter out the silent ones. \vspace{-3mm} \section{The proposed method} \vspace{-3mm} In this work, we aim to discriminatively localize the sounding objects from their mixed sound without the manual annotations of object category. To facilitate this novel and challenging problem, we develop a two-stage learning strategy, evolving from the localization in simple scenario with single sounding object to the complex one with multiple sounding objects, i.e., cocktail-party. Such curriculum learning perspective is based on the findings that existing audiovisual models~\cite{arandjelovic2017objects,hu2019deep,senocak2018learning} are capable of predicting reasonable localization map of sounding object in simple scenario, which is considered to provide effective knowledge reference for candidate visual localization of different objects in the cocktail-party scenario. Specifically, for a given set of audiovisual pair with arbitrary number of sounding objects, $\mathcal{X}=\left\{(a_i,v_i)|i=1,2,...,N\right\}$, we first divide it into one simple set whose scenario only contains single sounding object, $\mathcal{X}^s=\left\{(a_i^s,v_i^s)\right|i=1,2,...,N^s\}$, and one complex set, where each audiovisual pair consists of several sounding objects, $\mathcal{X}^c=\left\{(a_i^c,v_i^c)\right|i=1,2,...,N^c\}$, where $\mathcal{X}=\mathcal{X}^s \cup \mathcal{X}^c$ and $\mathcal{X}^s \cap \mathcal{X}^c=\emptyset$. In the first stage, we propose to learn potential visual representation of sounding object from their localization map in the simple scenario $\mathcal{X}^s$, with which we build a representation dictionary of objects as a kind of visual object knowledge reference. In the second stage, by referring to the learned representation dictionary, we step forward to discriminatively localize multiple sounding objects in the complex scenario $\mathcal{X}^c$, where the category distribution of localized sounding objects are required to match the distribution of their mixed sound according to the natural audiovisual consistency~\cite{hu2019deep}. In the rest sections, we detail the first and second learning stage for generalized sounding object localization. \begin{figure}[t] \centering \includegraphics[width=1\linewidth]{framework.jpg} \vspace{-6mm} \caption{An overview of the proposed framework. First, we use audiovisual correspondence as the self-supervision to localize sounding area and learn object representation (left). Then, we employ built object dictionary to generate class-aware localization maps and refer to inferred sounding area to eliminate silent objects. In that way, we reduce the localization task into a distribution matching problem, where we use KL divergence to minimize audiovisual distribution difference (right).} \label{fig:framework} \vspace{-3mm} \end{figure} \vspace{-2mm} \subsection{Learning object representation from localization} \vspace{-2mm} For the simple audiovisual scenario with single sound source, $\mathcal{X}^s$, we target to visually localize the sounding object from its corresponding sound, and synchronously build a representation dictionary from the localization outcomes. The framework is shown in the left part of Fig.~\ref{fig:framework}. At the first step, given an arbitrary audiovisual pair $(a_i^s, v_i^s ) \in \mathcal{X}^s$, to exactly predict the position of sounding object, we need to find which region of input image $v_i^s$ is highly correlated to the sound $a_i^s$. To this end, we feed the image into a convolution-based network (e.g., ResNet~\cite{resnet}) to extract spatial feature maps $f(v_i^s) \in R^{C \times H \times W}$ as the local image region descriptors, where $C$ is the channel dimension, $H$ and $W$ are the spatial size. Then, the localization network is encouraged to enhance the similarity between the image region of sounding object and corresponding sound embeddings $g(a_i^s)$ from the same video, but suppress those ones where sound and object are mismatched (from different videos), i.e., $(a_i^s, v_j^s)$, where $ i\ne j$. Formally, the localization objective can be written as \begin{equation} \label{eq:simple_local} \mathcal{L}_1=\mathcal{L}_{bce}(y^{match}, {GMP}(l(g(a_i^s),f(v_j^s)))), \end{equation} where the indicator $y^{match}=1$ is the audio and image are from the same pair, i.e., $i=j$, otherwise $y^{match}=0$, and $\mathcal{L}_{bce}$ is the binary cross-entropy loss. $l(g(a_i^s),f(v_j^s))$ is the audiovisual localization function, achieved by computing the cosine similarity of audio and visual feature representation\footnote{The cosine similarity is followed by a parameterized sigmoid function to achieve comparable scale to the binary supervision. More details about similarity computation and networks are in the appendix.}. Similar to~\cite{arandjelovic2017objects}, \emph{Global Max Pooling} (GMP) is used to aggregate the localization map to match the scene-level supervision. As there is no extra semantic annotation employed, the localization model is fully optimized in a self-supervised fashion. As the localization map could provide effective reference of object position, it helps to reduce the disturbance of complex background and boosts the visual perception performance of object appearance. To supply better visual object reference for the multi-source localization in the second stage, we utilize these localization outcomes to learn a kind of representation dictionary $D$ for different object categories. First, we propose to binarize the localization map $l_i$ of the $i-$th audiovisual pair into a mask $m_i \in \left\{0,1\right\}^{H \times W}$. As there should be only one sounding object in the simple scenario $\mathcal{X}^s$, $m_i$ should be a single-object-awareness mask indicator. Hence, we can extract potential object representation $o_i \in R^C$ over the masked visual features $f(v_i^s)$, i.e., \begin{equation} \label{eq:stage1_obj} o_i = {GAP}(f(v_i^s) \circ m_i), \end{equation} where $GAP$ is the Global Average Pooling operation and $\circ$ is the Hadamard product. These object representations $\mathcal{O} = \left\{o_1, o_2,...,o_{N^s}\right\}$ are extracted from the coarse localization results, which makes it difficult to provide robust expression of object characters. To facilitate such progress, we target to learn high-quality object indicators with these candidate representations in a dictionary learning fashion. Specifically, we propose to jointly learn a $K \times C$ dictionary $D$ and assignment $y_i$ of each object representation $o_i$, where each key $d^k \in R^{1 \times C}$ is identified as the representative object character in the $k-$th category. As K-means can be viewed as an efficient way of constructing representation dictionary~\cite{coates2012learning}, in our case we aim to minimize the following problem, \begin{equation} \label{eq:stage1_cluster} \mathcal{L}(D, y_i) = \sum_{i=1}^{N^s} \mathop{min}\limits_{y_i} ||o_i - D^{T} \cdot y_i||_2^2 {\rm{~~~~}}s.t. {\rm{~~}} y_i \in \left\{0,1 \right\}^K, \sum y_i = 1, \end{equation} where $K$ is the number of object category. Solving this problem provides a dictionary $D^*$ and a set of category assignments $\left\{ y_i^*|i= 1,2,...N^s \right\}$, where the former one is used for potential object detection in the second stage and the latter can be viewed as pseudo labels indicating different object categories. Recall that object localization could benefit from generalized categorization~\cite{oquab2015object,zhou2016learning}, we therefore choose to alternately optimize the model w.r.t. the localization objective using Eq.~\ref{eq:simple_local} and the object classification objective with generated pseudo labels, which could substantially improve the localization performance. \subsection{Discriminative sounding object localization} To discriminatively localize different sounding objects from their mixed sound, we propose to localize all the emerged objects in the image first, among which the sounding ones are causally selected based on whether they appear in the sounding area and required to match the category distribution of corresponding audio messages, as shown in the right part of Fig.~\ref{fig:framework}. Let $(a_i^c, v_i^c) \in \mathcal{X}^c$ denote the $i-$th audiovisual message that consists of multiple sounding objects. By referring to the learned representation dictionary of objects $D^*$, the location of emerged objects is indicated by computing the following inner-product similarity between each location of visual feature map $f(v_i^c) \in R^{C \times H \times W}$ and each representation key $d^k \in R^{1 \times C}$ within $D^*$, \begin{equation} \label{eq:stage2_loc} m_i^k = d^k \cdot f(v_i^c), \end{equation} where $m_i^k$ is the predicted object location area of the $k-$th category in the $i-$th visual scenario. If the scenario does not involve the object belonging to the $k-$th category, the corresponding localization map $m_i^k$ tends to remain low response (similarity). At this point, we can obtain $K$ localization maps, indicating the location of different categories of objects. As stated in the beginning, the cocktail-party scenario may consist of multiple sounding objects and silent objects. To localize the sounding objects as well as eliminate the silent ones, the sounding area $l_i$ that is highly related to the input mixed sound is regarded as a kind of sounding object filter, which is formulated as \begin{equation} \label{eq:stage2_filter} s^k_i = m^k_i \circ l_i. \end{equation} $s^k_i$ is deemed as the location of sounding object of the $k-$th category. Intuitively, if the $k-$th object does not produce any sound even if it visually appears in the image, there will be no sounding areas reflected in $s^k_i$. Hence, the category distribution of sounding objects for $v_i^c$ can be written as \begin{equation} \label{eq:stage2_so} p^{so}_{v_i} = softmax([{GAP}(s^1_i), {GAP}(s^2_i),..., {GAP}(s^K_i)]). \end{equation} As discussed in recent works~\cite{hu2019deep}, the natural synchronization between vision and sound provides the self-supervised consistency in terms of sounding object category distribution. In other words, the sound character and the visual appearance of the same sounding object are corresponding in taxonomy, such as barking and dog, meow and cat. Hence, we propose to train the model to discriminatively localize the sounding objects by solving the following problem, \begin{equation} \label{eq:stage2_kl} \mathcal{L}_c = \mathcal{D}_{KL}(p^{so}_{v_i} || p^{so}_{a_i}), \end{equation} where $p^{so}_{a_i}$ is the category distribution of sound $a_i$, predicted by a well-trained audio event network\footnote{The audio network is trained with the pseudo label in the first stage, more details are in the appendix.}, and $\mathcal{D}_{KL}$ is the Kullback–Leibler divergence. Overall, the second stage consists of two learning objective, one is the category-agnostic sounding area detection and the other one is class-aware sounding object localization, i.e., \begin{equation} \label{eq:stage2_obj} \mathcal{L}_2 = \mathcal{L}_c + \lambda \cdot \mathcal{L}_1, \end{equation} where $\lambda$ is the hype-parameter balancing the importance of both objective. By solving the problem in Eq.~\ref{eq:stage2_obj}, the location of sounding objects are discriminatively revealed in the category-specific maps $\left\{s^1_i,s^2_i,...,s^K_i\right \}$. Finally, softmax regression is performed across these class-aware maps on each location for better visualization. \vspace{-3mm} \section{Experiments} \vspace{-3mm} \subsection{Datasets and annotation} \textbf{MUSIC} MUSIC dataset~\cite{zhao2018sop} contains 685 untrimmed videos, 536 solo and 149 duet, covering 11 classes of musical instruments. To better evaluate sound localization results in diverse scenes, we use the first five/two videos of each instrument category in solo/duet for testing, and use the rest for training. Besides, we use one half of solo training data for the first-stage training, and employ the other half to generate synthetic data for the second-stage learning. Note that, some videos are now not available on YouTube, we finally get 489 solo and 141 duet videos. \textbf{MUSIC-Synthetic} The categories of instruments in duet videos of MUSIC dataset are quite unbalanced, e.g., more than 80\% duet videos contain sound of guitar, which is difficult for training and brings great bias in testing. Thus, we build category-balanced multi-source videos by artificially synthesizing solo videos to facilitate our second-stage learning and evaluation. Concretely, we first randomly choose four 1-second solo audiovisual pairs of different categories, then mix random two of the four audio clips with jittering as the multi-source audio waveform, and concatenate four frames of these clips as the multi-source video frame. That is, in the synthesized audiovisual pair, there are two instruments making sound while the other two are silent. Therefore, this synthesized dataset is quite proper for the evaluation of discriminatively sounding object localization\footnote{Available at \url{https://zenodo.org/record/4079386\#.X4NPStozbb0}}. \textbf{AudioSet-instrument} AudioSet-instrument dataset is a subset of AudioSet~\cite{2017audioset}, consisting of 63,989 10-second video clips covering 15 categories of instruments. Following~\cite{gao2019coseparation}, we use the videos from the ``unbalanced" split for training, and those from the ``balanced" for testing. We employ the solo videos with single sound source for the first-stage training and testing, and adopt those with multiple sound sources for the second-stage training and testing. \textbf{Bounding box annotation} To quantitatively evaluate the sound localization performance, we use a well-trained Faster RCNN detector w.r.t 15 instruments~\cite{gao2019coseparation} to generate bounding boxes on the test set. We further refine the detection results, and manually annotate whether each object is sounding or silent. Annotations are publicly available in the released code, for reproducibility. \vspace{-3mm} \subsection{Experimental settings} \textbf{Implementation details} Each video in the above datasets are equally divided into one second clips, with no intersection. We randomly sample one image from the video clip as the visual message, which is resized to $256 \times 256$ then randomly cropped to $224 \times 224$. The audio messages are first re-sampled into 16K Hz, then translated into spectrogram via Short Time Fourier Transform with a Hann window length of 160 and a hop length of 80. Similarly with ~\cite{zhao2018sop,hu2019deep}, Log-Mel projection is performed over the spectrogram to better represent sound characteristics, which therefore becomes a $201 \times 64$ matrix. The audio and visual message from the same video clip are deemed as a matched pair, otherwise mismatched. We use variants of ResNet-18~\cite{resnet} as audio and visual feature extractors. Detailed architecture is shown in the appendix. Our model is trained with Adam optimizer with learning rate of $10^{-4}$. In training phase, we use a threshold of 0.05 to binarize the localization maps to obtain object mask, with which we can extract object representations over feature maps. And each center representation in the object dictionary is accordingly assigned to one object category, which is then used for class-aware localization evaluation. \begin{table}[t] \caption{Localization results on MUSIC-solo and AudioSet-instrument-solo.} \vspace{-3mm} \centering \subtable[Results on MUSIC-solo.]{ \begin{tabular}{l|cc} \toprule Methods & [email protected] & AUC \\ \midrule Sound-of-pixel~\cite{zhao2018sop} & 40.5 & 43.3 \\ Object-that-sound~\cite{arandjelovic2017objects} & 26.1 & 35.8 \\ Attention~\cite{senocak2018learning} & 37.2 & 38.7 \\ DMC~\cite{hu2019deep} & 29.1 & 38.0 \\ Ours & \textbf{51.4} & \textbf{43.6} \\ \bottomrule \end{tabular} \label{tab:music-solo} } \qquad \subtable[Results on AudioSet-instrument-solo.]{ \begin{tabular}{l|cc} \toprule Methods & [email protected] & AUC \\ \midrule Sound-of-pixel~\cite{zhao2018sop} & 38.2 & 40.6 \\ Object-that-sound~\cite{arandjelovic2017objects} & 32.7 & 39.5 \\ Attention~\cite{senocak2018learning} & 36.5 & 39.5 \\ DMC~\cite{hu2019deep} & 32.8 & 38.2 \\ Ours & \textbf{38.9} & \textbf{40.9} \\ \bottomrule \end{tabular} \label{tab:audioset-solo} } \label{tab:solo} \vspace{-6mm} \end{table} \textbf{Evaluation metric} We employ \emph{Intersection over Union} (IoU) and \emph{Area Under Curve} (AUC) as evaluation metrics for single source sound localization, which are calculated with predicted sounding area and annotated bounding box. For discriminative sounding object localization in cocktail-party, we introduce two new metrics, \emph{Class-aware IoU} (CIoU) and \emph{No-Sounding-Area} (NSA), for quantitative evaluation. CIoU is defined as the average over class-specific IoU score, and NSA is the average activation area on localization maps of silent categories where the activation is below threshold $\tau$, \begin{align} CIoU = \frac{\sum_{k=1}^K\delta_k IoU_k}{\sum_{k=1}^K\delta_k},\quad NSA = \frac{\sum_{k=1}^K(1-\delta_k)\sum s^k<\tau}{\sum_{k=1}^K(1-\delta_k)A}, \end{align} where $IoU_k$ is calculated based on the predicted sounding object area and annotated bounding box for the $k-$th class, $s^k$ is localization map of $k$-th class, $A$ is the total area of localization map. The indicator $\delta_k=1$ if object of class $k$ is making sound, otherwise 0. These two metrics measure the model's ability to discriminatively localize sounding objects and filter out the silent ones. \vspace{-3mm} \subsection{Single sounding object localization} \vspace{-3mm} In this subsection, we focus on the simple task of sound localization in single source scenario. Table~\ref{tab:solo} shows the results on MUSIC-solo and AudioSet-instrument-solo videos, where ours is compared with recent SOTA methods. Note that we use the public source code from \cite{zhao2018sop,hu2019deep}. According to the shown results, we have two points should pay attention to. First, the compared methods~\cite{arandjelovic2017objects,hu2019deep,senocak2018learning} are trained to match the correct audiovisual pair via the contrastive~\cite{hu2019deep,senocak2018learning} or classification\cite{arandjelovic2017objects} objective, which is similar to ours. Yet, our proposed method significantly outperform these method by a large margin. Such phenomenon indicates that the learned object representations from localization is effective for semantic discrimination, which further benefits the object localization via the discriminative learning of object category. In order to explain this clearly, we plot the distribution of extracted feature from the well-trained vision network via t-SNE~\cite{maaten2008visualizing}. As shown in Fig.~\ref{fig:ablation}, the extracted visual features on MUSIC-solo are more discriminative in terms of object category when we train the model in a localization-classification alternative learning fashion, where the normalized mutual information for the clustering with masked object features achieves 0.74, which reveals high discrimination of learned representations. Second, our method is comparable to Sound-of-pixel~\cite{zhao2018sop}, especially on the MUSIC-solo dataset. This is because Sound-of-pixel~\cite{zhao2018sop} differently employs the audio-based mix-then-separate learning strategy, which highly relies on the quality of input audio messages. Hence, it could effectively correlate specific visual area with audio embeddings in the simple scene with single sound, but suffers from the noisy multi-source scenarios. In contrast, our method can simultaneously deal with both conditions and does not require to construct complex learning objective. Related results can be found in the next subsection. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{tsne.jpg} \vspace{-3mm} \caption{Visual feature distribution visualized by t-SNE on MUSIC-solo. These figures from left to right are global image features without alternative learning, image features with alternative learning and masked object features with alternative learning. The categories are indicated in different colors.} \vspace{-5mm} \label{fig:ablation} \end{figure} \vspace{-3mm} \subsection{Multiple sounding objects localization} \vspace{-3mm} Natural audiovisual scenario usually consists of multiple sounding and silent objects, which is more challenging for exactly localizing the sounding ones. To responsibly compare different methods under such scenarios, both of the synthetic and realistic data are evaluated. As shown in Table~\ref{tbl:syn}, we can find that our model shows significant improvements over all the compared methods in terms of CIoU. Such phenomenon mainly comes from three reasons. First, our model takes consideration of the class information of sounding objects by employing a category-based audiovisual alignment, i.e., Eq.~\ref{eq:stage2_kl}, while other methods~\cite{arandjelovic2017objects,senocak2018learning} simply correlate the audiovisual features for sounding area detection so that fail to discriminatively localize the sounding objects. Second, our localization results are achieved with the effective visual knowledge learned from the first-stage, which could vastly help to excavate and localize potential objects from cocktail-party scenario, while the compared method~\cite{zhao2018sop} cannot deal with such scenario with mix-then-separate learning fashion. Third, referring to NSA results, our model can automatically filter out the silent objects, but DMC~\cite{hu2019deep} has to rely on given knowledge of the number of sounding objects. Although~\cite{zhao2018sop} is high in NSA, it is probably because of too low channel activations to detect objects rather than the success of filtering out silent ones. Apart from the quantitative evaluation, we also provide visualized localization results in Fig.~\ref{fig:sample}. According to the shown results in realistic scenario, the attention-based approach~\cite{senocak2018learning} and Object-the-sound~\cite{arandjelovic2017objects} can just localize the sounding area without discriminating guitar or cello, while DMC~\cite{hu2019deep} suffers from the complex audiovisual components and mix up different visual areas. Among these compared methods, although sound-of-pixel~\cite{zhao2018sop} provides better results, it cannot exact localize the sounding object and filter out the silent saxophone. This is probably because it highly depends on the quality of mixed sounds. In contrast, our model can successfully localize the sounding guitar and cello in class-specific maps, as well as remain low response for the silent saxophone and other visual areas. The synthetic data show similar results. Note that, we also provide relevant ablation studies about the hyper-parameters and training settings in the appendix. \begin{table}[t] \caption{Localization results on MUSIC-synthetic, MUSIC-duet and AudioSet-instrument-multi. Note that, the CIoU reported in this table is [email protected], and NSA of DMC is not evaluated since it relies on given knowledge to determine whether the object is sounding or silent.} \vspace{-2mm} \label{tbl:syn} \centering{ \begin{tabular}{l|ccc|ccc|ccc} \toprule Data & \multicolumn{3}{c|}{MUSIC-Synthetic} & \multicolumn{3}{c|}{MUSIC-Duet} & \multicolumn{3}{c}{AudioSet-multi} \\\hline Methods & CIoU & AUC & NSA & CIoU & AUC & NSA & CIoU & AUC & NSA \\ \midrule Sound-of-pixel~\cite{zhao2018sop} & 8.1 & 11.8 & 97.2 & 16.8 & 16.8 & \textbf{92.0} & 39.8 & 27.3 & \textbf{88.8} \\ Object-that-sound~\cite{arandjelovic2017objects} & 3.7 & 10.2 & 19.8 & 13.2 & 18.3 & 15.7 & 27.1 & 21.9 & 16.5 \\ Attention~\cite{senocak2018learning} & 6.4 & 12.3 & 77.9 & 21.5 & 19.4 & 54.6 & 29.9 & 23.5 & 4.5 \\ DMC~\cite{hu2019deep} & 7.0 & 16.3 & - & 17.3 & 21.1 & - & 32.0 & 25.2 & -\\ Ours & \textbf{32.3} & \textbf{23.5} & \textbf{98.5} & \textbf{30.2} & \textbf{22.1} & 83.1 & \textbf{48.7} & \textbf{29.7} & 56.8 \\ \bottomrule \end{tabular} } \end{table} \begin{figure}[t] \centering \includegraphics[width=1\linewidth]{visualization.jpg} \vspace{-2mm} \caption{We visualize some localization results of different methods on realistic and synthetic cocktail-party videos. The class-aware localization maps are expected to localize objects of different classes and filter out silent ones. The green box indicates target sounding object area, and the red box means this class of object is silent and its activation value should be low.} \vspace{-4mm} \label{fig:sample} \end{figure} \vspace{-4mm} \section{Discussion} \vspace{-4mm} In this paper, we propose to discriminatively localize sounding objects in the absence of object category annotations, where the object localization in single source videos are aggregated to build discriminative object representation and the audiovisual consistency is used as the self-supervision for category distribution alignment. Although the object semantic learned from simple cases contributes noticeable results, it still need rough partition of single and multiple source videos, which should be emphasized in the future study. \clearpage \section{Acknowledgement} This work was supported in part by the Beijing Outstanding Young Scientist Program NO. BJJWZYJH012019100020098 and Public Computing Cloud, Renmin University of China. \section{Broader Impact} Visually sound source localization is a kind of basic perception ability for human, while this work encourages the machine to be equipped with similar ability, especially when faced with multi-source scenarios. Hence, the impact mainly lies in the machine learning technique and application aspect. On the one hand, the proposed approach is fully based on self-supervised learning, but can reward considerable discrimination ability for the visual objects and correlation capabilities across audio and visual modalities. Predictably, without elaborately manual annotation, this approach could still facilitate the progress of unimodal and multimodal learning and parse/model complex scene. On the other hand, it steps forward to pursuing human-like multimodal perception ability, which could further contribute to our society in several aspects, e.g., audio-assistant scene understanding for the deaf people by figuring out which objects are making sound, facilitating exploration into how to solve the cocktail-party effect in realistic audiovisual scenes, i.e., to perceive different sounds and focus on the pertinent content from mixed auditory input. {\small \bibliographystyle{ieee}
{'timestamp': '2020-10-13T02:28:49', 'yymm': '2010', 'arxiv_id': '2010.05466', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05466'}
arxiv
\section*{Appendix} \begin{defi}[Star-convexity \cite{zhou2018sgd}] Let $\omega^*$ be a global minimizer of a smooth function $F$. Then, $F$ is said to be star-convex at a point $\omega$ provided that $F(\omega) − F(\omega^*) + \langle \omega^* − \omega, \nabla F(\omega)\rangle\leq 0, \forall \omega$. \end{defi} \begin{thm}[Convergence] Let $\{\omega_t\}_{t\in[T]}$ be the sequence of the weight updates from Alg.~\ref{alg:fw-rnn}. Suppose \begin{itemize}[leftmargin=7mm] \item[A1.] $F$ in Eq. \ref{eqn:obj} is {\em locally convex} within each radius $\delta_t, \forall t\in[T]$ \emph{w.r.t. } $\ell_2$ norm centered at $\omega_{t-1}$; \item[A2.] $F$ in Eq. \ref{eqn:obj} is also {\em star-convex}, given a global minimizer $\omega^*$, \emph{i.e., } $F$ is lower bounded by $F(\omega^*)$; \item[A3.] $F$ in Eq. \ref{eqn:obj} is differentiable and its gradient is Lipschitz continuous with constant $L > 0$, \emph{i.e., } $\|\nabla F(\omega_1) - \nabla F(\omega_2)\|_2 \leq L\|\omega_1 - \omega_2\|_2, \forall \omega_1, \omega_2$; \item[A4.] $\omega_t, \forall t$ is upper bounded \emph{w.r.t. } $\omega^*$, \emph{i.e., } $\|\omega_t - \omega^*\|_2\leq \alpha < +\infty, \forall \omega, \exists \alpha$; \item[A5.] It holds that $\beta\leq\|\nabla F(\omega_{t-1}) - \Delta\omega_{t,K}\|_2 \leq (1-L\eta)^{\frac{1}{2}}\|\Delta\omega_{t,K}\|_2, \forall t, \exists\beta>0, \exists\eta\leq\frac{1}{L}$. \end{itemize} Then we have that the output of Alg. \ref{alg:fw-rnn}, $\omega_T$, satisfies \begin{align} F(\omega_T) - F(\omega^*) \leq \frac{\|\omega_0 - \omega^*\|_2^2 + 2\eta C}{2\eta T}, \end{align} where $C=\left(\frac{\alpha}{\beta}-\frac{\eta}{2}\right)(1 - L\eta)\sum_t\|\Delta\omega_{t,K}\|_2^2$, and $\omega_0$ denotes the initialization of the network weights. In particular, $\omega_T$ will converge to $\omega^*$ {\em asymptotically} if $\lim_{T\rightarrow+\infty}\sum_{t=1}^T\delta_t^2<+\infty$ holds. Further, if $-\frac{1}{2\eta}\|\omega_0 - \omega^*\|_2^2\leq C <+\infty$ holds, then $\omega_T$ will converge to $\omega^*$ {\em sublinearly}. \end{thm} \begin{proof} Based on Assmp. A1, A3 and A5, we have \begin{align}\label{eqn:local-convexity} & F(\omega_t) \leq F(\omega_{t-1}) + \langle\nabla F(\omega_{t-1}), \omega_t-\omega_{t-1}\rangle + \frac{L}{2}\|\omega_t-\omega_{t-1}\|_2^2 \\ &= F(\omega_{t-1}) - \eta\langle\nabla F(\omega_{t-1}), \Delta\omega_{t,K}\rangle + \frac{L\eta^2}{2}\|\Delta\omega_{t,K}\|_2^2 \nonumber\\ &= F(\omega_{t-1}) + \frac{\eta}{2}\|\nabla F(\omega_{t-1}) - \Delta\omega_{t,K}\|_2^2 - \frac{\eta}{2}\|\nabla F(\omega_{t-1})\|_2^2 + \frac{L\eta^2-\eta}{2}\|\Delta\omega_{t,K}\|_2^2\leq F(\omega_{t-1}). \nonumber \end{align} Further, based on Assmp. A2, A4 and A5, we have \begin{align}\label{eqn:star-convexity} & F(\omega_t) - F(\omega^*) \nonumber \\ &\leq \langle\nabla F(\omega_{t-1}), \omega_{t-1}-\omega^*\rangle - \frac{\eta}{2}\|\nabla F(\omega_{t-1})\|_2^2 + \frac{\eta}{2}\|\nabla F(\omega_{t-1}) - \Delta\omega_{t,K}\|_2^2 + \frac{L\eta^2-\eta}{2}\|\Delta\omega_{t,K}\|_2^2 \nonumber \\ &= \frac{1}{2\eta}\Big(\|\omega_{t-1} - \omega^*\|_2^2 - \|\omega_t - \omega^*\|_2^2\Big) + \langle\nabla F(\omega_{t-1})-\Delta\omega_{t,K}, \omega_t-\omega^*\rangle + \frac{L\eta^2-\eta}{2}\|\Delta\omega_{t,K}\|_2^2 \nonumber \\ &\leq \frac{1}{2\eta}\Big(\|\omega_{t-1} - \omega^*\|_2^2 - \|\omega_t - \omega^*\|_2^2\Big) + \left(\frac{\alpha}{\beta}-\frac{\eta}{2}\right)(1 - L\eta)\|\Delta\omega_{t,K}\|_2^2. \end{align} Now based on Eq. \ref{eqn:local-convexity} and Eq. \ref{eqn:star-convexity}, we can complete our proof by \begin{align} F(\omega_T) - F(\omega^*) & \leq \frac{1}{T}\sum_t F(\omega_t) - F(\omega^*) \leq \frac{\|\omega_0 - \omega^*\|_2^2}{2\eta T} + \frac{1}{T}\left(\frac{\alpha}{\beta}-\frac{\eta}{2}\right)(1 - L\eta)\sum_t\|\Delta\omega_{t,K}\|_2^2. \nonumber \end{align} \end{proof} \end{document} \section{Conclusions and future directions}\label{sec:conclusion} In this paper, we propose a novel and simple RNN optimizer based on the Frank-Wolfe method. We provide a theoretical proof of the convergence of our algorithm. The empirical experiments on several benchmark datasets demonstrate that the proposed RNN optimizer is an effective solver for the training stability of RNNs. Our algorithm outperforms SGD in all experiments and boosts the TBPTT performances. It also reaches a comparable test accuracy with the baseline algorithm in deep RNNs while requiring fewer gradient updates and less training time. The algorithm shows robustness in the noisy data classification experiment with an improvement of 15.14\%. This work motivates the RNN training on a distributed system. In future work, we will investigate the application of our algorithm in a distributed setting which can reach significant speed-ups at no or nearly no loss of accuracy. \section{Introduction}\label{sec:intr} Consider the problem of training RNNs based on minimizing empirical risk over minibatches, ${\cal B}$ that are sampled uniformly at random from training examples ${\cal X} \times {\cal Y}$ of feature-label pairs $(x,y)$ over $M$ time steps. Let us denote the instance at m-step as $x_m$, and the hidden state as $\mathbf{z}_m$. The batch-averaged empirical risk can be written as: \begin{align}\label{eqn:obj} & \min_{\omega} \left [F(\omega) \stackrel{def}{=} \mathbb{E}_{\mathcal{B}\sim\mathcal{X}\times\mathcal{Y}} f(\mathcal{B}; \omega) \stackrel{def}{=} \sum_{(x,y)\sim\mathcal{B}}\ell(y, \mathbf{z}_M; \omega_{\ell}) \right ] \nonumber \\ & \mbox{s.t.} \,\,\,\mathbf{z}_m = h(x_m, \mathbf{z}_{m-1}; \omega_h), \,\,\,\forall\,\,\, m\in[M], \end{align} where $\omega=\{\omega_{\ell}, \omega_h\}$ denotes the RNN weights, $\ell, h$ denotes the loss and (nonconvex) state transmission functions parameterized by $\omega_{\ell}, \omega_h$, and $\mathbb{E}$ denotes the expectation operator. \bfsection{Vanishing and Exploding Gradients} Training stability of RNNs is regarded as a fundamental aspect, attracting much attention in the literature \cite{cohen1983absolute, guez1988stability, hopfield1982neural, hopfield1984neurons, kelly1990stability, matsuoka1992stability, hui1992dynamical, michel1990analysis, collins2016capacity, miller2018stable}. In this context, gradient explosion/decay is identified as one of the key reasons that prevent RNNs from being trained efficiently and effectively, where the gradient magnitude is either too small or too large, leading to severe training instability \cite{pascanu2013difficulty}. This issue has been attributed to: \begin{itemize}[nosep, leftmargin=7mm] \item[{\em P1.}] The number of time steps, $M$, is large where long-term dependencies exist among the data; \item[{\em P2.}] The state transmission function, $h$, involves multiple hidden states such as in deep RNNs; \item[{\em P3.}] The data samples, $\mathcal{X}$, are very noisy or the true signal is weak. \end{itemize} \begin{wrapfigure}{r}{.4\linewidth} \vspace{-5mm} \begin{center} \includegraphics[width=\linewidth]{figures/idea.pdf} \vspace{-5mm} \caption{\footnotesize{Proposed method.}} \label{fig:idea} \end{center} \vspace{-15pt} \end{wrapfigure} \noindent \bfsection{Proposed Method} Different from prior works that propose methods based on novel designs \cite{chang2018antisymmetricrnn} or architectures \cite{hochreiter1997long} as a means to mitigate gradient decay or explosion, we propose to directly modify the well-known back-propagation algorithm. At a high-level, we propose to estimate the {\em stable} (approximate) gradients in RNNs. In Fig. \ref{fig:idea}, $u$ denotes the current realization for function $F(\omega)$ whose gradient is $\nabla F(u)$. $\Delta u$ denotes the desired output vector that points towards the local minimum from $u$, and $\delta\geq0$ denotes the radius of the search region in the parameter space centered at $u$ (denoted by the dotted circle). Obviously, $\nabla F(u)$ and $\Delta u$ could be quite different, and our goal is to learn $\Delta u$, by looking around in a sufficiently small neighborhood. \bfsection{Trust-Region \emph{vs. } Projected Gradient \emph{vs. } Frank-Wolfe} All of the three methods are potentially applicable for our learning purpose. Trust-region optimization~\cite{byrd1987trust,fortin2004trust,alexandrov1998trust} usually utilizes quadratic approximation to locate a local minimum given the current solution. In deep learning, however, computing the Hessian matrix in the high dimensional space is very challenging. If simplified with the identity matrix, the corresponding closed-form solution is equivalent to the $\ell_2$-normalized gradient. Projected gradient \cite{boyd2004convex} for training RNNs may lead to slow convergence due to the vanishing/exploding gradients, because the inner loop for locating the local minimum relies on the RNN gradients as well. In contrast, we propose to utilize the Frank-Wolfe (FW) algorithm \cite{frank1956algorithm}, one of the simplest and earliest iterative algorithms for constrained optimization due to its projection-free property and large-scale applicability. FW maintains a feasible solution satisfying the constraints, without the need to explicitly incorporate the constraints. Nevertheless, we are generally agnostic to the approach used, and our focus is on RNN training methods that are based on locally optimized trajectory. We collect a few salient aspects of our method and FW in particular to further build intuition. \bfsection{Normalized Gradient \emph{vs. } Frank-Wolfe} Since the magnitude of vanishing or exploding gradients limits RNN trainability, one plausible approach is to normalize gradients. While normalization has been been explored in practice for training deep models \cite{Zhang_2018_CVPR}, results in \cite{Zhang2020Why} demonstrate that the iteration complexity of $\ell_2$-normalized stochastic gradient descent (SGD) is $O(1/\epsilon^4)$ in order to achieve $\epsilon$-stationary solutions. In contrast, although normalization is inherent in the Frank-Wolfe algorithm as well \emph{w.r.t. } $\ell_p (p\geq1)$-norm constraints, such normalization guarantees the solution per iteration to be inside the local region towards a local minimum. Additionally, we show that our proposed Frank-Wolfe algorithm converges faster. \bfsection{Stable Direction} Gradient is singularly local in information, and as such, it does not fully capture the landscape, say, within a small ball around the point. Obviously, if the gradients were small within the entire ball, this would correspond to essentially being on a flat surface. In other cases, we are often in a situation, where the gradient vectors change rapidly, and one can make progress ``if it was possible to look around in suitable neighborhood.'' A measure for changing landscape within a closed convex set, $\mathcal{C}$, for convex smooth functions is the curvature constant $M$ \cite{jaggi2010simple}. For a smooth convex function, $g(\cdot)$, its curvature is defined as the maximum Bregman Divergence, namely, \begin{align}\label{eqn:M} M=\max_{\begin{array}{c} x,y,s \in \mathcal{C}\\ y=(1-\gamma)x + \gamma s \end{array}} \frac{2}{\gamma^2} (g(y)-g(x) - \langle \nabla g(x), y-x\rangle ). \end{align} Note that the curvature $M$ captures the notion of maximum error over all linear approximation errors within the set $\mathcal{C}$, and as such it can be significantly different from the gradient at any specific location. The notion of curvature is intimately tied to the Frank-Wolfe algorithm. A remarkable fact is that the Frank-Wolfe algorithm, is {\it affine invariant}, and with step size $\gamma_k=2/(k+1), \forall k\geq1$, asserts that, at iteration $k$, we can guarantee $g(x^k)-g(x^*) \leq \frac{M}{k+2}$, where $g(x^*)$ is the minimum in the set $\mathcal{C}$. Now, in our context of RNNs, the function $F(\omega)$ is not globally convex, and this convergence rate is no longer true globally. Nevertheless, if one were in a position that satisfies local convexity within a sufficiently small ball of radius $\delta$, it is then possible to assert this fact. While, even this cannot be guaranteed, the situation only demands that along the path trajectory of the updates, we are in a locally convex region. Additionally, one can often realize local convexity by adding a suitably small quadratic regularizer, which is adapted to the current location in the parameter space. In Sec.~\ref{sec:analysis}, under suitable technical conditions, which fall short of global convexity, we show that our proposed algorithm converges at a sublinear rate of $O(1/\epsilon)$ to achieve $\epsilon$ approximation error. The key insight from Eq. \ref{eqn:M} for training RNNs is that {\em for convergence guarantees, local curvature constant, rather than the noisy gradient at the current location is of relevance.} This provides us a means to mitigate vanishing gradients, through leveraging Frank-Wolfe algorithm. \if0 When $\delta\rightarrow0$, maximizing the directional derivative over $\Delta \mathbf{u}$ gradually enforces $\Delta\mathbf{u}$ to be overlapped with the gradient $\nabla F(\mathbf{u})$, that is, the directions of both vectors being the same eventually. Such a motivation provides us an alternative for gradient stabilization, as in our case the gradient magnitude plays a much less important role in learning that helps avoid both vanishing and exploding gradients in training RNNs. Once $\Delta\mathbf{u}$ is learned, it can be fed into an adaptive learning rate optimizer such as Adam \cite{kingma2014adam} or RMSProp \cite{hinton2012neural} to update the weights in RNNs. \fi \if0 \bfsection{Gradient mitigation} Different from prior work that propose methods based on novel designs \cite{chang2018antisymmetricrnn} or architectures \cite{hochreiter1997long} as a means to mitigate gradient decay or explosion, we propose to directly modify the well-known back-propagation algorithm to mitigate gradient explosion or decay. Since the {\em magnitude} of vanishing or exploding gradients limits RNN trainability, one plausible approach is to normalize gradients. While normalization has been been explored in practice for training deep models \cite{Zhang_2018_CVPR}, results in \cite{Zhang2020Why} demonstrate that the iteration complexity of $\ell_2$ normalized stochastic gradient descent (SGD) is $O(1/\epsilon^4)$, to achieve $\epsilon$-stationary solutions. This serves as a motivation for our proposed method, namely, whether {\em can one develop an algorithm, that still incorporates some form of normalization, and leads to faster convergence?} \fi \bfsection{Contributions} Our key contributions in this paper are: \begin{itemize}[leftmargin=*] \item We propose a novel yet simple RNN optimizer based on the Frank-Wolfe method \item We theoretically analyze the convergence of our algorithm and its benefits in RNN training; \item We empirically conduct comprehensive experiments to demonstrate the effectiveness and efficiency of our algorithm in various settings that cover all the scenarios of P1, P2, P3. \end{itemize} \section{Related Work} Below we only summarize the related works in the literature of RNNs. \bfsection{Optimization in RNNs} Truncated backpropagation through time (TBPTT) \cite{jaeger2002tutorial} is a widely used technique to avoid vanishing/exploding gradients in RNNs by controlling the maximum number of time steps in gradient calculation, although it has been demonstrated to be not robust to long-term dependencies \cite{tallec2017unbiasing}. Gradient clipping \cite{pascanu2013difficulty, li2018independently} is another common technique to prevent the exploding (not vanishing) gradients\footnote{Therefore, in practice vanishing gradients are more often for performance degradation of RNNs.} by, for instance, rescaling gradients when their norms are over a predefined threshold. It has been proved in \cite{Zhang2020Why} that gradient clipping can accelerate the training of deep neural networks. The scheme of initializing recurrent weight matrices to be identity or orthogonal has been widely studied such as \cite{le2015simple, arjovsky2016unitary, jing2017tunable, jose2017kronecker, mhammedi2017efficient, wisdom2016full, vorontsov2017orthogonality}. Weight matrix reparametrization has been explored as well \cite{zhang2018stabilizing}. Some other optimization approaches for training RNNs are proposed as well such as real-time recurrent learning (RTRL) \cite{williams1989learning}. To the best of our knowledge, trust-region (although it has been explored in other applications of deep learning such as reinforcement learning \cite{schulman2015trust}) or projected gradient methods have not been studied widely as an RNN optimizer, which we consider as one of our future works. \bfsection{Novel Network Architecture Development for RNNs} Recently there are significant amount of works on developing variants of RNNs such as, just to name a few, long short-term memory (LSTM) \cite{hochreiter1997long}, gated recurrent unit (GRU) \cite{cho2014properties, kanai2017preventing}, Fourier recurrent unit \cite{zhang2018learning}, UGRNN \cite{2016arXivUGRNN}, FastGRNN \cite{kusupati2018nips}, unitary RNNs \cite{arjovsky2016unitary, jing2017tunable, 2018SpectralRNN, 2017oRNN, pennington17}, deep RNNs \cite{pascanu2013construct, zilly2017recurrent, mujika2017fast}, linear RNNs \cite{quasirnn, lei2018sru, balduzzi2016strongly}, residual/skip RNNs \cite{Jaeger07,Bengio2013AdvancesIO,chang2017dilated,campos2017skip,kusupati2018nips}, ordinary differential equation (ODE) based RNNs \cite{talathi2015improving, niu2019recurrent, chang2018antisymmetricrnn, kusupati2018nips, chen2018neural, Yulia2019OdeRNN, kag2019rnns}. For instance, FastGRNN \cite{kusupati2018nips} feed-forwards state vectors to induce skip or residual connections, to serve as a middle ground between feed-forward and recurrent models, and to mitigate gradient decay. Incremental RNNs (iRNNs) \cite{kag2019rnns} are developed based on ODE with theoretical guarantee of identity gradients in the intermediate steps in chain rule for gradient calculation. Independently RNN (IndRNN) \cite{li2018independently} is a network structure where neurons in the same layer are independent of each other and multiple IndRNNs can be stacked to construct a deep network. \section{Frank-Wolfe RNN Optimizer}\label{sec:method} \begin{algorithm}[t] \SetAlgoLined \SetKwInOut{Input}{Input}\SetKwInOut{Output}{Output} \Input{objective $f$, norm $p$, local radius $\delta_t, \forall t$, max numbers of iterations $K, T$} \Output{RNN weights $\omega$} \BlankLine Randomly initialize $\omega_0$; \For{$t=1,\cdots,T$}{ $\Delta\omega_{t,0}\leftarrow\mathbf{0}$; \For{$k=1,\cdots,K$}{ $s_{t,k}\leftarrow\argmin_{s\in\mathcal{C}(p,\delta_t)}\langle s, \nabla_{\Delta\omega} F(\omega_{t-1}+\Delta\omega_{t,k-1})\rangle$; $\Delta\omega_{t,k} \leftarrow (1-\frac{1}{k})\Delta\omega_{t,k-1} + \frac{1}{k}s_{t,k}$; } $\omega_t \leftarrow \omega_{t-1} + \eta\Delta\omega_{t,K}$; } \Return $\omega_T$; \caption{Frank-Wolfe RNN Optimizer}\label{alg:fw-rnn} \end{algorithm} Recall that in our proposed method, given the current point $\omega$ in the parameter space, we attempt to solve a local minima in small ball around $\omega$. To this end, we consider the following general constrained optimization problem, which is also a central aspect of the Frank-Wolfe method: \begin{align}\label{eqn:inner-loop} \min_{\|\Delta\omega\|_p \leq \delta} F(\omega+\Delta\omega), \end{align} where $p>1$ is any $\ell_p$ norm. For our proposed method (see Alg. \ref{alg:fw-rnn}), this constrained optimization is carried out in an inner loop, by means of the FW method. Once, a satisfactory point is reached (which usually is quite fast), we then update the parameters in an outer loop. \if0 Following the notations in Eq.~\ref{eqn:obj}, the directional derivative of $F$ along the (unit) vector $\Delta\omega$ at the current solution $\Tilde{\omega}$, denoted by $D_{\Delta\omega} F(\Tilde{\omega})$, can be defined as \begin{align}\label{eqn:D} D_{\Delta\omega} F(\Tilde{\omega}) = = \langle\nabla F(\Tilde{\omega}), \Delta\omega\rangle, \end{align} where $\nabla F(\Tilde{\omega})\equiv\nabla_{\omega} F(\omega)|_{\omega=\Tilde{\omega}}$ denotes the gradient of $F$ over parameter $\omega$ at $\Tilde{\omega}$. Maximizing the directional derivative is equivalent to minimizing the angle between the gradient and the unit vector, and thus, \begin{align} \max_{\|\Delta\omega\|_2=1} D_{\Delta\omega} F(\Tilde{\omega}) \Leftrightarrow \Delta\omega = \frac{\nabla F(\Tilde{\omega})}{\|\nabla F(\Tilde{\omega})\|_2}, \nonumber \end{align} where $\|\cdot\|_2$ denotes the $\ell_2$ norm of a vector. \fi \bfsection{Frank-Wolfe Algorithm} We apply the stochastic Frank-Wolfe algorithm to solve Eq. \ref{eqn:inner-loop}, and list our novel and simple Frank-Wolfe based RNN optimizer in Alg. \ref{alg:fw-rnn}. In contrast to GD, the iterations in the Frank-Wolfe algorithm are as follows, in general: \begin{equation}\label{eqn:FW} \begin{gathered} s^{(k-1)} =\argmin_{s\in\mathcal{C}}\left\langle s, \nabla f(x^{(k-1)})\right\rangle,\\ x^{(k)} = (1-\gamma_k)x^{(k-1)} + \gamma_k s^{(k-1)}, \end{gathered} \end{equation} where $\langle\cdot,\cdot\rangle$ denotes the inner product of two vectors, and $\gamma_k\in[0,1]$. For $\ell_p (p\geq1)$-norm constraints, \emph{i.e., } $\mathcal{C}(p, \delta)=\{s \mid \|s\|_p\leq\delta\}$, there exist close-form solutions for $\argmin$ in Eq. \ref{eqn:FW}, as \begin{equation} \begin{gathered} s^{(k-1)} = -\alpha\cdot \text{sgn}(\nabla f(x^{(k-1)})) \cdot |\nabla f(x^{(k-1)})|^{\frac{p}{q}}, \\ \mbox{s.t.} \; 1/p + 1/q = 1, \end{gathered} \end{equation} where $\text{sgn}$ and $|\cdot|$ denote entry-wise sign and absolute operators, respectively, and $\alpha\geq0$ is a scalar satisfying $\|s^{(k-1)}\|_q = \delta$. In particular, \begin{itemize}[leftmargin=*] \item $p=2 \Rightarrow s^{(k-1)} = -\delta \cdot \frac{\nabla f(x^{(k-1)})}{\|\nabla f(x^{(k-1)})\|_2}$, \emph{i.e., } $\delta$-scaled $\ell_2$ normalized gradient; \item $p\rightarrow\infty \Rightarrow s^{(k-1)} = -\delta \cdot \text{sgn}(\nabla f(x^{(k-1)}))$, \emph{i.e., } $\delta$-scaled sign gradient. \end{itemize} In Alg. \ref{alg:fw-rnn} we set $\gamma_k = \frac{1}{k}$ to ensure that $\Delta\omega$ always lies inside the local region with convergence guarantee \cite{reddi2016stochastic}. Similarly we decrease $\delta_t$ with the learning rate. Note that Adam \cite{kingma2014adam} can be used to update $\omega$. Besides, Alg. \ref{alg:fw-rnn} can be applied to train other deep models as well. Similar two-loop algorithmic structures have been explored in the literature such as \cite{zhang2019time} for training convolutional neural networks (CNNs). In this paper we focus on the analysis and experiments with $p=2$, although our analysis generally holds for $p\geq1$. In practice, we utilize $p\rightarrow\infty$ to train IndRNN \cite{li2018independently} and achieve $98.37\%$ on Pixel-MNIST with $K=30$ over 400 epochs, similar to the numbers in Table \ref{tab:indRNN}. \input{Ziming_analysis} \input{Ziming_exp} \input{conclusion_yun} {\small \bibliographystyle{IEEEtran} \section{Analysis}\label{sec:analysis} Zhu \emph{et al. } in \cite{allen2019convergence} proved that for training RNNs, when the number of neurons is sufficiently large, meaning {\em polynomial} in the training data size and in network depth, then SGD is capable of minimizing the regression loss in the linear convergence rate. In contrast, we discuss the convergence of Alg.~\ref{alg:fw-rnn} for an arbitrary RNN. We start our analysis from a special case with $\ell_2$-normalized gradients as follows: \begin{thm}[$\ell_2$-Normalized Gradients] Suppose that the following assumptions hold globally: \begin{itemize}[leftmargin=*] \item $F$ is lower-bounded, twice differentiable, and $(L_0, L_1)$-smoothness, \emph{i.e., } $\|\nabla^2 F(\omega)\|_2 \leq L_0 + L_1\|\nabla F(\omega)\|_2, \forall \omega, \exists L_1,L_2>0$; \item There exist a $\tau>0$ such that $\|\nabla f(\mathcal{B}, \omega) - \nabla F(\omega)\|_2\leq\tau, \forall\mathcal{B}, \forall \omega$ holds. \end{itemize} Then for $K=1$ in Alg. \ref{alg:fw-rnn}, there exists $\delta>0$ so that in order to achieve $\epsilon$-stationary points the iteration complexity for Alg.~\ref{alg:fw-rnn} is upper bounded by $O(1/\epsilon^4)$, at least. \end{thm} To prove this theorem, please refer to Thm. 7 in \cite{Zhang2020Why}. Below we extend our analysis to general cases. \begin{defi}[Star-convexity \cite{zhou2018sgd}] Let $\omega^*$ be a global minimizer of a smooth function $F$. Then, $F$ is said to be star-convex at a point $\omega$ provided that $F(\omega) − F(\omega^*) + \langle \omega^* − \omega, \nabla F(\omega)\rangle\leq 0, \forall \omega$. \end{defi} \begin{thm}[Convergence]\label{thm:convergence} Let $\{\omega_t\}_{t\in[T]}$ be the sequence of the weight updates from Alg.~\ref{alg:fw-rnn}. Suppose \begin{itemize}[leftmargin=7mm] \item[A1.] $F$ in Eq. \ref{eqn:obj} is {\em locally convex} within each radius $\delta_t, \forall t\in[T]$ \emph{w.r.t. } $\ell_2$ norm centered at $\omega_{t-1}$; \item[A2.] $F$ in Eq. \ref{eqn:obj} is also {\em star-convex}, given a global minimizer $\omega^*$, \emph{i.e., } $F$ is lower bounded by $F(\omega^*)$; \item[A3.] $F$ in Eq. \ref{eqn:obj} is differentiable and its gradient is Lipschitz continuous with constant $L > 0$, \emph{i.e., } $\|\nabla F(\omega_1) - \nabla F(\omega_2)\|_2 \leq L\|\omega_1 - \omega_2\|_2, \forall \omega_1, \omega_2$; \item[A4.] $\omega_t, \forall t$ is upper bounded \emph{w.r.t. } $\omega^*$, \emph{i.e., } $\|\omega_t - \omega^*\|_2\leq \alpha < +\infty, \forall \omega, \exists \alpha$; \item[A5.] It holds that $\beta\leq\|\nabla F(\omega_{t-1}) - \Delta\omega_{t,K}\|_2 \leq (1-L\eta)^{\frac{1}{2}}\|\Delta\omega_{t,K}\|_2, \forall t, \exists\beta>0, \exists\eta\leq\frac{1}{L}$. \end{itemize} Then we have that the output of Alg. \ref{alg:fw-rnn}, $\omega_T$, satisfies \begin{align}\label{eqn:sublinear} F(\omega_T) - F(\omega^*) \leq \frac{\|\omega_0 - \omega^*\|_2^2 + 2\eta \rho}{2\eta T}, \end{align} where $\rho=\left(\frac{\alpha}{\beta}-\frac{\eta}{2}\right)(1 - L\eta)\sum_t\|\Delta\omega_{t,K}\|_2^2\in\mathbb{R}$, \emph{i.e., } a real number, and $\omega_0$ denotes the initialization of the network weights. In particular, $\omega_T$ will converge to $\omega^*$ {\em asymptotically} if $\lim_{T\rightarrow+\infty}\sum_{t=1}^T\delta_t^2<+\infty$ holds. Further, if $0 \leq \|\omega_0 - \omega^*\|_2^2 + 2\eta\rho <+\infty$ holds, then $\omega_T$ will converge to $\omega^*$ {\em sublinearly}. \end{thm} \begin{proof} Based on Assmp. A1, A3 and A5, we have \begin{align}\label{eqn:local-convexity} & F(\omega_t) \leq F(\omega_{t-1}) + \langle\nabla F(\omega_{t-1}), \omega_t-\omega_{t-1}\rangle + \frac{L}{2}\|\omega_t-\omega_{t-1}\|_2^2 \nonumber\\ &= F(\omega_{t-1}) - \eta\langle\nabla F(\omega_{t-1}), \Delta\omega_{t,K}\rangle + \frac{L\eta^2}{2}\|\Delta\omega_{t,K}\|_2^2 \nonumber\\ &= F(\omega_{t-1}) + \frac{\eta}{2}\|\nabla F(\omega_{t-1}) - \Delta\omega_{t,K}\|_2^2 \nonumber\\ &-\frac{\eta}{2}\|\nabla F(\omega_{t-1})\|_2^2 + \frac{L\eta^2-\eta}{2}\|\Delta\omega_{t,K}\|_2^2\leq F(\omega_{t-1}). \end{align} Further, based on Assmp. A2, A4 and A5, we have \begin{align}\label{eqn:star-convexity} & F(\omega_t) - F(\omega^*) \nonumber \leq \langle\nabla F(\omega_{t-1}), \omega_{t-1}-\omega^*\rangle - \frac{\eta}{2}\|\nabla F(\omega_{t-1})\|_2^2 \nonumber\\&+ \frac{\eta}{2}\|\nabla F(\omega_{t-1}) - \Delta\omega_{t,K}\|_2^2 + \frac{L\eta^2-\eta}{2}\|\Delta\omega_{t,K}\|_2^2 \nonumber \\ &= \frac{1}{2\eta}\Big(\|\omega_{t-1} - \omega^*\|_2^2 - \|\omega_t - \omega^*\|_2^2\Big) \nonumber\\&+ \langle\nabla F(\omega_{t-1})-\Delta\omega_{t,K}, \omega_t-\omega^*\rangle + \frac{L\eta^2-\eta}{2}\|\Delta\omega_{t,K}\|_2^2 \nonumber \\ &\leq \frac{1}{2\eta}\Big(\|\omega_{t-1} - \omega^*\|_2^2 - \|\omega_t - \omega^*\|_2^2\Big) \nonumber\\&+ \left(\frac{\alpha}{\beta}-\frac{\eta}{2}\right)(1 - L\eta)\|\Delta\omega_{t,K}\|_2^2. \end{align} Now based on Eq. \ref{eqn:local-convexity} and Eq. \ref{eqn:star-convexity}, we can complete our proof by \begin{align} &F(\omega_T) - F(\omega^*) \leq \frac{1}{T}\sum_t F(\omega_t) - F(\omega^*) \nonumber\\&\leq \frac{\|\omega_0 - \omega^*\|_2^2}{2\eta T} + \frac{1}{T}\left(\frac{\alpha}{\beta}-\frac{\eta}{2}\right)(1 - L\eta)\sum_t\|\Delta\omega_{t,K}\|_2^2. \nonumber \end{align} \end{proof} Equivalently, Thm. \ref{thm:convergence} states that our algorithm needs $O(\frac{1}{\epsilon})$ updates of $\omega$, independent on the inner loops $K$ in Alg. \ref{alg:fw-rnn}, in order to achieve an $\epsilon$-stationary solution. Note that the constant $\rho$ is highly correlated with the number of inner loops, $K$, in the algorithm. Therefore, empirically it is challenging to tell which choice of $K$ will be the best. From our experiments, we found that often small $K$'s can work better than SGD for training RNNs. \begin{wrapfigure}{r}{.5\linewidth} \vspace{-10mm} \begin{center} \includegraphics[width=\linewidth]{figures/A5.pdf} \vspace{-5mm} \caption{\footnotesize{Geometric interpretation.}} \label{fig:A5} \end{center} \vspace{-10pt} \end{wrapfigure} \bfsection{Geometric Interpretation of Assmp. A5} In Fig. \ref{fig:A5}, we illustrate the geometric relationship between $\nabla F(\omega_{t-1}), \Delta\omega_{t,K}$ and $\nabla F(\omega_{t-1}) - \Delta\omega_{t,K}$ given the current solution $\omega_{t-1}$ and $\beta\rightarrow0$. Clearly, any point within the green dotted circle (with radius $(1-L\eta)^{\frac{1}{2}}\|\Delta\omega_{t,K}\|_2$) will be a candidate for $\nabla F(\omega_{t-1})$ so that A5 holds. Therefore, the angle between any pair of $\nabla F(\omega_{t-1})$ and $\Delta\omega_{t,K}$ should be no more than $\pm 45^o$. In other words, $\nabla F(\omega_{t-1})$ and $\Delta\omega_{t,K}$ should have very similar directions. We verified this on the HAR-2 dataset (see Sec. \ref{sec:exp}) by computing such angles to see the distribution using 200 epochs. Statistically these angles are within $\pm 45^o$ with mean $-4.19^o$ and std $0.51^o$. \bfsection{Inexact Update in Frank-Wolfe} In the stochastic setting with limited $K$ and large-scale data, however, $\nabla F(\omega_{t-1}), \Delta\omega_{t,K}$ are infeasible to compute exactly. To address this problem, we borrow the concept of approximation quality in the inexact Frank-Wolfe method in \cite{jaggi2013revisiting}. \begin{defi}[\cite{jaggi2013revisiting}] In the Frank-Wolfe update, $s_{t,k} (\|s_{t,k}\|_2\leq\delta_t)$ is used so that it holds that \begin{equation}\label{eqn:approximation} \begin{gathered} \langle s_{t,k}, \nabla F(\omega_{t-1}+\Delta\omega_{t,k-1})\rangle \leq \\ \min_{\|s\|_2\leq \delta_t} \langle s, \nabla F(\omega_{t-1}+\Delta\omega_{t,k-1})\rangle + \frac{\lambda M_F}{k+1}, \; \forall k\geq 1, \end{gathered} \end{equation} where $\lambda\geq0$ denotes an arbitrary accuracy parameter that controls the upper bound of the convergence rate linearly from factor $1$ to $(1+\lambda)$, and $M_F$ denotes the curvature constant of $F$. \end{defi} Note that Eq. \ref{eqn:approximation} will still hold by setting $\lambda = \max_k\left\{\frac{2\delta_t(k+1)}{M_F}\|\nabla F(\omega_{t-1}+\Delta\omega_{t,k-1})\|_2\right\}<+\infty.$ Clearly, as long as $\|\nabla F(\omega_{t-1}+\Delta\omega_{t,k-1})\|_2=O(1/k)$ is met, the convergence of Alg. \ref{alg:fw-rnn} can be always guaranteed. \bfsection{Stochastic Frank-Wolfe in Alg. \ref{alg:fw-rnn}} In our implementation, we utilize the stochastic Frank-Wolfe method \cite{reddi2016stochastic} instead for computational efficiency. Essentially stochastic FW can be considered as a realization of inexact update in FW, and thus all the analysis above holds for this case as well. \section{Experiments}\label{sec:exp} \textbf{Datasets.} We test our RNN optimizer on the following benchmark datasets with all the statistics listed in Table \ref{tab:data}: \begin{itemize}[leftmargin=*] \item {\em Adding task:} We strictly follow the adding task\footnote{\url{https://github.com/rand0musername/urnn}} defined by \cite{arjovsky2016unitary, hochreiter1997long} to generate the dataset. There are two sequences with length $T=100$. The first sequence is sampled uniformly at random $\mathcal{U}[0,\,1]$. The second sequence is filled with 0 except for two entries of 1. The two entries of 1 are located uniformly at random position $i_1, i_2$ in the first half and second half of the sequence. The prediction value is the sum of the first sequence between $[i_1, i_2]$. \item {\em Pixel-MNIST \& Permute-MNIST:} Pixel-MNIST refers to pixel-by-pixel sequences of images in MNIST where each 28 $\times$ 28 image is flattened into a 784 time sequence vector, while a random permutation to the Pixel-MNIST is applied to generate a harder time sequence dataset as Permute-MNIST. All datasets are normalized as zero mean and unit variance during training and prediction. \item {\em HAR-2 \cite{kusupati2018nips}:} HAR-2 was collected from an accelerometer and gyroscope on a Samsung Galaxy S3 smartphone, and all samples are normalized with zero mean and unit variance. \item {\em Noisy-HAR-2:} This dataset is generated by adding Gaussian noise to HAR-2 with a mean of zero and a variance of two to HAR-2 to evaluate the robustness of our algorithm. \end{itemize} \bfsection{Baseline Algorithms and Implementation} We compare our Frank-Wolfe based RNN optimizer with SGD (gradient clipping involved if necessary) and TBPTT comprehensively, using (1) a vanilla RNN with one-layer transition function consisting of a linear function followed by a $\tanh$ activation (same as the literature. See \cite{kusupati2018fastgrnn}) and (2) IndRNN with six layers\footnote{\url{https://github.com/Sunnydreamrain/IndRNN_pytorch}}. Mean-square-error (MSE) and cross-entropy losses are applied for binary and multi-class classification tasks, respectively. Adam \cite{kingma2014adam} is used as the optimizer for all the methods. We implement our experiments using PyTorch, and run all the experiments on an Nvidia GeForce RTX 2080 Ti GPU with CUDA 10.2 and cuDNN 7.6.5 on a machine with Intel Xeon 2.20 GHz CPU with 48 cores. The code of our optimizer can be found here \footnote{\url{https://github.com/YunYunY/FW_RNN_optimizer}}. \bfsection{Hyperparameters} The hyperparameters of the vanilla RNN and IndRNN are the same as the literature \cite{Kag2020RNNs, kusupati2018fastgrnn, li2018independently}, if applicable, as from our experiments they seem to be the best settings. For our optimizer we perform a grid search over several learning rates \{2e-5, 2e-4, 6e-4, 1e-3\}, batch size \{32, 64, 128, 256, 512\} and learning rate decay factor \{0.1, 0.5, 0.9\} on validation data (from a small portion of training data) to ensure that a good parameter is used in our algorithm. We use hidden dimension 128 for MNIST datasets and the Adding task. When training HAR-2 related tasks, we use hidden dimension 80. We report the best test accuracy \subsection{Results} \begin{wrapfigure}{r}{5cm} \vspace{-10mm} \begin{center} \includegraphics[width=\linewidth]{figures/adding_loss.pdf} \vspace{-5mm} \caption{Training loss of Adding Task} \label{fig:addtask} \end{center} \vspace{-3mm} \end{wrapfigure} \textbf{Adding Task.} The Adding task is designed to evaluate the capability of RNNs to capture long-term dependency among the data \cite{2018SpectralRNN, li2018independently, le2015simple, arjovsky2016unitary, arjovsky2016unitary, hochreiter1997long}. Fig. \ref{fig:addtask} illustrates the loss change of our algorithm compared with SGD on this task when the time sequence is long. It is clear that our algorithm converges after a reasonable number of iterations while SGD lost the learning ability in this task. We hypothesize that at the beginning all the algorithms search for a good direction within a certain region. Given sufficient updates later, our algorithm starts to move towards informative directions, leading to significantly fast convergence. \bfsection{Vanilla RNN on Pixel-MNIST \& Permute-MNIST} We further apply our algorithm to Pixel-MNIST and Permute-MNIST and compare it with Adam and TBPTT. The forward and backward steps of TBPTT are set to 196, which means each 784 time sequence is partitioned into 4 segments. For our algorithm, we perform the inner iteration $K$=1 and 5. Since our algorithm can be easily combined with TBPTT, we also include the combination experiments on the two datasets. Fig. \ref{fig:p1_pixel} shows the change of training cross-entropy and test accuracy of RNN with the epoch for Pixel-MNIST and Permute-MNIST. Without extra optimization techniques, SGD shows no convergence or very slow convergence. We observe that TBPTT does help the convergence for the Permute-MNIST, however, the performance of TBPTT is only slightly better than the baseline SGD in the Pixel-MNIST case with sporadically increases and decreases of loss. As a contrast, our algorithm shows a faster convergence rate and a much more stable performance on both datasets. When TBPTT is combined with our algorithm, the model achieves faster convergence and higher test accuracy than the baseline for Pixel-MNIST. As for Permute-MNIST, the combination method eventually reaches higher test accuracy with more training epochs. It is worth mentioning that when the inner iteration $K$ increases in our algorithm, the total number of gradient updates needed for convergence decreases. \begin{figure}[t] \begin{minipage}[b]{0.49\columnwidth} \begin{center} \centerline{\includegraphics[height=3.5cm, keepaspectratio,]{figures/p1pixel_loss.pdf}} \end{center} \end{minipage} \begin{minipage}[b]{0.49\columnwidth} \begin{center} \centerline{\includegraphics[height=3.5cm,keepaspectratio]{figures/p1pixel_test_acc.pdf}} \end{center} \end{minipage} \hfill \begin{minipage}[b]{0.49\columnwidth} \begin{center} \centerline{\includegraphics[height=3.5cm,keepaspectratio]{figures/p1permute_loss.pdf}} \end{center} \end{minipage} \begin{minipage}[b]{0.49\columnwidth} \begin{center} \centerline{\includegraphics[height=3.5cm,keepaspectratio]{figures/p1permute_acc.pdf}} \end{center} \end{minipage} \vspace{-5mm} \caption{\footnotesize Training loss and test accuracy on Pixel-MNIST and Permute-MNIST} \label{fig:p1_pixel} \end{figure} \bfsection{IndRNN on Pixel-MNIST \& Permute-MNIST} This experiment addresses the application of our algorithm on training deep models. Since IndRNN can be stacked to construct a deep network \cite{li2018independently}, we apply a six-layer IndRNN structure with the two benchmark datasets Pixel-MNIST and Permute-MNIST. The model has proved the state-of-the-art performance on the two datasets with Adam optimizer \cite{li2018independently}, thus we also use Adam as the baseline algorithm to compare with ours. The model structure we use follows exactly \cite{li2018independently}.The inner iteration $K$ is tested with values \{1, 5, 10, 30\}. The training loss and test accuracy results of the two datasets trained with IndRNN are shown in Fig. \ref{fig:indRNN}. IndRNN applied batch normalization (BN) to accelerate Pixel-MNIST training. Due to the truncated training process of TBPTT, the relevant statistics over the mini-batch changes over time. It is not suitable to apply BN to TBPTT. Thus in Fig. \ref{fig:indRNN} we only compare our algorithm with the baseline IndRNN. Our algorithm has the same performance as Adam optimizer. In terms of accuracy, our algorithm achieves comparable test accuracy after 400 epochs using about half training time when $K$=5. \begin{figure}[hbt!] \hfill \begin{minipage}[b]{0.45\columnwidth} \begin{center} \centerline{\includegraphics[width=\columnwidth]{figures/p2ind_loss.pdf}} \end{center} \end{minipage} \hfill \begin{minipage}[b]{0.45\columnwidth} \begin{center} \centerline{\includegraphics[width=\columnwidth]{figures/p2permute_loss.pdf}} \end{center} \end{minipage} \hfill \vspace{-5mm} \caption{\footnotesize Training loss on Pixel-MNIST and Permute-MNIST with indRNN} \label{fig:indRNN} \end{figure} \begin{table}[hbt!] \def\arraystretch{0.8}% \begin{center} \caption{\footnotesize Test accuracy (\%) (training hours) of IndRNN} \label{tab:indRNN} \begin{tabular}{l c c c} \toprule \multirow{2}{*}{\textbf{Dataset}} & \multicolumn{3}{c}{\textbf{Acc. (Time)}} \\ \cmidrule(lr){2-4} & Baseline & Ours K=1 & Ours K=5 \\ \midrule Pixel-MNIST & 98.88 (4.84) & 98.73 (3.46) & 98.82 (2.55)\\ \midrule Permute-MNIST & 93.00 (4.92) & 92.87 (3.68) & 92.59 (2.41)\\ \bottomrule \end{tabular} \end{center} \end{table} \bfsection{RNNs on HAR-2 \& Noisy HAR-2} This experiment focuses on noise-free and noisy sequences. When the data samples are very noisy, RNNs usually exhibit unstable performance. To verify the robustness of our algorithm on noisy input, we compare the performance of the proposed optimizer with Adam and TBPTT on plain RNN with HAR-2 and Noisy-HAR-2 as input. The task is binary classification after observing a long sequence. HAR-2 has a 128 time sequence. Adding Gaussian noise with a mean of zero and a variance of two makes the task harder. We set forward and backward steps in TBPTT as 16. Thus the sequence is split into 16 segments. Same as Experiment 1, we also include the combination of TBPTT and our algorithm in the experiment. We also demonstrate the compatibility of our algorithm with LSTM and BN using the two datasets. We estimate the MSE of each experiment. \begin{figure}[t] \hfill \begin{minipage}[b]{0.45\columnwidth} \begin{center} \centerline{\includegraphics[width=\columnwidth]{figures/har_loss.pdf}} \end{center} \end{minipage} \hfill \begin{minipage}[b]{0.45\columnwidth} \begin{center} \centerline{\includegraphics[width=\columnwidth]{figures/noisyhar_loss.pdf}} \end{center} \end{minipage} \hfill \vspace{-5mm} \caption{\footnotesize Training loss of RNN on HAR-2 and Noisy-HAR-2} \label{fig:har} \end{figure} \begin{table}[t] \caption{\footnotesize Test accuracy (\%) and training time (hr) of RNN} \label{tab:har} \centering \begin{tabular}{l c c c c } \toprule \textbf{Method} & \textbf{HAR-2} & \textbf{Time} & \textbf {Noisy-HAR-2} & \textbf{Time} \\ \midrule SGD & 87.66 & 0.17 & 74.38 & 0.17\\ SGD+Clipping & 93.36 & 0.13 & 74.38 & 0.13 \\ TBPTT & 93.62 & 0.38 & 86.20 & 0.56\\ LSTM+Adam & 94.40 & 0.14 & 92.12 & 0.17\\ Ours K=1 & 93.52 & 0.15 & 86.04 & 0.14 \\ Ours K=5 & 94.11 & 0.14 & 89.36 & 0.14\\ Ours K=10 & 93.65 & 0.37 & 89.52 & 0.35\\ Ours+BN & 94.37 & 0.36 & 89.38 & 0.41\\ TBPTT+Ours & 94.01 & 0.35 & 89.28 & 0.84\\ LSTM+Ours & 94.95 & 0.19 & \textbf{92.41} & 0.42\\ IndRNN & 95.73 & 0.46 & 91.20 & 0.45\\ IndRNN+Ours & \textbf{96.55} & 0.13 & 92.15 & 0.17\\ \bottomrule \end{tabular} \end{table} Fig. \ref{fig:har} and Table~\ref{tab:har} show that our algorithm is not only robust to long-term dependency tasks but also robust to noisy time sequences. No matter the input data is noise-free or noisy, the training losses of SGD oscillate up and down. The TBPTT reaches a desirable MSE in the noise-free case because the forward and backward steps are set up relatively short. TBPTT is capable of avoiding the vanishing gradient issue in this setting. The literature shows RNN with SGD usually reaches a test accuracy 91.31\% with the learning that takes at least 300 epochs on HAR-2 dataset \cite{kusupati2018nips}. With the same initial learning rate setting, our algorithm outperforms the baseline within less training epochs. It is shown in Table~\ref{tab:har} that gradient clipping does improve the model performance on noise-free data, however, it loses its advantage when applied to Noisy-HAR-2 dataset. When combining our algorithm with TBPTT, we reach the test accuracy 94.01\%. The baseline accuracy of SGD is 15.14\% less than our algorithm on the Noisy-HAR-2 task. We also verified that our optimizer works well with LSTM and BN as listed in Table~\ref{tab:har}. When our algorithm is combined with IndRNN, it overpasses the original IndRNN with less running time.
{'timestamp': '2020-10-16T02:21:14', 'yymm': '2010', 'arxiv_id': '2010.05397', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05397'}
arxiv
\section{Introduction} The search for life has been one of the oldest endeavours of mankind. But only recently have we acquired the capability to take even a step towards this lofty goal. With the first exoplanet discovered in 1991\cite{cochran1991constraints}, we have now reached a point where we have discovered over 4000 exoplanets. We have also taken steps in discovering if life exists on these planets through the use of various metrics such as the Earth Similarity Index\cite{schulze2011two} or the Cobb-Douglas Habitability Score (CDHS) \cite{bora2016cd}. These metrics take various planetary parameters as inputs and give us an intuitive understanding of the likelihood of life existing on these planets. The Cobb-Douglas Habitability Production Function (CD-HPF) can quickly give us a score that is representative of the potential of habitability of an exoplanet. It takes in the Radius, Density, Escape Velocity and Mean Surface Temperature of a planet as inputs. All these inputs are in Earth Units(EU) i.e. the metric measurements of these parameters are divided by Earth's own measurements. Simply put, the values of any parameter of Earth in Earth Units is 1. The Cobb-Douglas function was first developed in 1927\cite{coma1928theory}, seeking to mathematically estimate the relationship between workers, capital and goods produced. In its most standard form for production of a single good with two factors, it is written as $$ Y = AL^\beta K^\alpha $$ Where, $Y$ is the total production, $A$ is total factor productivity, $L$ and $K$ being the labour and capital inputs, and $\alpha,\beta$ being output elasticities of labour and capital respectively. The function itself is highly adaptable and has been utilized for various tasks like revenue models for data centers\cite{saha2016novel}, frameworks for computing scholastic indicators of influence of journals\cite{ginde2016scientobase} successfully. The CDHS is calculated in a two-fold manner: by calculating the interior-CDHS using radius and density, and the surface-CDHS, by using escape velocity and surface temperature; the final score is computed by a convex combination of the two scores. Thus the function is formulated as a multi-objective optimization problem of the two scores. Most optimization functions require the gradient of a function to minimize or maximize it. However, this can prove computationally costly and all functions are not differentiable, and even then, the derivative might not be smooth or continuous. In this paper, we use Genetic Algorithms, a class of gradient-free optimization functions, which are more widely applicable by virtue of them not requiring the derivative of the function to optimize it. In the book, "On the Origin of Species" by Charles Darwin, he concluded that only those species survived who were successful in adapting to the changing environment and others died. He called this "Natural Selection" which has three main processes; Heredity,Variation and Selection. These involve species receiving properties from their parents, making variations to evolve and then being selected based on their adaptation to the environment for their survival. Along these lines, genetic algorithms \cite{holland1992adaptation} were introduced with five phases of process to solve an optimization problem. We create a initial population of randomly generated elements, known as solutions to the problem and then evaluate the correctness of the solutions using a fitness function which tells us how well the solution helps in optimizing the problem. Genetic Algorithms revolve around the twin principles of Exploration and Exploitation. There must be enough variety in the population to 'explore' the solution space which is usually vast, and on finding good solutions, the algorithm must 'exploit' these solutions and generate incrementally better solutions. The typical Genetic Algorithm consists of 3 processes: Selection, Crossover and Mutation. In this paper, we use a modified version of a GA that combines the processes of Mutation and Crossover into one. This Proto-Genetic Algorithm is simpler to implement and understand while not compromising on performance. We evaluate the 'fitness' of the population, that is to say we find the value of the function to be optimized using the members of the population, generate children using \textit{one} parent and then test their fitness as well, choosing the best for the next generation. It is similar to the biological process of asexual reproduction where the child inherits all the traits from one parent alone. In this case, the child is generated from a Gaussian Distribution (as shown in Figure 2) centered at the parent's value. We illustrate the results of our algorithm on the set of Earth-like exoplanets that is the TRAPPIST system from the exoplanet catalog\cite{phl}, hosted by the Planetary Habitability Laboratory at the University Of Puerto Rico at Acerbio. \section{Genetic Algorithms} A Genetic Algorithm (GA) is a meta heuristic which is based on the process of natural selection. It is a subset of the class of Evolutionary Algorithms which take cues from biological processes. They are most commonly used in optimization or search problems as they are capable of searching large combinatorial solution spaces to find globally optimal solutions. Figure 1 indicates the pseudo-code of a typical Genetic Algorithm where a \textit{population} of solutions are initialized randomly, given the constraints of a specific problem. The \textit{fitness} of each solution is calculated, which is the value returned by the given function for that solution. Following which the genetic operators of Selection, Crossover and Mutation take place in order to create an incrementally better population. This process is repeated until a termination condition is met, such as a specified number of \textit{generations}. \begin{figure}[ht] \centering \includegraphics[height = 4.5cm, width = 7.5cm]{figures/Genetic-Algorithm-pseudocode.png} \caption{Pseudo-code of a typical Genetic Algorithm} \end{figure} \subsection{Proto-Genetic Algorithm} In this paper, we have utilized a simpler version of the Genetic Algorithm. While GA's typically generate children using traits from both two parents, we have utilized a single-parent reproduction which is both crossover and mutation rolled into one. The best half of the population is selected and a single child is created for each parent. This child is created using a Gaussian Distribution centered at the parent, thus allowing for a mutation of sorts to occur. Due to the nature of the Gaussian Distribution, a small change is much more likely to happen than a drastic one, which reflects real life as well. At the end of this process, we have a highly fit population. This algorithm is simpler to understand and implement but gives satisfactory results. \begin{figure} \centering \includegraphics[height = 6.5cm, width = 8.5cm]{figures/GaussianDist.png} \caption{The bell-shaped curve of the Gaussian Distribution} \end{figure} \section{Implementation} \subsection{Single Objective Optimization} Various test functions like Mishra, Rastrigin, Schaffer and others share many similarities\cite{back1996evolutionary}. All of them have 2 parameters and are highly multimodal. Thus, these functions serve as suitable benchmarks for GA. We first initialize 2 sets of values for $x$ and $y$, having populations of 200 values each. Our next step is to run the Genetic Algorithm. Here we choose to run the algorithm for 1000 generations, that is to say the processes of crossover, mutation and recombination take place 1000 times at the end of which we have solutions which are very close to the global minimum. The fitness measure here is of course the value of the function for the parameters $x$ and $y$. After calculating the fitness for each pair we then choose the best pairs, i.e. the ones with the lowest fitness and then use them as the parents of the next generation. Generation of children is done using the Gaussian Distribution, allowing us to vary the children slightly in each generation. This is followed by checking the fitness of each child and arranging the children and the parents in order of their fitness. This weeds out all the parents who were not good enough and the children who were worse than their parents. Finally, we remake the population choosing the best of both the old and the new generation. For example, the Rastrigin Function\cite{muhlenbein1991parallel}, a commonly used benchmark function used to test optimization algorithms due to its highly multimodal nature: $$ f(x,y) = 20 + x^2 + y^2 - 10(cos(2\pi x) + cos(2 \pi y))$$ \begin{figure}[ht] \centering \includegraphics[height = 5cm, width = 8cm]{figures/rastriginfx.jpg}\\ \caption{The Rastrigin Function} \end{figure} The Rastrigin function in Figure 3 has a global minima of 0.0 with the domain being from -5.12 to 5.12. Thus, our algorithm generates 200 values of $x$ and $y$ in the given domain, which is the first generation of the algorithm. They are sorted according to their fitness and new children are generated from the best half of the population. Following this the population is remade by sorting according to fitness again and the second generation is created, with the members being slightly \textit{fitter} than their parents. Table 1 compares the actual global minima and that obtained using GA for various test functions. \begin{table}[htbp] \caption{Single Objective Optimization Results} \begin{center} \begin{tabular}{|l|c|c|} \hline \textbf{Test}&\multicolumn{2}{|c|}{\textbf{Global Minimum}} \\ \cline{2-3} \textbf{Functions} & \textbf{\textit{Actual Values}}& \textbf{\textit{GA Values}} \\ \hline Easom & -1 & -0.999 \\ \hline Rastrigin & 0.0 & 0.0003 \\ \hline Ackley & 0.0 & 0.009 \\ \hline Beale & 0.0 & 0.0 \\ \hline Goldstein-Price & 3.0 & 3.0001 \\ \hline Mishra No.4 & -0.199 & -0.193 \\ \hline Cross-in-tray & -2.06 & -2.06 \\ \hline Eggholder & -959.64 & -959.27 \\ \hline Holder table & -19.208 & -19.208 \\ \hline McCormick & -1.913 & -1.913 \\ \hline Schaffer No.4 & 0.292 & 0.292 \\ \hline \multicolumn{3}{l}{$^{\mathrm{}}$} \end{tabular} \label{tab1} \end{center} \end{table} \subsection{Constrained Optimization} These functions are also single objective optimization problems, however they are constrained. Whereas the previous batch of functions are only limited by the search domains, these functions have additional constraints. They tend to be more challenging to optimize. Mishra's Bird Function displayed in Figure 4 \cite{mishra2006some} has a global minima of -106.76 and the domain being from -10 to 0 for $x$ and -6.5 to 0 for $y$. The function is given as: \begin{multline*} f(x,y) = sin(y).e^{((1-cos(x))^2)} + cos(x).e^{((1-sin(y))^2)} + (x-y)^2 \end{multline*} In addition to minimizing this, the solutions must also not violate the additional constraint which is: $$ (x+5)^2 + (y+5)^2 < 25 $$ We follow the same procedure as with single objective optimization, albeit making sure the solutions do not violate the constraints along with the upper and lower bounds of the domain. Children generated will be discarded if they do not satisfy the constraints. The standard deviation of the Gaussian Distribution goes on increasing to widen the search range if a large number of solutions are discarded. Table 2 lists different test functions along with their actual and GA obtained global minimum. \begin{figure}[ht] \centering \includegraphics[height = 7cm, width = 8cm]{figures/mishrabird.png} \caption{Mishra's Bird Function (Constrained)} \end{figure} \begin{table}[htbp] \caption{Constrained Optimization Results} \begin{center} \begin{tabular}{|l|c|c|} \hline \textbf{Test}&\multicolumn{2}{|c|}{\textbf{Global Minimum}} \\ \cline{2-3} \textbf{Functions} & \textbf{\textit{Actual Values}}& \textbf{\textit{GA Values}} \\ \hline Rosenbrock (with a cubic and a line) & 0.0 & 0.0009 \\ \hline Rosenbrock (disk) & 0.0 & 0.0 \\ \hline Mishra's Bird & -106.76 & -106.76 \\ \hline Townsend & -2.02 & -2.02 \\ \hline Simionescu & -0.072 & -0.0719 \\ \hline \multicolumn{3}{l}{$^{\mathrm{}}$} \end{tabular} \label{tab2} \end{center} \end{table} \begin{figure*} \centering \includegraphics[height = 6cm, width = 13cm]{figures/Basics-of-NSGA-II-procedure.png} \caption{Basics of NSGA-II Procedure} \end{figure*} \subsection{Multi-Objective Optimization} Whereas for single-objective optimization problems there exists a single solution which is the best value, no such solution exists for non-trivial multi-objective problems. Multi-objective Optimization problems involve minimizing/maximi\-zing more than one function simultaneously. If these functions are competitive i.e. minimizing one maximizes the other, it is not possible to find a single best solution. Instead we get a set of \textbf{non-dominating} solutions known as a \textbf{Pareto Front} (as shown in Figure 6). In the absence of other information, each solution in the Pareto Front is equally valid and no solution can be said to be better than another. Pareto fronts are based on the idea of dominance. If $\vec{x},\vec{y}$ are two solutions, then $\vec{x}$ is said to dominate $\vec{y}$ if $$f_i(\vec{x})) \leq f_i(\vec{y})) \ \forall \ i = 1, 2, 3, ...k $$ In another words, the vector $\vec{x}$ is said to dominate $\vec{y}$ if and only if, $f(x) \leq f(y)$ for every single objective in the multi-objective optimization problem. We say that a vector of decision variables $\vec{x} \in F$ is said to be Pareto optimal if no other vector $\vec{x} \in F$ exists such that $f(\vec{y}) \leq f(\vec{x}).$ A multi-objective optimization consists of finding the best Pareto front for a given set of objectives. There are various algorithms for multi-objective optimization. Indeed, one such algorithm, Particle Swarm Optimization (PSO) has already been used in solving the CD-HPF\cite{theophilus2018novel}. PSO have many advantages over GA\cite{eberhart1998comparison} and hybrid PSO-GA have also been used in problems like intelligent routing\cite{v2015qos} to great success. When solving a multi-objective optimization problem using GA, a different approach must be taken. While in single objective problems we can directly compare function values as fitness and choose the best parents, the same cannot be done when we have multiple objectives to optimize. There are numerous algorithms such as MOGA\cite{fonseca1993genetic}, NSGA\cite{srinivas1994muiltiobjective}.In this paper, we have used one of the most popular multi-objective optimization algorithms, NSGA-II\cite{deb2002fast}. \begin{figure}[H] \centering \includegraphics[height = 7cm, width = 8cm]{figures/Pareto_Dominated.png} \caption{A Pareto Front} \end{figure} NSGA-II as illustrated in Figure 5 consists of two new processes in order to assign fitness to solutions. The first is the \textbf{non-dominated sort}, where the solutions are sorted into sets of non-dominating solutions i.e. fronts. The second is the \textbf{crowded-comparison}, which ensures that solutions which have fewer number of solutions in their vicinity have a higher chance of getting selected. In other words, this algorithm favours non-dominated solutions which are well distributed. Thus we can assign a fitness to the solutions even with multiple objectives. Following this we use our proto-genetic algorithm to evolve the chosen solutions and continue the process iteratively until we have our population closely resembling the optimal Pareto Front. Figures 7 and 8 compare the actual and obtained pareto fronts of different test functions. \begin{figure} \centering \subfloat[Poloni]{\includegraphics[width=4cm]{figures/poloniwiki.jpg}} \qquad \subfloat[Schaffer1]{\includegraphics[width=4cm]{figures/schaffer1wiki.jpg}} \qquad \subfloat[CTP 1]{{\includegraphics[width=4cm]{figures/ctpwiki.jpg}}} \qquad \subfloat[Constr-Ex]{{\includegraphics[width=4cm]{figures/constrexwiki.jpg}}} \qquad \subfloat[Binh and Korn]{{\includegraphics[width=4cm]{figures/binhkornwiki.jpg}}} \qquad \subfloat[Chakong and Haimes]{{\includegraphics[width=4cm]{figures/chakonghaimeswiki.jpg}}} \caption{Actual Pareto Fronts of Test Functions} \label{fig:paretowiki} \end{figure} \begin{figure}[ht] \centering \subfloat[Poloni]{\includegraphics[width=4cm]{figures/poloni.png}} \qquad \subfloat[Schaffer1]{\includegraphics[width=4cm]{figures/schaffer1.png}} \qquad \subfloat[CTP 1]{{\includegraphics[width=4cm]{figures/ctp.png}}} \qquad \subfloat[Constr-Ex]{{\includegraphics[width=4cm]{figures/constrex.png}}} \qquad \subfloat[Binh and Korn]{{\includegraphics[width=4cm]{figures/binhkorn.png}}} \qquad \subfloat[Chakong and Haimes]{{\includegraphics[width=4cm]{figures/chakonghaimes.png}}} \caption{Obtained Pareto Fronts} \label{fig:pareto} \end{figure} \section{Cobb-Douglas Habitability Function} The Cobb-Douglas Habitability Function is given as follows: \begin{equation*} Y = R^\alpha.D^\beta.V_e^\delta.T_s^\gamma \end{equation*} It can also be formulated as a bi-objective optimization problem for easy visualization and understanding. The Cobb-Douglas Habitability Score ($Y$) is divided into two components, CDHS-interior ($Y_i$) and CDHS-surface ($Y_s$). The CDHS is estimated by maximizing both $Y_i$ and $Y_s$ which are defined as follows: \begin{equation*} Y_i = R^\alpha.D^\beta \end{equation*} \begin{equation*} Y_s = V_e^\delta.T_s^\gamma \end{equation*} These functions are subject to the constraints: \begin{equation*} \alpha + \beta \leq 1 \end{equation*} \begin{equation*} \delta + \gamma \leq 1 \end{equation*} \begin{equation*} 0 < \alpha , \beta , \delta , \gamma < 1 \end{equation*} Where $\alpha,\beta,\gamma,\delta$ are the \textit{elasticities} of the planetary parameters Radius, Density, Escape Velocity and Mean Surface Temperature. The quality of this model is well noted.\cite{saha2018theoretical} Thus we have a bi-objective optimization problem where we have to optimize $CDHS_i$ and $CDHS_s$ simultaneously. \begin{equation*} max f(\vec{x}) = [Y_i,Y_s] \end{equation*} However, since $V_e = \sqrt{\dfrac{2GM}{R}}$, we know that increasing surface score is not possible without compromising on interior score and vice versa. Thus, as shown in \cite{bora2016cd}, we use the following relationships: $$V_e = \dfrac{\delta}{\alpha}\dfrac{W_R}{W_{V_e}}R $$ Where $W_R$ and $W_{V_e}$ are weights of $R$ and $V_e$ respectively. Rearranging the equation we get: $$ \delta = \alpha \dfrac{V_e}{R} C$$ where, $$ C = \dfrac{W_{V_e}}{W_R} $$ In order to bring out the trade-off between the two components of the Cobb-Douglas Habitability Score, we calculate $\delta$ from the other parameters, optimizing the variables $\alpha,\beta,\gamma$ and $C$. We apply the aforementioned proto-genetic algorithm modified with NSGA-II on a set of planets from the exoplanet catalog hosted by the Planetary Habitability Laboratory at the University Of Puerto Rico, the TRAPPIST system. The results are shown in Table 3 with illustrations in Figure 9. \section{Results} After testing on multiple exoplanets in the catalog, we found promising results similar to that of past approaches\cite{saha2018theoretical}. \begin{table}[htbp] \caption{Comparison of CDHS using GA with past approaches} \begin{center} \begin{tabular}{|l|c|c|} \hline \cline{2-3} \textbf{Exoplanets} & \textbf{CDHS(2018)}& \textbf{CDHS(GA)} \\ \hline TRAPPIST-1 b & 1.0410 & 1.3753 \\ \hline TRAPPIST-1 c & 1.1589 & 1.2073 \\ \hline TRAPPIST-1 d & 0.8870 & 1.0146 \\ \hline TRAPPIST-1 e & 0.9093 & 0.9990 \\ \hline TRAPPIST-1 f & 0.9826 & 1.0389 \\ \hline TRAPPIST-1 h & 0.8025 & 0.9973 \\ \hline Proxima Cen b & 1.08297 & 1.11909 \\ \hline \multicolumn{3}{l}{$^{\mathrm{}}$} \end{tabular} \label{tab3} \end{center} \end{table} \begin{figure}[ht] \centering \subfloat[TRAPPIST-b]{\includegraphics[width=4cm]{figures/cdhsTRAPPISTb.png}} \qquad \subfloat[TRAPPIST-c]{\includegraphics[width=4cm]{figures/cdhsTRAPPISTc.png}} \qquad \subfloat[TRAPPIST-d]{{\includegraphics[width=4cm]{figures/cdhsTRAPPISTd.png}}} \qquad \subfloat[TRAPPIST-e]{{\includegraphics[width=4cm]{figures/cdhsTRAPPISTe.png}}} \qquad \subfloat[TRAPPIST-f]{{\includegraphics[width=4cm]{figures/cdhsTRAPPISTf.png}}} \qquad \subfloat[TRAPPIST-h]{{\includegraphics[width=4cm]{figures/cdhsTRAPPISTh.png}}} \caption{The TRAPPIST system of exoplanets} \label{fig:trappist} \end{figure} The Pareto fronts also show a trend where increase in one score is compensated for by decrease in the other. These complementary scores bring out the trade-off between $Y_i$ and $Y_s$. The final score is calculated as the weighted linear combination of interior and surface score where the weights sum up to 1. \begin{equation*} Y = w_i.Y_i + w_s.Y_s \end{equation*} \begin{equation*} w_i + w_s = 1 \end{equation*} We set the weights $w_i$ and $w_s$ as 0.5 i.e. equal weights. Thus the calculated CDHS is the mean of the surface score and the interior score. With different weight pairs we get a range of habitability scores for each planet instead of a hard score, making the model more robust than other metrics. In order to ensure the results are consistent, the CD-HPF was also solved as a single objective optimization problem i.e. its original form: \begin{equation*} Y = R^\alpha.D^\beta.V_e^\delta.T_s^\gamma \end{equation*} Similar to other single-objective optimization problems, we generated populations of $\alpha, \beta, \gamma$ and $\delta$ and evolved them with the proto-genetic algorithm. The results were similar and establish the veracity of the multi-objective optimization approach as listed in Table 4. \begin{table}[htbp] \caption{CDHS obtained using Multi-Objective and Single Objective Optimization} \begin{center} \begin{tabular}{|l|c|c|} \hline \cline{2-3} \textbf{Exoplanets} & \textbf{CDHS(Multi-Objective)}& \textbf{CDHS(Single Objective)} \\ \hline TRAPPIST-1 b & 1.3753 & 1.3684 \\ \hline TRAPPIST-1 c & 1.2073 & 1.2065\\ \hline TRAPPIST-1 d & 1.0146 & 1.0138\\ \hline TRAPPIST-1 e & 0.9990 & 0.9972\\ \hline TRAPPIST-1 f & 1.0389 & 1.0343\\ \hline TRAPPIST-1 h & 0.9973 & 0.9929\\ \hline Proxima Cen b & 1.11909 & 1.1158\\ \hline \multicolumn{3}{l}{$^{\mathrm{}}$} \end{tabular} \label{tab4} \end{center} \end{table} \section{Conclusion} In this paper, we have used a Proto-Genetic algorithm along with NSGA-II to calculate the best habitability scores for different exoplanets using the Cobb-Douglas Habitability Production Function. The optimizing capability of the proto-genetic algorithm was well established by testing on numerous benchmark functions of the single objective, constrained single-objective and multi-objective optimization types. Finally the algorithm was applied in calculating the habitability scores of promising exoplanets from the TRAPPIST system. The results were further verified using the single-objective optimization approach as well, establishing the merit of a genetic bi-objective optimization approach to habitability scores. \section*{Acknowledgment} We thank our teachers who gave us this opportunity to work on something innovative and provided us a rich learning experience in the process. We thank Dr. Snehanshu Saha for assistance with this endeavour and guiding us in this project. And finally, we would also like to show our gratitude to the PES University for allowing us to go beyond our coursework and work on a project with practical applications. \bibliographystyle{splncs04}
{'timestamp': '2020-10-13T02:29:59', 'yymm': '2010', 'arxiv_id': '2010.05494', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05494'}
arxiv
\section{Introduction}\label{sec:introduction}} \section{Introduction} \label{sec:introduction} \IEEEPARstart{A}{n} exceptional aspect of human intelligence is its ability to leverage prior experiences to solve problems in a new domain with limited experience. A similar ability to learn efficiently under limited available data and computational resources is also a desirable attribute of artificial intelligent (AI) agents. Over the last decade, deep neural networks (DNNs) have revolutionized a variety of application domains, such as computer vision, speech recognition, and robotic control. However, data scarcity is still a limiting factor in training DNNs for various applications, such as healthcare and cognitive modeling of human decisions \cite{hassantabar2020coviddeep, hassantabar2021mhdeep, bourgin2019cognitive}. Many such applications offer just a few thousand data instances for training. Training of DNN models with such small datasets may lead to overfitting, hence limit their applicability to real-world environments. Some of the drawbacks of the current DNN training process are as follows: \begin{itemize} \item \emph{Need to obtain and label large datasets}: Collecting a large number of data instances and manually labeling them is costly and time-consuming, even more so in domains where experts are needed to label the data instances. As a result, reducing the cost of labeling is an active area of research \cite{enayati2021visualization}. \item \emph{Ignoring domain knowledge}: Training DNN architectures only on available training data does not take into account available expert domain knowledge or the set of rules that may have been derived for the domain. As a result, the process is not efficient and, in turn, exacerbates the need for large datasets. \item \emph{Substantial redundancy}: Most DNN architectures need substantial storage, memory bandwidth, and computational resources for training. However, recent work shows that it is possible to significantly reduce the number of parameters and floating-point operations (FLOPs), with no loss in accuracy ~\cite{han2015learning, dai2019nest}. \end{itemize}{} There has been a recent spurt of interest in combining domain-specific information in the form of rule-based AI with modern statistical AI~\cite{richardson2006markov, serafini2016logic}. In such works, rule-based AI can act as an inductive bias to enhance the learning efficacy of novel tasks. Imposing prior knowledge mitigates the need for a large amount of training data. However, extracting domain knowledge or creating a set of rules for a novel domain is often challenging as it requires specific expertise in the area. Nevertheless, domains, such as natural language processing, often have pre-defined rules that make such a combination attractive \cite{balestriero2017neural}. Researchers have also explored various synthetic data generation methods to address a number of problems, such as preserving privacy when sharing data, testing new tools, and increasing dataset size. Generative models, such as variational auto-encoders \cite{pu2016variational} and generative adversarial networks (GANs) \cite{goodfellow2014generative}, provide an appealing solution for generating well-performing synthetic data. Using image and text data, these models learn the probability distribution of training data. Recently, GANs have also been used in the generation of tabular synthetic data \cite{park2018data}. They have been shown to generate synthetic data that are close to the real data distribution. However, the use of neural network models with a large number of parameters in the generator and discriminator components of GANs necessitates large training datasets to generate high-quality synthetic data. In this work, we assume we have access to only a limited number of data instances in order to synthesize accurate models that generalize well. As a result, we aim to develop a synthetic data generation module that is sample-efficient and maximizes the use of the small available data. To address the above problems, we propose a new DNN training and synthesis framework called TUTOR, which is particularly suitable for tasks where limited training data and computational resources are available. It relies on the generation of synthetic data from the same probability distribution as the available training data, to enable the DNN to start its training from a better initialization point. TUTOR consists of three sequential stages: (1) synthetic data generation, verification, and labeling, (2) training schemes for incorporating synthetic and real data into the training process, and (3) grow-and-prune DNN synthesis to ensure model compactness as well as to enhance performance. Data augmentation is an effective technique, often used in image classification applications, to increase dataset size, help the model learn invariance, and regularize the model \cite{lingchen2020uniformaugment}. However, TUTOR targets tabular datasets. It generates synthetic data by modeling the joint multivariate distribution of the given dataset and sampling from the learned distribution. The synthetic data generation module simultaneously generates categorical and continuous features. To ensure the semantic integrity of synthetic data, TUTOR uses a semantic integrity classifier module that verifies the validity of the generated synthetic data. This classifier verifies the values of categorical features with respect to other features of the synthetic data instance. We label the synthetic data by incorporating a set of rules extracted from real data. These rules are obtained using a random forest model trained on real data. Finally, TUTOR uses the synthetic data alongside the real data in two training schemes. The intuition behind using synthetic data in DNN training is to provide a suitable inductive bias to the DNN weights. It thus mitigates the problem of limited data availability. To address the problem of network redundancy, we use the grow-and-prune synthesis paradigm \cite{dai2019nest} by leveraging three different operations: connection growth, neuron growth, and connection pruning. It allows the DNN architecture to grow neurons and connections to adapt to the prediction problem at hand. Subsequently, it prunes away the neurons and connections of little importance. In addition, it does not fix the number of layers in the architecture beforehand, enabling the architecture to be learned during the training process. The major contributions of this article are as follows: \begin{itemize} \item TUTOR addresses two challenges in the design of predictive DNN models: lack of sufficient data and computational resources. It focuses on tabular datasets and addresses the lack of sufficient data by generating synthetic data from the same probability distribution as the training data using three different density estimation methods. It uses semantic integrity classifiers to verify the integrity of the generated synthetic data. By relying on decision rules generated from a random forest machine learning model, it obviates the need for domain experts to label the synthetic data. \item TUTOR uses a training flow to combine synthetic and real data to train the DNN models and learn both the weights and the architecture by using a grow-and-prune synthesis paradigm. This addresses the problem of fixed network capacity while reducing memory and computational costs. \item Less data: TUTOR requires $5.9\times$ fewer data instances to match or exceed the classification accuracy of conventional fully-connected (FC) DNNs. \item Efficiency: TUTOR uses $4.7 \times$ fewer parameters and 4.3$\times$ fewer FLOPs relative to FC DNNs. \item Accuracy: TUTOR enhances classification accuracy by $3.4\%$ over conventional FC DNNs. \item Privacy enhancement: The synthetic data generated by TUTOR can be separately used to train a DNN, with little to no drop in accuracy, without the need for real data. This is useful in applications where privacy issues make sharing of real data infeasible. \end{itemize} The rest of the article is organized as follows. Section \ref{sect:related} covers related work. Section \ref{sect:background} provides some necessary background and the theoretical motivation behind this work. Then, in Section \ref{sect:methodology}, we discuss the proposed TUTOR framework in detail. Section \ref{sect:results} presents evaluation results for TUTOR. In Section \ref{sect:discussion}, we provide a short discussion on analogies between the human brain and the TUTOR training flow. Finally, Section \ref{sect:conclusion} concludes the paper. \section{Related Work} \label{sect:related} In this section, we review several related works along four different dimensions. First, we discuss how logical AI can be combined with data-driven statistical AI. Second, we review work that combines decision trees with DNNs. Third, we discuss some of the recent work in efficient DNN synthesis. Finally, we discuss various data augmentation and synthetic data generation methods. \subsection{Combining Logical AI with Statistical AI} Recently, there have been several attempts to combine propositional and first-order logic (FOL) with the statistical techniques of machine learning. For instance, Markov logic network (MLN) \cite{richardson2006markov} is based on probabilistic logic that combines Markov networks with FOL. The first-order knowledge base (KB) is viewed as imposing a set of hard constraints, where violation of a formula reduces the probability of the targeted application world to zero. An MLN softens these constraints by associating a weight with each FOL formula in the KB. These weights are proportional to the probability of the FOL formula being true. The incorporation of FOL enables reasoning about pre-existing domain knowledge. As a result, the Markov networks model uncertainty in reasoning. However, the main drawback of an MLN is the need for domain expertise to obtain the formulas, thereby limiting its usage. The logic tensor network (LTN) \cite{serafini2016logic} uses fuzzy logic to combine DNNs with FOL. Logical predicates represent concepts that are combined to form logical formulas. Fuzzy logic enables a formula to be partially true and take a value between 0 and 1. In LTN, a DNN learns the membership of an object in a concept. Each concept or formula is a point in a feature space and the DNN outputs a number between 0 and 1 to denote the degree of membership. \subsection{Combining Decision Trees with DNNs} There are several works that combine DNNs with decision trees. Neural-backed decision trees (NBDTs) \cite{wan2020nbdt} combine decision trees with a DNN to enhance DNN explainability. NBDTs achieve performance close to that of the DNN while improving explainability. A neural decision tree \cite{balestriero2017neural} incorporates a nonlinear splitting criterion in its nodes by using a DNN to make the splitting decision. Deep neural decision forests \cite{kontschieder2015deep} present an end-to-end learning framework based on convolutional neural networks (CNNs) and a stochastic differentiable decision tree for image classification applications. This approach uses back-propagation to learn the parameter to split at a node. Deep neural decision trees \cite{yang2018deep} use a soft binning function modeled by a DNN to split nodes into multiple leaves. Initializing the weights of a DNN from a good starting point can also be used to improve its performance. Humbird et al. \cite{humbird2018deep} use a decision tree model to construct the architecture and initialize the weights of the DNN. The DNN architecture is obtained using the decision paths of a decision tree. The tree acts as a warm-start for the training process. \subsection{Efficient DNN Synthesis} To reduce the need for data, a popular approach involves the use of transfer learning \cite{oquab2014learning} to transfer weights learned for one task to initialize weights of a network for a similar task. This approach is based on the fact that some of the learned features are similar across related tasks. A common approach for reducing computational cost is the use of efficient building blocks. For example, MobileNetV$2$ \cite{sandler2018mobilenetv2} uses inverted residual blocks to reduce model size and FLOPs. ShuffleNet-v$2$ \cite{ma2018shufflenet} uses depth-wise separable convolutions and channel-shuffling operations to ensure model compactness. Spatial convolution is one of the most expensive operations in CNN architectures. To reduce its computational cost, Shift \cite{wu2018shift} uses shift-based modules that combine shifts and point-wise convolutions that significantly reduce computational cost and storage needs. FBNet-v$2$ uses differentiable neural architecture search to automatically generate compact architectures. Efficient performance predictors, e.g., for accuracy, latency, and energy, are also used to accelerate the DNN search process \cite{dai2018chamnet, hassantabar2019steerage}. DNN compression methods can be used to remove redundancy in DNN models. Han et al.~\cite{han2015deep} proposed a pruning methodology to remove redundancy from large CNN architectures, such as AlexNet and VGG. Pruning methods are also effective on recurrent neural networks \cite{han2017ese}. Combining network growth with pruning enables a sparser, yet more accurate, architecture. Dai et al.~\cite{dai2019nest, dai2018grow} use the grow-and-prune synthesis paradigm to generate efficient CNNs and long short-term memories (LSTMs). SCANN \cite{hassantabar2019scann} uses feature dimensionality reduction alongside grow-and-prune synthesis to generate very compact models for deployment on edge devices and Internet-of-Things (IoT) sensors. Orthogonal to the above works, low-bit quantization of DNN weights can also be used to reduce FLOPs. A ternary weight representation is used in \cite{zhu2016trained} to significantly reduce computation and memory costs of ResNet-$56$, with a limited reduction in accuracy. \subsection{Data Augmentation and Synthetic Data Generation} Learning with sparse data is challenging as machine learning algorithms, especially DNNs, face the overfitting problem in a small-data regime. To overcome this problem, several techniques have been developed to augment the dataset. Data augmentation for images enhances the accuracy of image classification and reinforcement learning tasks. AutoAugment \cite{cubuk2018autoaugment} uses reinforcement learning to obtain a policy for optimal image transformation to improve performance on various computer vision tasks. The optimal transformation is dependent on the dataset. UniformAugment \cite{lingchen2020uniformaugment} augments images by uniformly sampling from the continuous space of augmentation transformations, hence, avoiding the costly search process for finding augmentation policies. Laskin et al. \cite{laskin2020reinforcement} use two new augmentation schemes based on random translation and random amplitude scaling alongside standard augmentation techniques (crop, cutout, flip, rotate, etc.). They use these augmentation schemes to achieve a state-of-the-art performance for reinforcement learning tasks. Antoniou et al. \cite{antoniou2017data} use GANs to augment the images for few-shot learning in the low-data regime tasks. Privacy is an important concern when sharing data with partners or releasing data to the public. As a result, researchers have investigated techniques to generate synthetic data with performance similar to that of real data. TableGAN \cite{park2018data} is a GAN-based approach for creating synthetic tabular data. It uses a GAN architecture with three components: generator, discriminator, and a classifier that learns correlations between the labels and other attributes of the table. Synthetic data generated by TableGAN is shown to achieve high model capacity while offering protection against membership attacks. TGAN \cite{xu2018synthesizing} generates tabular data based on GANs and uses an LSTM with attention mechanisms to generate the synthetic data column by column. CTGAN \cite{xu2019modeling} improves tabular synthetic data generation by introducing conditional vectors for categorical features and training by sampling the different conditional vectors. \section{Background} \label{sect:background} In this section, we discuss background material that motivates the TUTOR framework. First, we discuss different probability density estimation methods. We use such methods in the TUTOR synthetic data generation module. Next, we discuss the Hierarchical Bayes and Empirical Bayes concepts. We also discuss linking of gradient-based learning with hierarchical Bayes. These methods motivate our training schemes (explained in Section \ref{sect:schemes}) in the way we combine synthetic and real data to learn the DNN model parameters. \subsection{Probability Density Estimation} \label{sect:PDE} The probability density function (pdf) is a fundamental concept in statistics. It is used to compute various probabilities associated with a random variable. Probability density estimation deals with estimating the density of function $f$ with $\hat{f}$, given random samples $x_1, \dots, x_n \stackrel{}{\sim} f$. Predominantly, probability density estimation can be categorized into two groups: parametric and non-parametric. In parametric density estimation, pdf $f$ is assumed to be a member of a parametric family. Hence, density estimation is transformed into finding estimates of the various parameters of the parametric family. For example, in the case of a normal distribution, density estimation aims to find the mean $\mu$ and standard deviation $\sigma$. In general, the classic parametric mixture of $C$ Gaussian models has a pdf of the form: $$ p(x_{i}|\Theta) = \Sigma_{c=1}^{C} p(x_{i}|z_{i}=c, \Theta) p(z_{i}=c|\Theta) $$ where each component $c$ is a $d$-dimensional multivariate Gaussian distribution with mean vector ${\mu}_{c}$ and covariance matrix $\Sigma_{c}$ in the form of: \begin{equation*} \begin{split} p(x_{i}|z_{i}=c, \Theta) = \left(\frac{1}{2\pi}\right)^{(d/2)} |\Sigma_{c}|^{-1/2} \\ \text{exp} \left( -\frac{1}{2} (x_{i}-\mu_{c})^{T} \Sigma_{c}^{-1} (x_{i}-\mu_{c}) \right) \end{split} \end{equation*} where $|\Sigma_{c}|$ is the determinant of the covariance matrix. In addition, the mixture probabilities are modeled as categorical: $$ p(z_{i} = c|\Theta) = \theta_{c} $$ A non-parametric density estimation scheme can generate any possible pdf. It does not make any distributional assumptions and covers a broad class of functions. Kernel density estimation is a non-parametric density estimation approach that approximates a probability distribution as a sum of many \emph{kernel} functions. Each kernel function $K$ satisfies the following property: $$ \int_{-\infty}^{\infty} K(y) dy = 1 \quad , \quad K(y) > 0 \quad \forall {y} $$ There may be various options for choosing function $K$, such as the pdf of the normal distribution. Another important parameter is the kernel \emph{bandwidth}, $h$, that rescales the kernel function. Kernel density estimation can be formulated as: $$ \hat{f}(y) = \frac{1}{nh} \sum_{i=1}^{n} K(\frac{y-x_{i}}{h}) $$ where $n$ is the number of samples and $x_i$ is the $i^{th}$ sample. \subsection{Hierarchical Bayes and Empirical Bayes} \label{sect:bayes} Creating sub-models can be a way to model the distribution of data with a hierarchical structure. Each sub-model has its own parameters that are interlinked to model the complete distribution. Hierarchical Bayes models the data distribution at a prior level by using Bayes inference that links the parameters and propagates uncertainties among the sub-models. It uses the Bayesian network assumption: variables are conditionally independent of their non-descendants, given their parents. The equation below shows hierarchical Bayes modeling of the distribution of data $X$ \cite{malinverno2004expanded}. $$ X \longrightarrow \theta \longrightarrow \theta_{1} \longrightarrow \theta_{2} \longrightarrow \ldots \longrightarrow \theta_{t} $$ \noindent where $\theta$ is the parameter and $\theta_{1}, \theta_{2}, \ldots , \theta_{t}$ are the hyperparameters. Based on the Bayes assumption, using only the following conditionals specifies the complete model: $[X|\theta]$, $[\theta|\theta_{1}]$, $[\theta_{1}|\theta_{2}]$, $\ldots$, $[\theta_{t-1}|\theta_{t}]$. \noindent By exploiting the inherent structure of the distribution, hierarchical modeling reduces the number of parameters needed in its modeling. Hence, it is less prone to overfitting. Empirical Bayes \cite{malinverno2004expanded} is similar to Hierarchical Bayes. However, Empirical Bayes determines the hyperparameters by using the data instead of the hyper-prior distribution. The two training schemes of TUTOR (explained in Section \ref{sect:schemes}) model DNN parameter learning with Hierarchical Bayes. In addition, similar to Empirical Bayes, TUTOR estimates the hyperparameters by using the available data. In this process, it first uses probability density estimation to estimate the distribution of the training dataset. It uses the sum of the log-probabilities of the data instances in the validation set to determine the hyperparameter $\lambda$ of the probability density estimation function. It generates synthetic data by sampling from this function. In the training schemes, it learns parameters $\theta$ of the DNN model by using the synthetic data to pre-train the weights of the model. Therefore, we can obtain a Hierarchical Bayes model of the parameters as follows: $$ X \longrightarrow \lambda \longrightarrow \theta $$ \noindent The posterior distribution can be written as: $$p(\lambda, \theta \mid X) \propto p(X \mid \theta, \lambda) p(\theta \mid \lambda) p(\lambda)$$ \noindent where $X$ denotes the combined training and validation set, $\theta$ the parameter of the model after training with synthetic data, and $\lambda$ the hyperparameter of the probability density estimation function. \subsection{Linking Gradient-based Learning with Synthetic Data and Hierarchical Bayes} \label{sect:gradient+bayes} Gradient-based learning combined with a Bayesian network enables the transfer of knowledge across various domains in a sample-efficient manner. Model-agnostic meta-learning (MAML) \cite{finn2017modelagnostic} trains a model across a variety of tasks and fine-tunes it using gradient descent on a new learning task. As a result, MAML uses other related tasks to initialize DNN weights instead of using random initialization. Grant et al. \cite{grant2018recasting} cast MAML as Empirical Bayes using a hierarchical probabilistic model. It learns a prior that is adapted to new tasks to augment gradient-based meta-learning. Learning on one task influences the parameters of another task through a meta-level parameter that determines the task-specific parameters. In a similar fashion to MAML, TUTOR generates synthetic data and uses them to learn parameters $\theta$ of the model. Then, it learns parameters $\phi$ of the DNN from the initialization with $\theta$, followed by gradient descent using real training data. \section{Synthesis Methodology} \label{sect:methodology} In this section, we discuss the TUTOR DNN synthesis framework in detail. First, we give a high-level overview of its DNN training methodology. We then zoom into each part of the methodology. First, we explain the three synthetic data generation methods, the semantic integrity classifier module, and the synthetic data labeling method. Next, we focus on the two training schemes that combine the real and synthetic data in the training process. We then explain our grow-and-prune synthesis algorithm. Finally, we discuss the use of synthetic data alone as a proxy for real data to train DNNs, with a little to no loss in accuracy, for the sake of privacy enhancement. \subsection{Framework Overview} We illustrate the proposed TUTOR framework in Fig.~\ref{fig:diagram}. It consists of three main parts: (1) synthetic data generation, verification, and labeling with decision rules, (2) two training schemes that combine synthetic data with real data, and (3) grow-and-prune synthesis to decrease network redundancy and computational cost for inference while improving performance. The synthetic data generation module uses the training and validation sets as inputs to generate synthetic data instances. It targets both continuous and categorical features of the tabular data. We formulate this step as an optimization problem. The objective is to find the best set of hyperparameters ($\lambda$) of the probability density estimation function computed on the training data ($\hat{f}(X_{train}|\lambda)$). To this end, we use the sum of the log probabilities of instances in the validation set ($\texttt{score}(X_{validation})$) as a measure for comparing different functions. We sample a pre-defined number of instances ($count$) from the density estimation function $\hat{f}$ with an optimal set of hyperparameters $\lambda^{*}$ to generate synthetic data: $$ \lambda^{*} = \underset{\lambda}{\arg\max} \left( \hat{f}(X_{train}|\lambda).\texttt{score}(X_{validation}) \right) $$ $$ X_{syn} = \hat{f}(X_{train}|\lambda^{*}).\texttt{sample}(count) $$ To synthesize the correct values for categorical features, we treat them differently from the continuous features, using the one-hot encoding technique. To ensure the validity of the categorical features relative to other data features, we use several semantic integrity classifiers to verify the generated synthetic data. Section~\ref{sect:syn-data} explains the process of synthetic data generation and verification. To label the synthetic dataset, we use decision rules to obviate the need for the expensive and laborious process of labeling by an expert. To do so, we use a random forest model trained on data used as a KB. Section~\ref{sect:labeling} explains this process. In the two training schemes, A and B, TUTOR uses synthetic data alongside the original training and validation data. As explained in Section \ref{sect:gradient+bayes}, these schemes learn the DNN weights by combining gradient-based learning with Hierarchical Bayes modeling. TUTOR uses synthetic data to learn parameters $\theta$ of the DNN model that enable better initialization for the next training step. Then, it learns parameters $\phi$ of the DNN by performing gradient-descent training with real training data, starting from initialization point $\theta$. Section~\ref{sect:schemes} explains these two training schemes. Finally, we perform grow-and-prune synthesis \cite{dai2019nest, hassantabar2019scann} on the FC DNN models that are the outputs of Schemes A and B. This step uses gradient-based learning to obtain both the final architecture and the final DNN parameters. Grow-and-prune synthesis uses three different architecture-changing operations that are explained in Section~\ref{sect:gp}. \begin{figure*}[!hbt] \centering \includegraphics[scale=0.5]{Tutor-schematic.pdf} \caption{Block diagram of the TUTOR DNN synthesis framework: (1) synthetic data generation, verification, and labeling, (2) two training schemes, and (3) grow-and-prune synthesis.} \label{fig:diagram} \end{figure*} \subsection{Synthetic Data Generation} \label{sect:syn-data} In this section, we discuss how TUTOR models tabular data distribution and sampled rows from the distribution to generate synthetic data. Tabular data $X$ contains $N$ continuous features and $M$ categorical features. Each feature is assumed to be a random variable. The goal is to model the joint distribution of all the features, given the observations provided by real data instances. To tackle this problem, TUTOR uses both parametric and non-parametric density estimation methods. To deal with categorical data columns in the table, it uses one-hot encoding to model the value of each categorical feature for each data instance. It also verifies the values of these categorical features relative to other synthetic data features. These values should be semantically correct. For example, if a continuous feature representing blood glucose level has a value of 120 mg/dL, a categorical feature showing whether or not the subject has diabetes cannot have a value of 1 for the following reason: the blood glucose level is too low for the subject to be diabetic. We introduce a module called the semantic integrity classifier that verifies that the generated synthetic data are semantically correct. We then use supervised machine learning models to label verified synthetic data. \subsubsection{Encoding the categorical features} We use the one-hot encoding to encode categorical data. Hence, for categorical feature $F$ with $k$ different values, we use $k$ columns to represent feature $F$, with $1$ in the column corresponding to its value and 0 in the other columns. In addition, after generating synthetic data, we use the $softmax$ operator on the synthetic values corresponding to $k$ possible different values of the feature to specify the value of that feature for the synthetic data instance. Note that categorical features with a very high cardinality in the presence of a low number of data instances may lead to incorrect values for these features in the synthetic data. Hence, using a semantic integrity classifier to check for the validity of these values is important. We explain this part in more detail in Section~\ref{sect:semantic-classifier}. \subsubsection{Probability density estimation} In this section, we discuss the three probability density estimation methods we use to model the distribution of tabular data. The first approach involves the use of multivariate normal distribution to estimate the probability distribution of training data. This is an example of parametric density estimation. We also use an approach based on kernel density the estimation that resides on the other side of the spectrum, being a non-parametric density estimation approach. Finally, we use Gaussian mixture models (GMMs) to estimate the training data distribution. The GMM approach can be considered to effect a trade-off between the other two approaches. It is based on the sum of a limited number of multivariate normal distributions. \noindent \textbf{Multivariate normal distribution (MND):} Next, we discuss modeling data with a multivariate normal distribution. The parameters of this distribution are computed based on the training data. The sample mean vector $\hat{\mu}$ can be estimated as: $$ \hat{\mu} = \frac{1}{N} \sum_{i=1}^{N} x_{i} $$ where $N$ is the total number of training data instances and $x_i$ is the $d$-dimensional vector that depicts the $i^{th}$ training instance. To estimate the $d \times d$ covariance matrix of the multivariate normal distribution, we use the maximum likelihood estimator of the covariance matrix: $$ \hat{\Sigma} = \frac{1}{N} \sum_{i=1}^{N} (x_{i} - \hat{\mu})(x_{i} - \hat{\mu})^{T} $$ Thus, a multivariate normal distribution with a $d$-dimensional mean vector $\hat{\mu}$ and $d \times d$ covariance matrix $\hat{\Sigma}$ estimates the density. The joint density function of a random vector $X$ based on this density function is given by: $$ {\textstyle p_{X}(x|\hat{\mu}, \hat{\Sigma}) = \left( \frac{1}{2\pi} \right) ^ {d/2} |\hat{\Sigma}|^{-1/2} \text{exp} \left( -\frac{1}{2} (x-\hat{\mu})^{T} \hat{\Sigma}^{-1} (x-\hat{\mu}) \right) } $$ \noindent where $|\hat{\Sigma}|$ is the determinant of matrix $\hat{\Sigma}$. When the number of available data points is small, we can constrain the covariance matrix to be diagonal to reduce the number of independent parameters in the model. The synthetic data are generated by sampling the following distribution: $$ X \sim \mathcal{N} (\hat{\mu}, \hat{\Sigma}) $$ \noindent \textbf{Gaussian mixture model (GMM):} \label{sect:GMM} The second approach involves the use of a multi-dimensional GMM to model the training data distribution. The data are modeled as a mixture of $C$ Gaussian models that lead to a pdf of the form: $$ p_{X}(x|\Theta) = \Sigma_{c=1}^{C} p_{X|Z}(x|z=c, \Theta) p_{Z}(z=c|\Theta) $$ where $\Theta$ depicts the parameters of the Gaussian model, $X$ the observed variables, and $Z$ the hidden state variables that indicate Gaussian model assignment, with the prior probability of each model $c$ being: $$ p_{Z}(z=c) = \theta_{c} $$ Hence, the GMM can simply be written as: $$ p_{X|C}(x)=\sum_{c=1}^{C} \mathcal{N}\left(x|\mu_{c},\Sigma_{c}\right) \pi_{c} $$ Here, ${\mu}_{c}$ represents the mean vector, $\Sigma_{c}$ the covariance matrix, and $\pi_{c}$ the weight of GMM component $c$, with a total of $C$ components. The drawback of this approach lies in its learning complexity. To address this issue, we use the iterative Expectation-Maximization ($EM$) algorithm to determine the GMM parameters. The EM algorithm solves this optimization problem in two steps: \begin{itemize} \item E-step: given the current parameters $\theta_{i}$ and observations in data $\mathcal{D}$, estimate the values of $z_{i}$. \item M-step: with the new estimate of $z_{i}$, find the new parameters, $\theta_{i+1}$. \end{itemize} In the $E$-$step$, for each training data instance $x_{i}$, the most likely cluster $z_{i}$ is obtained. In the $M$-$step$, the cluster parameters, i.e., cluster mean $\mu_{c}$ and covariance matrix $\Sigma_{c}$, are obtained from the current cluster assignments. This procedure is repeated until convergence. Several choices are available for cluster shape \textit{(diagonal, spherical, tied, full)} that can be used to control the degree of cluster freedom. The choices span the spectrum from the most general to more specific mixture models. Although the \textit{full} type generates a more general mixture model, it also increases the number of independent model parameters. Hence, with limited available data, using a more specific model may potentially improve performance by reducing the number of independent model parameters. Hence, we explore these four choices in our setup. To avoid overfitting on the training data, the likelihood of validation data is obtained by varying the number of mixtures, $C$. The sum of log probabilities of instances in the validation set is used to evaluate the quality of the model. The number of components that maximizes this criterion is chosen as the optimal number of components required to model the distribution: $$ C^{*} = \underset{C}{\arg\max} \left( p_{X|C}(x).\texttt{score}(X_{validation}) \right) $$ The GMM parameters thus obtained are then used to generate synthetic data by sampling a pre-defined number of instances ($count$) from this distribution. $$ X_{syn} = p_{X|C^{*}}(x).\texttt{sample}(count) $$ \noindent \textbf{Kernel density estimation (KDE):} \label{sect:kde} As opposed to the parametric mixture models, non-parametric mixture models assign one component to every training example. In general, this can be formulated as: $$ p(x|\Theta) = \sum_{i=1}^{N} p_{Z}(z_{i}=c|\Theta)p_{X|Z}(x|z=c, \Theta) $$ In our setup, we use the pdf of the normal distribution as the kernel function. An important hyperparameter of the KDE model is kernel bandwidth $h$ that controls the smoothness of the estimated function. The bandwidth has a large impact on the bias-variance trade-off of the estimator. Essentially, high-variance models estimate the training data well, but suffer from overfitting on the noisy training data. On the other hand, high-bias estimators are simpler models, but suffer from underfitting on the training data and fail to capture important regularities. In the KDE models, small bias is achieved when $h \rightarrow 0$ and small variance when $h \rightarrow \infty$. Therefore, the choice of the $h$ value directly impacts function performance on unseen data. Hence, as in the case of finding the optimal number of components in a GMM model, we use a validation set to find the optimal bandwidth value $h^{*}$. We use the sum of log probabilities of the instances in the validation set to evaluate the KDE probability estimator: $$ h^{*} = \underset{h}{\arg\max} \left( p_{X|h}(x).\texttt{score}(X_{validation}) \right) $$ After obtaining all the parameters of the KDE estimator, we sample a pre-defined number of instances ($count$) from this distribution to generate the synthetic data: $$ X_{syn} = p_{X|h^{*}}(x).\texttt{sample}(count) $$ \subsubsection{Semantic integrity classifier} \label{sect:semantic-classifier} To ensure the quality of the synthetic data, and verify the semantic integrity of the categorical feature values, we utilize the semantic integrity classifier module. Given a synthetic record, the task of the semantic integrity classifier is to predict the values of the categorical features based on the values of other continuous features in that data instance. We train a semantic integrity classifier for each categorical feature. Algorithm~\ref{alg:semanctic-integrity} summarizes the semantic integrity verification process for one categorical feature. In the case of a mismatch between the value predicted by the semantic integrity classifier and the value of the categorical feature in the synthetic data, we discard the data instance. The classifier model can be chosen from among many options. In our implementation, we use random forest models to implement the semantic integrity classifiers. We use validation accuracy to optimize the hyperparameters of the model. \begin{algorithm}[h] \caption{Semantic integrity classifier} \label{alg:semanctic-integrity} \begin{algorithmic}[l] \REQUIRE \textit{($X$)}: Training data; \textit{($X_{syn}$)}: generated synthetic data; \textit{$F_{cont}$}: the set of continuous features; \textit{$F_{cat}$}: the categorical feature; \textit{$CLF$}: classifier model \STATE Train \textit{$CLF$} on $(X[:, F_{cont}] , X[:, F_{cat}])$ \FOR{\textit{$x_{syn}$} in \textit{$X_{syn}$} } \STATE $Predicted$ = $CLF$ ($x_{syn} [F_{cont}] $) \IF{$predicted$ != $x_{syn} [cat] $} \STATE discard $x_{syn}$ from $X_{syn}$ \ENDIF \ENDFOR \ENSURE Verified $X_{syn}$ \end{algorithmic} \end{algorithm} \subsection{Labeling the Synthetic Data} \label{sect:labeling} In the case of supervised machine learning, domain experts are generally asked to label the data. However, this process can be very expensive and time-consuming. Furthermore, in many settings, researchers may not have access to domain experts. Instead, we use decision rules extracted from a random forest model trained on real training data. In a decision tree, each path starting from the root and ending at a leaf can be considered a \emph{rule}. Hence, as shown in Fig.~\ref{fig:diagram}, we investigate labeling of synthetic data with rules derived from the random forest model that performs the best on the validation set. We evaluate various random forest models using different splitting criteria (such as Gini index and entropy) and different depth constraints on its constituent decision trees. \subsection{TUTOR Training Schemes} \label{sect:schemes} In this section, we explain how TUTOR uses labeled synthetic data to obtain a prior on the DNN weights. We introduce two schemes, termed Schemes A and B, to combine the synthetic and real data to train two FC DNN models. \subsubsection{Scheme A} Scheme A combines gradient-based learning with the Hierarchical Bayes approach to estimate the parameters of the model in two steps (as explained in Section \ref{sect:gradient+bayes}). Algorithm \ref{alg:scheme-a} summarizes the process of training DNN weights using synthetic and real data. Scheme A uses the data generated by the three different synthetic data generation methods to pre-train the network architecture. Pre-training is followed by use of the real training dataset to fine-tune and train network weights. Scheme A outputs the model that performs the best on the validation set. Then, we use the test set for its evaluation. \begin{algorithm}[h] \caption{Scheme A} \label{alg:scheme-a} \begin{algorithmic}[l] \REQUIRE \textit{($X$,$y$)}: Training data; \textit{Methods}: the three methods for synthetic data generation; \textit{Arch}: DNN architecture; $KB$: knowledge-base (random forest model) \FOR{\textit{method} in \textit{Methods} } \STATE $X_{\text{Syn}}$: synthetic data based on \textit{method} \STATE $y_{syn}$ = KB ($x_{syn}$) \STATE Pre-train \textit{Arch} with ($X_{\text{Syn}}$, $y_{\text{Syn}}$) \STATE Train \textit{Arch} with ($X$, $y$) \STATE $Model_{method}$ = \textit{Arch} with the learned weights \ENDFOR \STATE $Model_{A}$: best model as evaluated on the validation set \STATE $testAcc$: Evaluate $Model_{A}$ on test data \ENSURE $Model_{A}$ and $testAcc$ \end{algorithmic} \end{algorithm} \subsubsection{Scheme B} Algorithm~\ref{alg:scheme-b} summarizes Scheme B. First, we train two instances of the same DNN architecture. We train the first DNN on the training dataset. This network is responsible for learning the data. We train the second DNN on synthetic data. This network is responsible for learning the KB, i.e., the random forest model. Next, we obtain another architecture by concatenating the outputs of these two networks and adding two FC layers followed by an output layer. We then train this architecture on the training dataset and evaluate it on the validation set. The two added FC layers are responsible for learning the importance of the output from each of the two DNN components in making the final prediction. In this aspect, Scheme B takes inspiration from an MLN \cite{richardson2006markov}. An MLN associates a weight with each FOL formula in a KB to depict its relative importance. Furthermore, it uses Markov networks to model uncertainty in reasoning based on the KB. Similarly, Scheme B uses the added two FC layers to learn the relative importance of prediction based on training data and based on synthetic data that represent the KB, in the final prediction. Finally, we record the best model and evaluate it on the test set. \begin{algorithm}[h] \caption{Scheme B} \label{alg:scheme-b} \begin{algorithmic}[l] \REQUIRE \textit{($X$,$y$)}: Training data; \textit{Methods}: the three methods for synthetic data generation; \textit{Arch}: DNN architecture; $KB$: knowledge-base (random forest model) \FOR{\textit{method} in \textit{Methods} } \STATE $X_{\text{Syn}}$: synthetic data based on \textit{method} \STATE $y_{syn}$ = KB ($x_{syn}$) \STATE $Model_1$: Train \textit{Arch} on ($X_{\text{Syn}}$, $y_{\text{Syn}}$) \STATE $Model_2$: Train \textit{Arch} using ($X$,$y$) \STATE \textit{CombinedNet}: \texttt{Concat} (Output of \textit{Models} $1$ and $2$) + $2$ FC layers + an output layer \STATE fine-tune \textit{CombinedNet} on the training set \STATE Evaluate on the validation set \ENDFOR \STATE $Model_{B}$: best \textit{CombinedNet} on the validation set \STATE $testAcc$: Evaluate $Model_{B}$ on test data \ENSURE $Model_{B}$ and $testAcc$ \end{algorithmic} \end{algorithm} \subsection{Grow-and-prune Synthesis} \label{sect:gp} In this section, we discuss the grow-and-prune synthesis step. This approach, first proposed in \cite{dai2019nest, hassantabar2019scann}, allows both the architecture and weights to be learned during the training process, enhancing both model accuracy and compactness. We apply grow-and-prune synthesis to models $A$ and $B$ that are outputs of Algorithms~\ref{alg:scheme-a} and \ref{alg:scheme-b}, respectively. The approach we use allows the depth of the DNN to change during the training process. This is enabled by allowing a neuron to feed its output to any neuron activated after it. As a result, DNN depth depends on how the neurons are connected in the architecture and can be changed during the grow-and-prune synthesis process. We use three different architecture-changing operations for a predefined number of iterations (set to five in our experiments). After each change, the DNN architecture is trained for a few epochs (set to $20$ in our experiments) and its performance evaluated on the validation set. Finally, we choose the highest-performing architecture on the validation set. The three operations that are used in our grow-and-prune synthesis step are as follows: \noindent \textbf{Connection growth}: Connection growth activates the dormant connections in the network, with their weights set to $0$ initially. The two main approaches we use for connection growth are: \begin{itemize} \item \textbf{Gradient-based growth}: In this approach, we choose the added connections based on their effect on the loss function $\mathcal{L}$. Each weight matrix $W$ has a corresponding binary mask $Mask$ that has the same size. The binary mask is used to disregard the inactive connections with zero-valued weights. Algorithm \ref{alg:gradient-growth} shows the process of gradient-based growth. The goal of this process is to identify the dormant connections that are most effective in reducing the loss function value. For each mini-batch, we extract the gradients for all the weight matrices $W.grad$ and accumulate them over a training epoch. An inactive connection is activated if its gradient is above a certain percentile threshold of the gradient magnitude of its associated layer matrix. \item \textbf{Full growth}: This approach restores all the dormant connections in the network to make the DNN fully connected. \end{itemize} \begin{algorithm}[h] \caption{Connection growth algorithm} \label{alg:gradient-growth} \begin{algorithmic}[l] \REQUIRE $W \in R^{M \times N}$: weight matrix of dimension $M \times N$; $Mask \in R^{M \times N}$: weight mask of the same dimension as the weight matrix; Network $P$; $W.grad$: gradient of the weight matrix (of dimension $M \times N$); data $D$; $\alpha$: growth ratio \IF{full growth} \STATE $Mask_{[1:M, 1:N]} = 1 $ \ELSIF{gradient-based growth} \STATE {Forward propagation of data $D$ through network $P$ and then back propagation} \STATE {Accumulation of $W.grad$ for one training epoch} \STATE {$t = (\alpha \times MN)^{th}$ largest element in the $\left|W.grad\right|$ matrix} \FORALL {$w.grad_{ij}$} \IF{$\left| w.grad_{ij} \right| > t$} \STATE {$Mask_{ij} = 1$} \ENDIF \ENDFOR \ENDIF \STATE $W$ = $W \otimes Mask$ \ENSURE Modified weight matrix $W$ and mask matrix $Mask$ \end{algorithmic} \end{algorithm} \noindent \textbf{Connection pruning}: The connection pruning operation is based on the magnitude of the connection. We remove a connection $w$ if and only if its magnitude is smaller than a certain percentile threshold of the weight magnitude of its associated layer matrix. Algorithm \ref{alg:pruning} shows this process. \begin{algorithm}[h] \caption{Connection pruning algorithm} \label{alg:pruning} \begin{algorithmic}[l] \REQUIRE Weight matrix $W \in R^{M \times N}$; mask matrix $Mask$ of the same dimension as the weight matrix; $\alpha$: pruning ratio \STATE $t = (\alpha \times MN) ^{th}$ largest element in $\left|W\right|$ \FORALL {$w_{ij}$} \IF{$\left| w_{ij} \right| < t$} \STATE {$Mask_{ij} = 0$} \ENDIF \ENDFOR \STATE $W$ = $W \otimes Mask$ \ENSURE Modified weight matrix $W$ and mask matrix $Mask$ \end{algorithmic} \end{algorithm} \noindent \textbf{Neuron growth}: This step duplicates the existing neurons in the architecture, to add neurons to the network, and increases network size. Algorithm \ref{alg:neuron-growth} explains the neuron growth process. In this process, we select the neuron with the highest activation function (neuron $i$) for duplication. After adding the new neuron (neuron $j$) to the network, we use the original neuron $i$ to set the new values for mask and weight matrices. In addition, to break the symmetry, random noise is added to the weights of all the connections related to the newly added neuron. \begin{algorithm}[h] \caption{Neuron growth algorithm} \label{alg:neuron-growth} \begin{algorithmic}[l] \REQUIRE Network $P$; weight matrix $W \in R^{M \times N}$; mask matrix $Mask$ of the same dimension as the weight matrix; data $D$; candidate neuron $n_j$ to be added; array $A$ of activation values for all hidden neurons \STATE {forward propagation through $P$ using data $D$} \STATE {$i = argmax~(A)$} \STATE {$Mask_{[j, 1:N]} = Mask_{[i, 1:N]}$} \STATE {$Mask_{[1:M,j]} = Mask_{[1:M,i]}$} \STATE {$W_{[j,1:N]} = W_{[i,1:N]} + noise$} \STATE {$W_{[1:M,j]} = W_{[1:M,i]} + noise$} \ENSURE Modified weight matrix $W$ and mask matrix $Mask$ \end{algorithmic} \end{algorithm} We apply connection pruning after neuron growth and connection growth in each iteration. We apply these three operations for a pre-defined number of iterations. Finally, we select the best-performing architecture on the validation set. \subsection{TUTOR Application: Using Synthetic Data Alone} It is common to assume that a trusted curator gathers a dataset with sensitive information from a large number of individuals. Such a dataset can be used to train predictive machine learning models for specific tasks in a related domain. A dataset can contain \emph{micro-data}, revealing information about individuals from whom the data are collected. For example, many healthcare datasets contain legally protected information, such as health histories of patients. Hence, there is a privacy risk in publishing or sharing such datasets. Narayanan et al.~\cite{narayanan2008robust} have shown that an adversary with a small amount of background knowledge about an individual can use it to identify the individual's record in an anonymized dataset, with a high probability. This means that the adversary can learn private information about the individual. In addition, a study \cite{sweeney2000simple} shows that using $1990$ U.S. Census summary data, with a high probability, $87\%$ of the U.S. population can be identified with only three features: ZIP Code, gender, and date of birth. As a result, the free flow of data between various organizations risks privacy loss. However, data sharing is necessary for building predictive machine learning models. To address this issue, we could share synthetic data, drawn from the same distribution as the real data, with the other parties \cite{surendra2017review}. The synthetic data generation module in TUTOR can be used to generate such a dataset. Furthermore, the dataset can be labeled using the most accurate DNN model (on the validation set) synthesized by the TUTOR framework. In Section~\ref{sect:data-privacy}, we show that DNN models trained on the synthetic dataset incur little to no drop in accuracy compared to DNNs trained on real data. \section{Experimental Results} \label{sect:results} In this section, we evaluate the performance of the TUTOR synthesis methodology on nine datasets. Table \ref{tab:characteristics} shows their characteristics. These datasets are publicly available from the UCI machine learning repository \cite{ucidb}, Kaggle classification datasets \cite{ptbdb, mitbih, covertype}, and Statlog collection \cite{Hsu2002comparison}. Since TUTOR focuses on tabular datasets, none of these datasets are image-based. In addition, TUTOR focuses on settings where limited data are available. Hence, the majority of the chosen datasets are of small to medium size. First, we present results of applying TUTOR DNN synthesis to these datasets. In this case, we use the available data to synthesize the most accurate DNN models. We also evaluate the contribution of each training step of the TUTOR framework. Next, we evaluate the ability of TUTOR to reduce the need for large amounts of data. In this context, we evaluate the performance of TUTOR-generated models when only a part of the training and validation datasets are available. We then look into using dimensionality reduction (DR) as a method to reduce the number of parameters in the joint density estimation, and generating higher quality synthetic data. Finally, we discuss an application of TUTOR in which only the synthetic data are shared with other parties, not the real data. We compare DNN models synthesized for each case. \begin{table*}[htbp] \caption{Characteristics of the datasets.} \label{tab:characteristics} \centering \begin{tabular}{lccccc} \toprule Dataset & Training Set & Validation Set & Test Set & Features & Classes \\ \midrule Forest Cover Type (CoverType) \cite{covertype} & $348600$ & $116201$ & $116201$ & $12$ & $7$ \\ Sensorless Drive Diagnosis (SenDrive) \cite{ucidb} & $40509$ & $9000$ & $9000$ & $48$ & $11$ \\ MIT-BIH Arrhythmia Dataset (BIH-arrhythmia) \cite{mitbih} & $22628$ & $7543$ & $7543$ & $187$ & $2$\\ PTB Diagnostic ECG Database (PTB-ECG) \cite{ptbdb} & $8730$ & $2910$ & $2910$ & $187$ & $2$\\ Smartphone-based Human Activity Recognition (SHAR) \cite{ucidb} & $6213$ & $1554$ & $3162$ & $561$ & $12$ \\ Epileptic Seizure Dataset (EpiSeizure) \cite{ucidb} & $6560$ & $1620$ & $3320$ & $178$ & $2$\\ Human Activity Recognition Dataset (HAR) \cite{ucidb} & $5881$ & $1471$ & $2947$ & $561$ & $6$ \\ Statlog DNA (DNA) \cite{Hsu2002comparison} & $1400$ & $600$ & $1186$ & $180$ & $3$ \\ Breast Cancer Wisconsin Diagnostic Dataset (Breast Cancer) \cite{ucidb} & $404$ & $150$ & $160$ & $30$ & $2$ \\ \bottomrule \end{tabular} \end{table*} \subsection{TUTOR Performance Evaluation} \label{sect:performance} In this section, we evaluate the performance of the TUTOR framework on nine datasets. We present results for various synthetic data generation methods and training schemes. To compare the different synthetic data generation methods, we use t-distributed Stochastic Neighbor Embedding (t-SNE) \cite{maaten2008visualizing} to visualize high-dimensional data in a two-dimensional plane. Fig.~\ref{fig:tsne} compares the distribution of the three synthetic data generation methods with that of the original training data for the HAR dataset. One of the methods used in statistics to compare various models and measure how well they fit the data is the Akaike information criterion (AIC) \cite{vrieze2012model}. When a model is used to represent the process that generated the data, some of the information is lost due to the model not being exact. AIC measures the relative information lost in the process of modeling that data. A lower AIC value shows a better fit. Fig.~\ref{fig:aic} shows the AIC values as a function of the number of components in the GMM for modeling the training data of the HAR dataset. As can be seen, for this metric the best fit happens when the GMM has 22 components. \begin{figure*}[!ht] \centering \includegraphics[scale=0.24]{tsne-comp.png} \caption{Visualizing data distribution using t-SNE for $5000$ data points obtained from various data generation methods applied to the HAR dataset, from left to right: (1) original training data, (2) multi-variate normal distribution, (3) GMM, and (4) kernel density estimation.} \label{fig:tsne} \end{figure*} \begin{figure}[!h] \includegraphics[scale=0.4]{aic.pdf} \caption{AIC vs. number of components in GMM for the HAR dataset.} \label{fig:aic} \end{figure} Next, we analyze the impact of different parts of TUTOR on DNN model performance. We compare three classes of DNN models. The first class consists of conventional FC DNNs trained on the real training dataset. We refer to such models as DNN 1. The second class of models, referred to as DNN 2, consists of the better model between those obtained by Schemes A and B. The third class of models, referred to as DNN 3, is based on grow-and-prune synthesis. The starting point for DNN 3 is the better one from those synthesized by Schemes A and B, as evaluated on the validation set. Table~\ref{tab:NN-ablation} shows the comparisons. We report test accuracy, FLOPs, and number of parameters (\#Param) for each model. It also shows the test accuracy of the random forest model used in labeling the synthetic dataset. For each dataset, we train various FC DNNs (with different number of layers and neurons per layer) and verify their performance on the validation set. The FC baseline (DNN 1) for each dataset is the one that performs the best on the validation set. Since Scheme A only changes the weights of the network using synthetic data, the network architecture remains the same. Therefore, the FLOPs and number of parameters in the network are the same as those of DNN 1 models. Compared to DNN 1 models, Schemes A and B that take help of synthetic data can be seen to perform better. On average, DNN 2 models have $2.6\%$ higher test accuracy relative to DNN 1 models. This shows the importance of making use of synthetic data when the available dataset size is not large. We summarize below the relative performance of the DNN models obtained through grow-and-prune synthesis using both real and synthetic data (DNN 3). \begin{itemize} \item \textbf{Better test accuracy:} Compared to DNN 1 (DNN 2), DNN 3 improves test accuracy on an average by 3.4\% (2.3\%). \item \textbf{Less computation:} There is a $4.3\times$ ($5.9\times$) reduction in FLOPs per inference on an average (geometric mean) relative to DNN 1 (DNN 2). \item \textbf{Smaller model size:} There is a $4.7\times$ ($6.3\times$) reduction in the number of parameters on an average (geometric mean) relative to DNN 1 (DNN 2). Hence, the memory requirements are also significantly reduced. \end{itemize} \small\addtolength{\tabcolsep}{-2.0pt} \begin{table*}[] \caption{Comparison results for various parts of TUTOR. The best test accuracies between Schemes A and B (DNN 2) and with grow-and-prune (GP) synthesis are shown in bold. The results for the random forest (RF) model are also shown.} \label{tab:NN-ablation} \centering \begin{tabular}{l|c|ccc|ccc|ccccc|ccc} \toprule & \multicolumn{1}{c|}{RF} & \multicolumn{3}{c|}{FC Baseline} & \multicolumn{3}{c|}{Scheme A (ACC. \%)} & \multicolumn{5}{c|}{Scheme B (Acc. \%)} & \multicolumn{3}{c}{ + GP synthesis} \\ Dataset & Acc. (\%) & Acc. (\%) & FLOPs & \#Param. & MND & GMM & KDE & MND & GMM & KDE & FLOPs & \#Param. & Acc. (\%) & FLOPs & \#Param. \\ \toprule CoverType & 91.5 & 91.3 & 90.0k & 45.2k & \textbf{92.6} & 91.3 & 92.6 & 92.4 & 91.8 & 92.5 & 184.2k & 92.5k & \textbf{93.1} & 19.5k & 10.0k \\ SenDrive & 96.6 & 95.1 & 19.3k & 9.0k & 96.5 & 97.3 & 95.9 & 97.4 & \textbf{97.5} & 97.1 & 44.0k & 20.8k & \textbf{99.0} & 9.8k & 5.0k \\ BIH-Arrhythmia & 95.3 & 94.5 & 107.4k & 54.1k & 96.0 & \textbf{96.5} & 96.1 & 94.9 & 95.5 & 94.9 & 215.1k & 108.4k & \textbf{96.6} & 9.7k & 5.0k \\ PTB-ECG & 95.9 & 95.0 & 21.2k & 10.7k & 95.2 & \textbf{96.2} & 95.6 & 95.8 & 95.1 & 95.8 & 42.7k & 21.6k & \textbf{97.3} & 19.9k & 5.0k \\ SHAR & 90.3 & 91.6 & 707.6k & 354.9k & 93.4 & 93.0 & 93.3 & 93.2 & \textbf{93.7} & 92.7 & 1.4M & 710.6k & \textbf{94.3} & 19.2k & 10.0k \\ EpiSeizure & 97.4 & 89.4 & 95.5k & 48.1k & 93.0 & 92.4 & 93.0 & \textbf{95.6} & 94.6 & 95.0 & 191.9k & 96.7k & \textbf{97.2} & 69.7k & 35.0k \\ HAR & 87.5 & 93.2 & 703.1k & 352.7k & \textbf{94.2} & 93.8 & 94.1 & 93.3 & 93.6 & 93.6 & 1.4M & 706.1k & \textbf{95.1} & 49.2k & 25.0k \\ DNA & 92.4 & 92.3 & 130.3k & 65.7k & 93.9 & 94.8 & 93.5 & 93.5 & \textbf{94.9} & 94.0 & 260.9k & 131.6k & \textbf{95.8} & 49.6k & 25.0k \\ Breast Cancer & 93.7 & 93.7 & 7.2k & 3.7k & 94.4 & \textbf{96.9} & 94.4 & 94.4 & 96.6 & 95.0 & 14.7k & 7.6k & \textbf{98.7} & 2.9k & 1.5k\\ \bottomrule \end{tabular} \end{table*} \subsection{Reducing the Need for Data} \label{sect:data-reduction} In this section, we explore the impact of TUTOR on reducing the number of data instances needed. We apply TUTOR to only a part of the data selected using random sampling from the original dataset. We define the \emph{data compression ratio} as the ratio of the original training (validation) dataset size over the sub-sampled training (validation) dataset size. For a fair comparison, the test set remains unchanged across various data compression ratios. Fig.~\ref{fig:data-compression} shows the results for all the datasets. We compare the three DNN models as the dataset size decreases. The dashed horizontal and vertical lines in Fig.~\ref{fig:data-compression} show the needed data for DNN 3 to achieve similar test accuracy as DNN 1 that relies on the whole training and validation sets. We summarize this information in Table~\ref{tab:reduced-data}. On an average (geometric mean), TUTOR-synthesized DNN 3 (DNN 2) reduces the need for data by $5.9 \times$ ($3.6 \times$) while maintaining a similar test accuracy. \begin{figure*}[!ht] \centering \includegraphics[width=1.0\textwidth]{data_compression.png} \caption{Test accuracy vs. data compression ratio.} \label{fig:data-compression} \end{figure*} \begin{table*}[] \caption{Comparison of the data needed for TUTOR-synthesized DNNs to achieve similar accuracy to DNN 1.} \label{tab:reduced-data} \centering \begin{tabular}{l|ccc|ccc|ccc} \toprule & \multicolumn{3}{c|}{DNN 1} & \multicolumn{3}{c|}{DNN 2} & \multicolumn{3}{c}{DNN 3} \\ Dataset & Acc. (\%) & \#Train & \#Val & Acc. (\%) & \#Train & \#Val & Acc. (\%) & \#Train & \#Val\\ \midrule CoverType & 91.3 & 348600 ($1\times$) & 116201 ($1\times$) & 91.3 & 174300 ($2\times$) & 58100 ($2\times$) & 91.3 & 69720 ($5\times$) & 23240 ($5\times$) \\ SenDrive & 95.1 & 40509 ($1\times$) & 9000 ($1\times$) & 94.6 & 5063 ($8\times$) & 1125 ($8\times$) & 95.1 & 4050 ($10\times$) & 900 ($10\times$) \\ BIH-Arrhythmia & 94.5 & 22628 ($1\times$) & 7543 ($1\times$) & 95.6 & 11314 ($2\times$) & 3771 ($2\times$) & 94.5 & 5657 ($4\times$) & 1885 ($4\times$) \\ PTB-ECG & 95.0 & 8730 ($1\times$) & 2910 ($1\times$) & 96.2 & 8730 ($1\times$) & 2910 ($1\times$) & 95.1 & 4365 ($2\times$) & 1455 ($2\times$) \\ SHAR & 91.6 & 6213 ($1\times$) & 1554 ($1\times$) & 91.5 & 776 ($8\times$) & 194 ($8\times$) & 91.6 & 690 ($9\times$) & 172 ($9\times$) \\ EpiSeizure & 89.4 & 6560 ($1\times$) & 1620 ($1\times$) & 89.9 & 410 ($16\times$) & 101 ($16\times$) & 91.3 & 410 ($16\times$) & 101 ($16\times$)\\ HAR & 93.2 & 5881 ($1\times$) & 1471 ($1\times$) & 93.5 & 1960 ($3\times$) & 490 ($3\times$) & 93.3 & 840 ($7\times$) & 210 ($7\times$) \\ DNA & 92.3 & 1400 ($1\times$) & 600 ($1\times$) & 92.2 & 466 ($3\times$) & 200 ($3\times$) & 92.3 & 280 ($5\times$) & 120 ($5\times$) \\ Breast Cancer & 93.7 & 404 ($1\times$) & 150 ($1\times$) & 95.0 & 134 ($3\times$) & 50 ($3\times$) & 93.7 & 101 ($4\times$) & 38 ($4\times$) \\ \bottomrule \end{tabular} \end{table*} We also compare the performance of TUTOR-generated synthetic data with the synthetic data generated by the CTGAN \cite{xu2019modeling} method. In these experiments, we limit the available data to the same amount of data that DNN 2 and DNN 3 need to match the accuracy of DNN 1. To this end, we compare the performance of Schemes A and B using the two synthetic datasets, one generated by TUTOR and the other generated by CTGAN. Table~\ref{tab:comp-ctgan} summarizes the results. For each case, we report the accuracy of DNN 2. As can be seen, although the synthetic data generated by CTGAN performs better in a few cases, in a majority of cases our synthetic data leads to better results. In addition, for the cases where the available data is smaller, the performance of the TUTOR is noticeably superior. This is mainly due to the fact that GAN-based synthetic data generation relies on more data to train the generator and discriminator components. \begin{table*}[] \caption{Comparison between the performance of synthetic data generated by our framework and CTGAN \cite{xu2019modeling}.} \label{tab:comp-ctgan} \centering \begin{tabular}{l|cccc|cccc} \toprule & \multicolumn{4}{c|}{DNN 2} & \multicolumn{4}{c}{DNN 2} \\ Dataset & Acc. (\%) & Acc. (\%) & \#Train & \#Val & Acc. (\%) & Acc. (\%) & \#Train & \#Val\\ & (CTGAN \cite{xu2019modeling}) & (Ours) & & & (CTGAN \cite{xu2019modeling}) & (Ours) & & \\ \midrule CoverType & 91.5 & 91.3 & 174300 ($2\times$) & 58100 ($2\times$) & 89.7 & 90.1 & 69720 ($5\times$) & 23240 ($5\times$) \\ SenDrive & 93.6 & 94.6 & 5063 ($8\times$) & 1125 ($8\times$) & 92.9 & 95.1 & 4050 ($10\times$) & 900 ($10\times$) \\ BIH-Arrhythmia & 93.9 & 95.6 & 11314 ($2\times$) & 3771 ($2\times$) & 92.6 & 93.6 & 5657 ($4\times$) & 1885 ($4\times$) \\ PTB-ECG & 95.1 & 96.2 & 8730 ($1\times$) & 2910 ($1\times$) & 94.1 & 93.8 & 4365 ($2\times$) & 1455 ($2\times$) \\ SHAR & 87.8 & 91.5 & 776 ($8\times$) & 194 ($8\times$) & 85.9 & 91.6 & 690 ($9\times$) & 172 ($9\times$) \\ EpiSeizure & 86.7 & 89.9 & 410 ($16\times$) & 101 ($16\times$) & - & - & - & - \\ HAR & 92.0 & 93.5 & 1960 ($3\times$) & 490 ($3\times$) & 90.3 & 92.6 & 840 ($7\times$) & 210 ($7\times$) \\ DNA & 89.2 & 92.2 & 466 ($3\times$) & 200 ($3\times$) & 86.9 & 91.1 & 280 ($5\times$) & 120 ($5\times$) \\ Breast Cancer & 86.9 & 95.0 & 134 ($3\times$) & 50 ($3\times$) & 85.0 & 93.1 & 101 ($4\times$) & 38 ($4\times$) \\ \bottomrule \end{tabular} \end{table*} \subsection{Combining DR with TUTOR} In this section, we look into the impact of reducing the number of features in the dataset by applying DR methods. As the number of features in the data increases, more data instances are needed to model the joint distribution of the features in the data. This is due to the increase in the number of independent parameters of the joint density model. Thus, reducing the number of features may be helpful in reducing the need for more data instances. Hence, we study the impact of reducing the number of features for the two most high-dimensional datasets in our experiments: SHAR, and HAR. We use the traditional principal component analysis (PCA) for dimensionality reduction. Dimensionality reduction is only applied to continuous features and the categorical features remain unchanged. Table~\ref{tab:DR} shows the results. For each dataset, we report the best accuracy of Schemes A and B for various feature compression ratios. As we can see, DR helps improve model performance. For the HAR dataset, the highest accuracy corresponds to $2\times$ feature compression ratio using Scheme B for DNN synthesis. A $3\times$ feature compression ratio and Scheme B yield the highest accuracy for the SHAR dataset. Note that after a certain point, DR does not help improve performance, as it leads to loss of information. \small\addtolength{\tabcolsep}{-1.5pt} \begin{table*}[] \caption{Impact of DR on the performance of the TUTOR training schemes.} \label{tab:DR} \centering \begin{tabular}{c|ccc|ccc} \toprule & \multicolumn{3}{c|}{HAR data} & \multicolumn{3}{c}{SHAR data} \\ Feature compression ratio & DNN 1 & Scheme A & Scheme B & DNN 1 & Scheme A & Scheme B \\ & (\%) & (\%) & (\%) & (\%) & (\%) & (\%) \\ \toprule 1$\times$ & 93.2 & 94.2 & 93.6 & 90.3 & 93.4 & 93.7 \\ 2$\times$ & 93.3 & 94.1 & 95.2 & 93.5 & 94.3 & 94.1 \\ 3$\times$ & 93.7 & 93.7 & 94.6 & 93.7 & 94.2 & 95.1 \\ 4$\times$ & 92.7 & 92.9 & 93.1 & 93.1 & 93.7 & 94.1\\ 5$\times$ & 92.6 & 93.1 & 93.3 & 92.4 & 93.3 & 93.4 \\ 6$\times$ & 92.4 & 92.9 & 93.7 & 92.3 & 92.5 & 93.1 \\ 7$\times$ & 91.8 & 92.3 & 92.7 & 91.5 & 91.6 & 92.9 \\ \bottomrule \end{tabular} \end{table*} \subsection{TUTOR Application: Performance of Synthetic Data Alone} \label{sect:data-privacy} In this section, we evaluate the application of TUTOR to generating synthetic data that can be used alone to train DNN predictive models. In this application, to avoid exchanging personal information between various parties, we share the synthetic data generated by TUTOR instead. We use the synthetic data generation scheme that leads to the most accurate DNN model on the validation set. We use this DNN model to label the synthetic dataset. We generate 100,000 synthetic data instances. We train a generic three-layer DNN architecture, with two hidden layers with 100 neurons and an output layer, with only the synthetic data, and evaluate its performance on the separate real test set. We compare the results obtained with DNN 1 that is trained using the real training and validation sets. Table~\ref{tab:NN-synvreal} shows the results. As one can see, using synthetic data alone to train the DNN model leads to similar performance as DNN 1 on the unseen test data. Since we can generate large synthetic datasets, in six of the nine cases, the test accuracy improves by 0.2\% to 7.2\%. \small\addtolength{\tabcolsep}{-0.5pt} \begin{table*}[] \caption{Comparison of the FC baseline trained on real data with an FC DNN trained on synthetic data.} \label{tab:NN-synvreal} \centering \begin{tabular}{l|ccc|cccc} \toprule & \multicolumn{3}{c|}{FC DNN trained on real data} & \multicolumn{4}{c}{FC DNN trained on syn. data} \\ Dataset & Acc. (\%) & FLOPs & \#Param. & Method & Acc. (\%) & FLOPs & \#Param. \\ \toprule CoverType & 91.3 & 90.0k & 45.2k & GMM & 84.2 & 24.2k & 12.2k \\ SenDrive & 95.1 & 19.3k & 9.0k & GMM & 92.5 & 31.6k & 16.1k \\ BIH-Arrhythmia & 94.5 & 107.4k & 54.1k & KDE & 95.1 & 57.6k & 29.1k \\ PTB-ECG & 95.0 & 21.2k & 10.7k & GMM & 92.6 & 57.6k & 29.1k \\ SHAR & 91.6 & 707.6k & 354.9k & KDE & 92.8 & 134.4k & 67.5k \\ EpiSeizure & 89.4 & 95.5k & 48.1k & GMM & 96.6 & 55.8k & 28.2k \\ HAR & 93.2 & 703.1k & 352.7k & GMM & 93.4 & 133.2k & 66.9k \\ DNA & 92.3 & 130.3k & 65.7k & GMM & 94.2 & 56.4k & 28.5k \\ Breast Cancer & 93.7 & 7.2k & 3.7k & KDE & 95.0 & 26.2k & 13.4k \\ \bottomrule \end{tabular} \end{table*} \section{Discussion and Limitations} \label{sect:discussion} In this section, we discuss the inspiration we took from the human brain in designing the TUTOR framework. We also discuss TUTOR's limitations that can be addressed in the future. An interesting aspect of the human brain is its ability to quickly solve a problem in a new domain, despite limited experience. It intelligently utilizes prior learning experiences to adapt to the new domain. Inspired by this process, TUTOR addresses the need for a large amount of data by generating synthetic data from the same probability distribution as the limited available data. The synthetic data are used to warm-start the DNN training process, providing it with an appropriate inductive bias. The human brain also changes its synaptic connections dynamically, to adapt to the task at hand. In fact, this is one way for it to acquire knowledge. TUTOR takes inspiration from this aspect of human intelligence in the grow-and-prune synthesis step. Allowing architectures to adapt during the training process enables TUTOR to generate accurate and efficient (both in terms of computation and memory requirements) architectures for the task at hand. Although TUTOR addresses the small data problem of tabular datasets, the same problem may exist in image-based datasets. For example, image-based datasets in healthcare tend to be small, due to the difficulty of data collection and labeling. Although techniques like DeepInversion \cite{yin2020dreaming} have begun to address realistic but synthetic images from the same probability distribution, extending TUTOR to image-based applications can also be part of future work. \section{Conclusion} \label{sect:conclusion} In this work, we proposed the TUTOR framework to address the need for large datasets in training DNN predictive models. TUTOR targets tabular datasets. It relies on the synthetic data generated from the same distribution as the real training data. Using the semantic integrity classifier module, TUTOR verifies the validity of the generated synthetic data. To label the verified synthetic data, it uses a random forest model trained on the real training data. Synthetic data are used alongside real data in two training schemes to train the DNN weights. These schemes employ synthetic data in two different ways to impose a prior on the DNN weights, thus starting the training process with a better initialization point. In addition, TUTOR utilizes the grow-and-prune synthesis paradigm to ensure model compactness while boosting accuracy. TUTOR can be particularly useful in settings where available data are limited, such as healthcare applications. Since the generated models are compact, they can be deployed on edge devices, such as smartphones and Internet-of-Things sensors. \bibliographystyle{IEEEtran}
{'timestamp': '2022-02-17T02:06:30', 'yymm': '2010', 'arxiv_id': '2010.05429', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05429'}
arxiv
\section*{Introduction} As cooperation is costly, an individual is better off not cooperating. This leads to a tragedy of the commons where everyone ends up being worse off than if otherwise, all had cooperated \cite{Hardin}. However, contrary to what a rational argument suggests, empirical evidence shows that tragedies of the commons are not that common in nature \cite{Boyd}. Over the past decades, many efforts have been devoted to understanding how evolution has prevented tragedies of the commons and promoted high levels of cooperation \cite{Boyd,Axelrod,Nowak,Perc2013}. Prisoner's dilemma, and its extension to $n$ players, public goods game (PGG), have been the most common frameworks in many of these studies \cite{Doebeli,Axelrod,Nowak,Perc2013,Axelrod}. In the latter game, each player in a group of $n$ players can decide whether to invest an amount $c$ in a public good or not. All the investments are multiplied by an enhancement factor $r<n$ and are divided equally among the players. Defectors, refraining from investment, receive the highest payoff and are expected to dominate the population. This expectation contradicts observation \cite{Boyd,Axelrod}. Past researches have revealed different mechanisms through which this puzzle can be solved. For instance, when interactions are repeated, cooperation can evolve due to the threat of retaliation of a defective act in future rounds \cite{Hilbe2018a,Axelrod,Schmid2021}. However, in many cases, interactions are not repeated. A similar mechanism, indirect reciprocity \cite{Milinski,Panchanathan,Schmid2021,Alexander2017}, based on which an individual's reputation determines others' behavior towards the individual can be at work to promote cooperation in non-repeated interactions. Similarly, punishment of defectors \cite{Fehr,Perc,Boyd2,Szolnoki,Hauert1,Hilbe2,Salahshour2,Salahshour2021B} or rewarding cooperators \cite{Rand,Attila,Hilbe} can promote social behavior. Cooperation can also evolve when interactions are not obligatory \cite{Hauert,Szabo}, or when individuals have a choice between different institutions \cite{Salahshour0,Salahshour2021A}. Furthermore, it is shown that the very existence of population structure can promote cooperation due to the assortativity of interactions in structured populations \cite{Ohtsuki2006,Perc2013}. Other studies have shown assortativity \cite{Iyer2020}, for instance resulting from kin selection, group selection \cite{Nowak} or tag-based mechanisms \cite{Riolo2001}, social diversity \cite{Qin,Santos}, heterogeneity \cite{Perc2011,Stilwell2020,Kun2013}, conformity \cite{Hu2019,Szolnoki2015}, costly signaling \cite{Salahshour1,Gintis}, moral norms \cite{Salahshour2021C,Alexander2017}, and coevolution of cooperation and language \cite{Salahshour2020}, to mention a few, can play a positive role in the evolution of cooperation. Despite the valuable insights reached on the subject, open questions regarding the mechanisms and conditions under which cooperative behavior is expected to flourish, remain to be addressed. A curious question in this regard is the existence of consistent cooperative and defective personalities. For instance, public goods experiments have shown that while about half of the people are conditional cooperators who are willing to cooperate provided their group-mates cooperate, others tend to free-ride on others' contributions \cite{Fischbacher1,Fischbacher2,Burlando,Chaudhuri}. Similar observations regarding consistent personality differences in humans and animals, in different contexts, have been made \cite{Bergmuller}. These observations raise the question of how such consistent cooperative and defective personality differences evolve, and if this can play a constructive role in the evolution of cooperation? To gain a better insight into this question, here, I consider a context where individuals possibly play two consecutive PGGs. Individuals have independent strategies in the two PGGs. However, their strategy in the first PGG determines the PGG they enter for the second round. This feature of the model has similarities with stochastic games \cite{Hilbe2018b}, where individuals' strategy can affect the game they play in future rounds. However, while in stochastic games, the future interaction occurs in the same context for all the individuals \cite{Hilbe2018b}, here, I consider a situation where individuals may have different future interactions based on their strategies. I consider two different scenarios. In the first scenario, only first-round cooperators play a second PGG. In the second scenario, both first-round cooperators and first-round defectors are offered the chance to play a second PGG, but in different groups. In the first scenario, playing a second public good can be considered as a potential reward for cooperative behavior. This scenario is motivated by the observations that in many contexts, cooperation serves as a signal of merit \cite{Milinski,Van,Gintis,Salahshour1} or offers a high social status \cite{Smith3,Bird,Marlowe} which can increase others' willingness to interact with a cooperator. This can increase an individual's chance of having future interaction, which I model by allowing a cooperator to enter a second PGG. However, in contrast to a certain reward for a cooperative act, the outcome of the second PGG can be positive or negative, depending on the groups' ability to solve the second public goods dilemma, which we call a prosocial reward dilemma. Then, the question arises whether the community can solve a reward dilemma and if this can promote cooperation in the first PGG in the first place? In the second scenario, I consider an assortative context where not only first-round cooperators, but both first-round cooperators and first-round defectors enter a second PGG, but in different groups. This scenario is motivated by many pieces of evidence of assortative behavior \cite{Kossinets,Brekke}, such as breaking or forming ties \cite{Wang,Santos2}, according to which individuals are more likely to interact with similar individuals, and can be considered as a context where both cooperative and defective behavior are rewarded, by, respectively, a prosocial and an antisocial reward dilemma. Importantly, in the model introduced here, the strategies of the individuals are independent in the two rounds. Thus, while it is noted that associativity can promote cooperation when individuals have the same strategy in different interactions - a fact which in a sense underlies many mechanisms for the evolution of cooperation such as network reciprocity, tag based mechanisms, group selection and kin selection - it is not clear whether assortativity of the interactions can play a positive role where individuals have a priori independent strategies in different interactions. The analysis of the models show that cooperation evolves in both the presence of a reward dilemma and in the presence of assortative interaction. As the comparison of the two scenarios reveals, offering defectors the chance to play a second PGG, that is, an antisocial reward dilemma, can have a surprisingly positive impact on the evolution of cooperation. Interestingly, in an assortative context, in the course of evolution, individuals tend to develop consistent strategies in the two consecutive games. By increasing the likelihood that the benefit of a cooperative act is reaped by fellow cooperators, such a personality consistency, in turn, facilitates the evolution of cooperation. These findings shed new light on the evolution of consistent personalities \cite{Weissing,Wolf,Wolf2,Dall,Johnstone,Bergmuller}, and shows how in an attempt to solve social dilemmas, evolution may have given rise to the evolution of consistent cooperative and defective personalities. \section*{The Model} In our model, in a well-mixed population of $N$ individuals, groups of size $g$ are randomly formed to play a PGG with enhancement factor $r_1$, possibly followed by a second PGG with enhancement factor $r_2$. That is, at each time step, the whole population is divided into $N/g$ randomly formed groups. Strategies of the individuals in the second PGG are independent of the first PGG. Thus, there are four possible strategies: cooperation in both games ($C_1C_2$), cooperation in the first game and defection in the second one ($C_1D_2$), defection in the first and cooperation in the second game ($D_1C_2$), and finally, defection in both games ($D_1D_2$). I consider two different scenarios. In the first scenario, called a (prosocial) reward dilemma, while defection entails no more round of PGG, cooperation in the first game leads to the entrance to a second PGG. This scenario is consistent with a situation where cooperation serves as a signal of merit \cite{Milinski,Van,Gintis,Salahshour1} or offers a high social status \cite{Smith3,Bird,Marlowe} which can increase others' willingness to interact with a cooperator, and thus, the individual is permitted to enter an elite PGG. In the second scenario, called the assortative public goods game, all the individuals in the group proceed to play a second PGG. However, motivated by many pieces of evidence of assortative behavior \cite{Kossinets,Brekke}, such as breaking or forming ties \cite{Wang,Santos2}, I assume individuals are sorted based on their strategies in the first round, such that all the individuals who cooperate in the first round form a subgroup to play a PGG (which is called the cooperative or prosocial PGG), and all those who defect in the first round form a different subgroup to play their second PGG (which is called the defective or anti-social PGG). In this way, the corresponding PGG can be considered an assortative PGG, in which individuals are sorted based on their strategy in the first round. Individuals gather payoff according to the outcome of the games. Besides, I assume individuals receive a base payoff $\pi_0$ from other activities not related to the PGG. After playing the games, individuals reproduce with a probability proportional to their payoff, such that the population size remains constant. That is, the whole population is updated synchronously such that each individual in the next generation is offspring to an individual $i$ in the past generation with a probability proportional to its payoff $\pi_i$. Offspring inherit the strategy of their parent. However, mutations can occur. Mutations in the strategy of the individuals in each round ($s_1$ and $s_2$, where $s_i$ can be $C$ or $D$) occur independently, and each with probability $\nu$. When a mutation occurs, the corresponding variable's value switches to its opposite value ($C$ to $D$ and vice versa). \begin{figure \centering \includegraphics[width=1\linewidth, trim = 80 101 55 51, clip,]{fig1Srep} \caption{A reward dilemma solves the social dilemma. (a): The phase diagram of the model derived from solutions of the replicator dynamics, for two different mutation rates (top $\nu=10^{-3}$ and bottom $\nu=10^{-5}$). The dynamics settle in a periodic orbit or a fixed point depending on the parameters of the model. (b) to (d): Color plots of, respectively, $\langle\rho_{C_1C_2}\rangle_t$, $\langle\rho_{C_1D_2}\rangle_t$ and $\langle\rho_{D_1}\rangle_t=\langle\rho_{D_1C_1}+\rho_{D_1D_2}\rangle_t$. Top panels result from solutions of the replicator dynamics, and bottom panels result from simulations. Cooperation evolves in the second game (c) and is maximized for moderate values of $r_2$. This renders entering the second game an incentive to cooperate in the first game, which promotes cooperation in the first game. Here, $g=10$, $c=1$, and $\pi_0=2$. In (b), (c), and (d), $\nu=10^{-3}$. Simulations are performed in a population of size $N=5000$. The simulation is performed for $T=3000$ time steps starting from an initial condition with random assignment of strategies, and the time averages are taken over the last $2000$ time steps. The replicator dynamics are solved for $T=5000$ time steps starting from homogeneous initial conditions. Time averages are taken over the last $2000$ time steps. As the model is mono-stable in the entire phase diagrams, the results are independent of the initial conditions.} \label{fig1} \end{figure} \section*{Results} \subsection*{The first scenario: A reward dilemma solves the social dilemma} As shown in the Methods Section, both models can be described in terms of the replicator dynamics, which gives an exact description of the model in infinite population limit. Beginning with the reward dilemma model, I note that when $r_2>g$, the second PGG is no longer a dilemma. Cooperation becomes the most rational strategy, which guarantees for the second PGG to yield a positive reward to those who enter it by cooperating in the first PGG. As it is known \cite{Attila,Rand,Hilbe}, and as our model confirms, such a certain reward promotes cooperation. The situation becomes more interesting when $r_2<g$. In this case, the second PGG can even yield a negative outcome. For a promise of having future interaction to promote cooperation, the community needs to solve a second dilemma. As I show below, such coupled dilemmas can be solved through evolution. I begin by plotting the phase diagram of the model for two different mutation rates, $\nu=10^{-3}$ (top), and $\nu=10^{-5}$ (bottom), in Fig. \ref{fig1}(a). Here and in the following, $g=10$, $c=1$, $\pi_0=2$. For too large values of $r_1$, the dynamics settle in a fixed point (denoted by FP in the figures). On the other hand, for smaller values of $r_1$, cyclic behavior occurs for intermediate values of $r_2$ (indicated by PO in the figures). For both too large and too small $r_2$, a transition to a phase where the dynamics settle in a fixed point is observed. As can be seen by comparing the phase diagram for two different mutation rates, lower mutation rates increase the size of the region where the dynamics settle in a periodic orbit. To see how the cooperation changes with $r_1$ and $r_2$, in Figs. \ref{fig1}(b), \ref{fig1}(c), and \ref{fig1}(d), I plot, respectively, the time average of $\rho_{C_1C_2}$, $\rho_{C_1D_2}$ and $\rho_{D_1}=\rho_{D_1C_2}+\rho_{D_1D_2}$. For small $r_2$, such that the second PGG is not profitable enough to motivate cooperation in the first PGG, the dynamics settle into a defective fixed point, where the majority of the individuals defect in the first game and do not play the second game. Consequently $\rho_{D_1}$ takes a large value approximately equal to $1-\nu$, and both $\rho_{C_1C_2}$ and $\rho_{C_1D_2}$ take small values maintained by mutations. As $r_2$ increases, cooperation in both rounds evolve. To see how this happens, I note that the cost of cooperation in the first round is equal to $c(r_1/g-1)$. As a single mutant $C_1C_2$ receives a payoff of $c(r_2-1)$ from the second round, cooperation evolves when the payoff of a mutant $C_1C_2$ from the second round becomes larger than the cost of cooperation in the first round. That is when $r_2>2-r_1/g$. By increasing $r_2$ beyond this point, $\rho_{C_1C_2}$ rapidly increases. This increases the effective group size in the second round PGG, and thus the expected payoff of second-round defectors, which is an increasing function in $\rho_{C_1C_2}$, increases. To see why this is the case, I note that the payoff of a $C_1D_2$ individual from the second round in a group composed of $n_{C_1C_2}$ $C_1C_2$ group-mates and $n_{C_1D_2}$ $C_1D_2$ group-mates is equal to $cr_2\rho_{C_1C_2}/(1+n_{C_1C_2}+n_{C_1D_2})$, which is larger in groups with a higher number of $C_1C_2$ individuals. The probability of formation of groups with a higher number of $C_1C_2$ individuals, in turn, increases with increasing $\rho_{C_1C_2}$ (see Methods), and thus, the expected payoff of a second-round defector increases by increasing $\rho_{C_1C_2}$. Consequently $\rho_{C_1D_2}$ increases by further increasing $r_2$ beyond $2-r_1/g$. While this leads to enhanced cooperation in the first round, it also reduces the frequency of second-round cooperators due to the exploitation by second-round defectors. Consequently, the profitability of the second-round PGG decreases and fewer individuals cooperate in the first round to enter the second round PGG. Thus the density of first-round defectors shows a local maximum at a moderate value of $r_2$ at the transition between the cyclic orbit and partially cooperative fixed point at large $r_2$. \begin{figure \centering \includegraphics[width=1\linewidth, trim = 90 265 75 05, clip,]{fig2Srep} \caption{Time evolution of the reward dilemma model. The frequency of different strategies as a function of time is plotted. The top panels represent numerical solutions of the replicator dynamics, and the bottom panel results from a simulation in a population of $N=5000$ individuals. In all the cases, $r_1=1.8$. In (a), $r_2=2$, which is slightly larger than the threshold necessary for the evolution of cooperation, $2-r_1/g=1.82$, and thus a small fraction of $C_1C_2$ strategies evolve. In (b) $r_2=3.8$, corresponding to the cyclic phase where different strategies cyclically dominate the population. In (c) and (d), respectively, $r_2=8.8$ and $r_2=9.8$, both corresponding to the cooperative fixed point. Parameter values: $\nu=10^{-3}$, $g=10$, $c=1$, and $\pi_0=2$. The replicator dynamics is solved starting from homogeneous initial conditions, and simulations are performed starting from random assignment of strategies.} \label{fig2} \end{figure} The time evolution of the system for different strength of reward dilemma $r_2$ is presented in Fig. \ref{fig2}. Here, the result of the numerical solution of the replicator dynamics (top) and a simulation in a population of size $N=5000$ (bottom) are presented. Here, $g=10$, $\nu=10^{-3}$, $c=1$, $\pi_0=2$, and $r_1=1.8$. In Fig. \ref{fig2}(a), $r_2=2$. This is slightly larger than $2-r_1/g=1.82$, and thus $C_1C_2$ strategy survive in the population. For larger values of $r_2$, the fixed point becomes unstable, and the dynamics settle in the cyclic orbit. An example of the cyclic orbit for $r_2=3.8$ is presented in Fig. \ref{fig2}(b). In the cyclic phase, when the density of individuals who cooperate in the first round and thus enter the second PGG is small, individuals can reach a high payoff by entering and cooperating in the second PGG. Thus $\rho_{C_1C_2}$ increases. When $\rho_{C_1C_2}$ increases enough, individuals can reach a higher payoff by defecting in the second PGG. At this point, $\rho_{C_1D_2}$ begins to increase, while $\rho_{C_1C_2}$ decreases. As the density of defectors in the second PGG increases, its profitability decreases, and thus individuals have no incentive to cooperate in the first round. Consequently, both $\rho_{D_1D_2}$ and $\rho_{D_1C_2}$, as well as $\rho_D=\rho_{D_1D_2}+\rho_{D_1C_2}$ increase, while other strategies decrease (I note that, since those who defect in the first round do not enter the second game, the two strategies $D_1D_2$ and $D_1C_2$ are degenerate as they lead to the same payoff and are found in the same densities). The time evolution of the system in the partially cooperative fixed point in large $r_2$ is presented in Figs. \ref{fig2}(c) and \ref{fig2}(d). In Fig. \ref{fig2}(c), $r_2=8.8$. This corresponds to just above the transition line from the periodic solution to the fixed point. Consequently, the replicator dynamics settle in the fixed point after showing transient damped osculations around the fixed point. The simulation results show small fluctuations around the stationary state due to finite-size effects. Comparison of the case of $r_2=3.8$ in Fig. \ref{fig2}(b) and $r_2=8.8$ in Fig. \ref{fig2}(c) shows that $\rho_{C_1D_2}$ increases for larger $r_2$ due to the higher profitability of the second-round PGG, which motivates more individuals to cooperate in the first round to enter this PGG. This, in turn, can have an adverse effect on $\rho_{C_1C_2}$ due to the larger effective group size of the second round $PGG$. For larger $r_2$, as in Fig. \ref{fig2}(d) where $r_2=9.8$, the dynamics settles in the fixed point without showing damped osculations. Furthermore, $\rho_{C_1C_2}$ increases and $\rho_{C_1D_2}$ decrease as $r_2$ approaches $g$. \begin{figure \centering \includegraphics[width=1\linewidth, trim = 196 255 280 90, clip,]{fig3Srep} \caption{The phase diagram of the assortative public goods game. The phase diagram in the $r_1-r_2$ plane. For both small and large values of $r_2$ the model settles into a fixed point (FP). In between, the model shows the cyclic dominance of different strategies. Two different periodic orbits, DPO and CPO, separated by a singular transition exist. (b): Different stability regions in the $r_1-r_2$ plane (lines). The phase boundaries are superimposed (empty circles). The model shows two bistability regions where either both the fixed point and the CPO, or both DPO and CPO are stable. Here, $g=10$, $\nu=10^{-3}$, $c=1$, and $\pi_0=2$.} \label{fig3} \end{figure} \subsection*{The second scenario: The evolution of cooperation and consistent personalities in assortative public goods} As we have seen so far, a reward dilemma solves the social dilemma. An interesting question is whether such a mechanism can be competitive if defectors have the chance of forming a PGG of their own? This brings us to an assortative public goods game where both first-round cooperators and first-round defectors are rewarded by a second round of interaction, but in separate groups. The phase diagram of the assortative public goods game is presented in Fig(\ref{fig3}.a), top panel. For both too small and too large $r_2$, the system settles into a fixed point, and cyclic behavior emerges in between. However, there are two qualitatively different periodic orbits, each stable in some region of the parameter space. For smaller $r_2$, the dynamics settle into a defective periodic orbit (DPO). In this orbit, while cooperation in the cooperative PGG evolves, cooperation does not evolve in the defective PGG. I note that this is the same periodic orbit observed in the reward dilemma model. That such a periodic orbit endures in the second scenario shows its competitive stability. In other words, just as prosocial reward is stable in the presence of an antisocial reward \cite{Attila}, a prosocial reward dilemma is stable in the presence of an anti-social reward dilemma. On the other hand, for large $r_2$, the dynamics settle into the cooperative periodic orbit (CPO), where cooperation in both cooperative and defective PGGs evolves. \begin{figure \centering \includegraphics[width=1\linewidth, trim = 90 265 75 05, clip,]{fig4Srep} \caption{The time evolution of the system in assortative public goods games (a) to (d): The frequency of different strategies as a function of time. Top panels show replicator dynamics solutions and the bottom panels result form the simulations in a population of $N=5000$ individuals. The system shows two different periodic orbits. A cooperative periodic orbit, with higher level of cooperation for larger $r_2$, $r_2=4.8$ in (a), and a defective periodic orbit, for small $r_2$, $r_2=2.4$ in (b). In the fixed point of the dynamics for small $r_2$ but larger than $2-r_1/g$, as in (c) where $r_2=2$, only $C_1C_2$ cooperators evolve, and for large $r_2$, $r_2=5.6$ in (d), both $C_1C_2$ and $D_1C_2$ evolve. Here, $g=10$, $\nu=10^{-3}$, $c=1$, $\pi_0=2$, and $r_1=2.8$. The replicator dynamics is solved starting from homogeneous initial conditions and simulations are performed starting from random assignment of strategies.} \label{fig4} \end{figure} Interestingly, for small fixed $r_1$, by increasing $r_2$ the system shows a cross-over from the DPO to CPO without passing any singularity. However, for large $r_1$, starting from a uniform initial condition, in which the initial densities of all the strategies are equal, as $r_2$ increases, the equilibrium state of the system changes singularly in a certain value of $r_2$. This indicates the transition between DPO and CPO resembles a discontinuous transition for larger $r_1$. As a discontinuous transition is usually accompanied by bistability \cite{Binder}, this raises the question of whether the system possesses a bistable region as well? To address this question, I present the boundaries of bistability in Fig. \ref{fig3}(b) (black lines). The phase boundaries, which result from a homogeneous initial condition, are superimposed in this figure as well. The boundaries of bistability are derived by solving the replicator dynamics starting from different initial conditions and checking for hysteresis (see Methods). The system is monostable outside of the bistable region, indicated by black lines. In the monostable regions, the dynamics settle in the same stationary state, starting from all the initial conditions. In the bistable region (inside the black line), two different stable states, indicated in the figure, are possible depending on the initial conditions. I note that, while the cooperative periodic orbit is stable in the bistable region, it has a very small basin of attraction, such that the replicator dynamics does not settle into this orbit starting from most randomly generated initial conditions (see the Supplementary Information, figures SI.4 and SI.5). For this reason, to derive the boundaries of bistability, a hysteresis analysis is used (see methods). As can be seen in the figure, the transition from a fixed point to the DPO in small $r_2$ does not show any bistability and occurs at the same value for all the initial conditions. Similarly, the transition from CPO to a fixed point in large $r_2$ does not show any bistability. In contrast, the transition to CPO by increasing $r_2$ shows bistability: For medium $r_2$, there is a region of the phase diagram where both CPO and DPO are stable. Similarly, the model shows a bistability region for large $r_1$ where both the fixed point and the cooperative periodic orbit are stable. In Fig. \ref{fig4}, I present the time evolution of different strategies. An example of different periodic orbits is presented in Fig. \ref{fig4}(a) (CPO) and Fig. \ref{fig4}(b) (DPO). Top panels present the result of the replicator dynamics, and the bottom panels present the result of a simulation in a population of size $N=5000$. In Fig. \ref{fig4}(a), $r_1=2.8$ and $r_2=4.8$, and in Fig. \ref{fig4}(b), $r_1=2.8$ and $r_2=2.4$. For larger $r_2$, as in Fig. \ref{fig4}(a), defective and cooperative PGGs perform competitively, and competition between these two maintains cooperation in the system. When $\rho_{C_1D_1}$ ($\rho_{D_1D_2}$) is small, the cooperative (defective) PGG is profitable, and thus, it motivates individuals to cooperate (defect) in the first game in order to enter to this PGG. Consequently, $\rho_{C_1C_2}$ ($\rho_{D_1C_2}$) increases. As $\rho_{C_1C_2}$ ($\rho_{D_1C_2}$) increases enough, the cooperative (defective) PGG becomes vulnerable to defection, due to high frequency of cooperators in this PGG which increase the expected payoff of a second round defector, $\rho_{C_1D_2}$ ($\rho_{D_1D_2}$). At this point, $\rho_{C_1D_1}$ ($\rho_{D_1D_2}$) starts to increase. This in turn decreases the profitability of the cooperative (defective) PGG, and individuals are better off by switching to defection (cooperation) in the first round to enter the defective (cooperative) PGG. Consequently, both $\rho_{C_1C_2}$ and $\rho_{C_1D_2}$ ($\rho_{D_1C_2}$ and $\rho_{D_1D_2}$) decrease, while $\rho_{D_1C_2}$ and $\rho_{D_1D_2}$ ($\rho_{C_1C_2}$ and $\rho_{C_1D_2}$) increase. In this way, competition between cooperative and defective PGGs maintain cooperation in the population. Interestingly, individuals tend to have compatible strategies in the two rounds. That is, those who cooperate in the first round are more likely to cooperate in the second round. This can be seen by noting that on average $\rho_{C_1D_2}$ is much smaller than $\rho_{D_1D_2}$, even though defection in cooperative and defective PGGs leads to, on average, similar payoffs as the density of cooperators in these two games ($\rho_{C_1C_2}$ and $\rho_{D_1C_2}$) are similar. \begin{figure}[!hbt] \centering \includegraphics[width=1\linewidth, trim = 81 51 40 95, clip,]{fig5Srep} \caption{Evolution of cooperation and consistent personalities in assortative public goods game. (a): The time series of the personality consistency measure $\gamma$ (top), and the connected correlation function between the strategies of the individuals in the two rounds $\langle s_1s_2\rangle_t$ (middle). For comparison, the densities of different strategies are plotted in the bottom panel. Both measures always remain non-negative. This shows individuals evolve consistent personalities in the two rounds. (b): The contour plot of the time average personality measure $\langle\gamma\rangle_t$, in $r_1-r_2$ plane. $\gamma$ remains non-negative in the whole phase diagram, which indicates consistent cooperative and defective personalities evolve. (c): The contour plot of the time average cooperation level in the first round $\langle\rho_{C_1}\rangle_t=\langle\rho_{C_1C_2}+\rho_{C_1D_2}\rangle_t$. The phase boundaries are plotted in the top panel as well. Interestingly, the cooperation level in the first round is maximized on the singular transition between the two periodic orbits. (e): The contour plot of the time average cooperation level in the second round $\langle\rho_{C_2}\rangle_t=\langle\rho_{C_1C_2}+\rho_{D_1C_2}\rangle_t$. $\langle\rho_{C_2}\rangle_t$ increases with increasing $r_2$. Here, $g=10$, $\nu=10^{-3}$, $c=1$, and $\pi_0=2$. In (a) numerical solutions of the replicator dynamics are used. In (b) to (d), top panels result from numerical solutions of the replicator dynamics, and bottom panels result from simulation on a population of size $N=10000$. The replicator equations are solved for $T=5000$ time steps starting from a homogeneous initial condition, and the time averages are taken over the last $2000$ steps. The simulations are performed for $T=4000$ steps starting from a random assignment of strategies, and the averages are taken over the last $3500$ steps.} \label{fig5} \end{figure} As mentioned before, the situation is different for smaller $r_2$. For smaller $r_2$, as can be seen in Fig. \ref{fig4}(b), while cooperation in the cooperative PGG evolves, cooperation in the defective PGG does not evolve. This again hints at the evolution of compatible strategies in the two rounds. Consequently, for smaller $r_2$, while the cooperative PGG can become profitable due to the evolution of fully cooperative $C_1C_2$ strategies and motivates individuals to cooperate in the first game, the defective PGG does not perform competitively and can not attract individuals. As mentioned before, this periodic orbit is the same periodic orbit observed in the reward dilemma model. The dynamics settle in fixed points for both small and large $r_2$. Example of the dynamics of the system in this regime are presented in Fig. \ref{fig4}(c), for small $r_2$, $r_2=2$ and Fig. \ref{fig4}(d), for large $r_2$, $r_2=5.6$. As for small $r_2$, cooperation evolves only in the cooperative PGG, the situation is similar to the reward dilemma model: $C_1C_2$ individuals are found in the population (beyond that maintained by mutations) if $r_2>2-r_1/g$. This is what we observe in Fig. \ref{fig4}(c). This again hints at the evolution of consistent personalities, as only fist round cooperators cooperate in the second round. The fixed point for large $r_2$ is presented in Fig. \ref{fig4}(d). As $r_2$ is chosen just slightly beyond the transition line between cooperative periodic orbit and the fixed point, the dynamics shows damped oscillations around the stationary state before settling in the fixed point. Simulations in a finite population, on the other hand, show that small fluctuations around the stationary state occur in this region. I note that the evolution of consistent personalities can be observed in this regime as well, as the frequency of defectors in the defective PGG is larger than that in the cooperative PGG. That is, first-round defectors are more likely to defect in the second round compared to first-round cooperators. The fact that individuals' strategies in the two games tend to be compatible can be studied in more depth. To do this, I consider two measures of consistency of the strategies in the two rounds. As a first measure of compatibility of the strategies of the individuals in the two rounds, I define $\gamma=[P(C_2|C_1)+P(D_2|D_1)-P(D_2|C_1)-P(C_2|D_1)]/2$. Here, $P(s_2|s_1)$ is the conditional probability that an individual has strategy $s_2$ in the second game, given its strategy in the first game $s_1$. $\gamma$ takes a value between one and minus one, and the more positive $\gamma$, the more individuals' strategies in the two rounds are consistent. As a second measure of personality consistency, I consider the connected correlation function of the strategies of the individuals in the two rounds $\langle s_1 s_2 \rangle_c= \langle s_1s_2\rangle-\langle s_1\rangle \langle s_2\rangle$. To calculate this, I assign $-1$ to the strategy $D$, and $+1$ to the strategy $C$. These are plotted in Fig. \ref{fig5}(a) (top). For comparison, the density of different strategies is plotted as well (bottom panel). Both personality measures show cyclic behavior and always remain non-negative. Importantly, the latter holds in all the phases. This can be seen in Fig. \ref{fig5}(b), where the color plot of the time average of $\gamma$, for numerical solutions of the replicator dynamics (top) and a simulation in a population of size $N=10000$ (bottom) is presented. Interestingly, for fixed $r_2$, personality consistency measures show a maximum close to (but not exactly on) the transition from the fixed point to the defective periodic orbit. This corresponds to $r_2=2-r_1/g$, where the benefit of cooperation in the cooperative PGG starts to become large enough to compensate the cost of cooperation in the first round necessary to enter this PGG. Our results thus show that individuals develop consistent cooperative and defective personalities [See the Supplementary Information for the validity of this result for other parameter values]. This, in turn, plays a positive role in promoting cooperation, as individuals behaving consistently in the two rounds, together with the assortative nature of the public goods, allows first-round cooperators to be more likely to reap the benefit of cooperation in the second round, compared to first-round defectors. I begin the study of the cooperation by plotting the average cooperation in the first game in Fig. \ref{fig5}(c), and the average cooperation in the second game in Fig. \ref{fig5}(d). Here, the phase transition lines are indicated in the figure as well. As can be seen, cooperation in the first game is maximized for a moderate value of $r_2$, and it drops for both too small and too large values of $r_2$. Increasing $r_2$ beyond this value has a detrimental effect on cooperation in the first round. This is due to the fact that for larger values of $r_2$, cooperation in the second round increases in both the defective and the cooperative PGGs. This decreases individuals' incentive to cooperate in the first round to be sorted with fellow cooperators in the second round. On the other hand, for too small $r_2$, any potential benefit from the second round can be too small to promote high cooperation in the first round. Interestingly, the maximum cooperation level is achieved exactly on the transition line between the cooperative and the defective periodic orbits, which coincides with the edge of bistability. This aligns with some arguments that being on the edge of bistability can be beneficial for biological systems \cite{Salahshour}. Finally, the level of cooperation in the second PGG is plotted in Fig. \ref{fig5}(d). Here, it can be seen the cooperation increases by increasing $r_2$. On the other hand, as we have seen in Fig. \ref{fig1}, in the reward dilemma model, cooperation in the second game is maximized in an intermediate value of $r_2$. This contrast can be argued to result from competition between the two cooperative and defective PGGs, such that evolution favors the more cooperative one. Consequently, if individuals in one of the two cooperative or defective PGGs start to defect, the other more cooperative one is favored by evolution. This, in turn, shows that a potential reward to defection, by promoting competition, can have a surprisingly positive impact on the evolution of cooperation in an assortative context. \section*{Discussion} The fact that individuals consistently show cooperative or defective strategies had been noticed in public goods experiments \cite{Fischbacher1,Fischbacher2,Burlando,Chaudhuri}, and in many animal populations \cite{Bergmuller}. It is argued this persistent personality differences can partly explain why cooperation is observed in laboratory experiments and many human and animal societies \cite{Bergmuller,Fischbacher1,Fischbacher2,Burlando,Chaudhuri}. However, while some theoretical work had shed light on the evolution of some aspects of personality differences, such as the evolution of responsive and unresponsive personalities\cite{Wolf2}, risk-averse and risk-taking personalities \cite{Weissing}, or personality differences in leadership \cite{Johnstone}, the evolution of cooperative and defective personalities had alluded theoretical understanding. Our findings address this gap by showing how such consistent personality differences can evolve naturally in an evolutionary process when individuals need to work collectively to solve a social dilemma. Importantly, as the analysis of the model shows, the evolution of consistent personalities, in turn, helps solving social dilemmas by increasing the likelihood that the benefit of a cooperative act is reaped by those who behave cooperatively. In this regard, the evolution and maintenance of consistent cooperative and defective personalities can be regarded as an important mechanism at work in promoting cooperation in biological populations. An interesting question is that why consistent personality differences evolve in an assortative context? The key to the question is that entering the cooperative PGG in the second round is costly, while entering the defective PGG is costless. As it has been shown recently, an entrance cost for a PGG can promote cooperation in a costly PGG, due to the smaller effective size of a costly PGG \cite{Salahshour2021A}. For this reason, cooperation is more frequent and defection less frequent in the cooperative, costly PGG, compared to the defective, cost-less PGG. This phenomenon naturally leads to the evolution of consistent cooperative and defective personalities in an assortative context. Our analysis also reveals new roads to the evolution of cooperation. In this regard, as the analysis of the reward dilemma model shows, a population of self-interested agents can successfully solve a reward dilemma and this, in turn, helps to solve the social dilemma. This mechanism can be at work to promote cooperation in a context where cooperation increases an individual's chance of having more social interaction, even if actually benefiting from those interactions requires solving another social dilemma. The second scenario model, on the other hand, shows cooperation still evolves when defection is rewarded by a promise of future interaction as well, provided an assortative mechanism is at work. In other words, just as prosocial reward is stable against antisocial reward \cite{Attila}, a prosocial reward dilemma is competitively stable in promoting cooperation in the presence of an anti-social reward dilemma. In the presence of both prosocial and antisocial reward dilemmas, competition between the prosocial and anti-social public goods maintains cooperation in the system, and moreover, surprisingly increase cooperation in the second round, compared to a case where such competition is lacking. This shows a potential reward to defection, by fostering competition, can have a surprisingly positive impact in promoting cooperation. \section*{Methods} \label{Methods} \subsection*{Replicator dynamics} The model can be described in terms of replicator-mutation equations \cite{Nowak3}, which provide an exact description of the model in infinite population limit. These equations can be written as follows: \begin{align} \rho_{xy}(t+1)=\sum_{x',y'}\nu_{xy}^{x'y'}\rho_{x'y'}(t)\frac{\pi_{x'y'}(t)}{\sum_{x'',y''}\rho_{x''y''}(t)\pi_{x''y''}(t)}. \label{eqrepMmain} \end{align} Here, $xy$ (as well as $x'y'$ and $x''y''$) refer to the strategies of the individuals, such that $x$ is the strategy of an individual in the first round, and $y$ is its strategy in the second round. $x$, $x'$ etc. can be either cooperation $C$ or defection $D$. $\nu_{xy}^{x'y'}$ is the mutation rate from the strategy $x'y'$ to the strategy $xy$. These can be written in terms of mutation rate $\nu$ as follows: \begin{align} \begin{cases} \nu_{xy}^{x'y'}=1-2\nu+\nu^2 \quad &\textit{if\quad ($x=x'$ \quad and \quad $y=y'$)},\\ \nu_{xy}^{x'y'}=\nu-\nu^2 \quad&\textit{if\quad ($x\neq x'$ \quad and \quad $y=y'$)\quad or \quad ($x=x'$ \quad and \quad $y\neq y'$)}, \\ \nu_{xy}^{x'y'}=\nu^2\quad& \textit{if\quad ($x\neq x'$\quad and \quad$y \neq y'$)}. \end{cases} \end{align} In eq. (\ref{eqrepMmain}), $\pi_{x'y'}$ is the expected payoff of an individuals with strategy $x'y'$. In the case of the first scenario, these are given by the following equations: \begin{align} \pi_{C_1C_2}=&\sum_{n_{D_1C_2}=0}^{g-1-n_{C_1C_2}-n_{C_1D_2}}\sum_{n_{C_1D_2}=0}^{g-1-n_{C_1C_2}}\sum_{n_{C_1C_2}=0}^{g-1}\bigg[cr_1\frac{1+n_{C_1}}{g} +cr_2\frac{1+n_{C_1C_2}}{1+n_{C_1}}\bigg]{\rho_{C_1C_2}}^{n_{C_1C_2}}{\rho_{C_1D_2}}^{n_{C_1D_2}}{\rho_{D_1C_2}}^{n_{D_1C_2}}\nonumber\\&{\rho_{D_1D_2}}^{g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}\binom{g-1}{n_{C_1C_2},n_{C_1D_2},n_{D_1C_2},g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}-2c+\pi_0,\nonumber\\ \pi_{C_1D_2}=&\sum_{n_{D_1C_2}=0}^{g-1-n_{C_1C_2}-n_{C_1D_2}}\sum_{n_{C_1D_2}=0}^{g-1-n_{C_1C_2}}\sum_{n_{C_1C_2}=0}^{g-1}\bigg[cr_1\frac{1+n_{C_1}}{g} +cr_2\frac{n_{C_1C_2}}{1+n_{C_1}}\bigg]{\rho_{C_1C_2}}^{n_{C_1C_2}}{\rho_{C_1D_2}}^{n_{C_1D_2}}{\rho_{D_1C_2}}^{n_{D_1C_2}}\nonumber\\&{\rho_{D_1D_2}}^{g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}\binom{g-1}{n_{C_1C_2},n_{C_1D_2},n_{D_1C_2},g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}-c+\pi_0,\nonumber\\ \pi_{D_1C_2}=&\sum_{n_{D_1C_2}=0}^{g-1-n_{C_1C_2}-n_{C_1D_2}}\sum_{n_{C_1D_2}=0}^{g-1-n_{C_1C_2}}\sum_{n_{C_1C_2}=0}^{g-1}\bigg[cr_1\frac{n_{C_1}}{g} \bigg]{\rho_{C_1C_2}}^{n_{C_1C_2}}{\rho_{C_1D_2}}^{n_{C_1D_2}}{\rho_{D_1C_2}}^{n_{D_1C_2}}\nonumber\\&{\rho_{D_1D_2}}^{g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}\binom{g-1}{n_{C_1C_2},n_{C_1D_2},n_{D_1C_2},g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}+\pi_0,\nonumber\\ \pi_{D_1D_2}=&\sum_{n_{D_1C_2}=0}^{g-1-n_{C_1C_2}-n_{C_1D_2}}\sum_{n_{C_1D_2}=0}^{g-1-n_{C_1C_2}}\sum_{n_{C_1C_2}=0}^{g-1}\bigg[cr_1\frac{n_{C_1}}{g} \bigg]{\rho_{C_1C_2}}^{n_{C_1C_2}}{\rho_{C_1D_2}}^{n_{C_1D_2}}{\rho_{D_1C_2}}^{n_{D_1C_2}}\nonumber\\&{\rho_{D_1D_2}}^{g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}\binom{g-1}{n_{C_1C_2},n_{C_1D_2},n_{D_1C_2},g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}+\pi_0. \label{eqscenario1Mmain} \end{align} Here, we have $n_{C_1}=n_{C_1C_2}+n_{C_1D_2}$. To write these equations, I used the fact that in a group with $n_{C_1C_2}$ individuals with strategy ${C_1C_2}$, and $n_{C_1D_2}$ individuals with strategy ${C_1D_2}$, $r_1\frac{1+n_{C_1}}{g}-c$ and $r_1\frac{n_{C_1}}{g}$ are, respectively, the expected payoff of an individual who cooperates, defects, in the first game. Those who defect in the first game do not gather payoff from the second game. On the other hand, those who cooperate in the first game, obtain a payoff from the second game as well (which can be negative or positive). This is $r_2\frac{1+n_{C_1C_2}}{1+n_{C_1}}-c$ for an individual with strategy $C_1C_2$, and $r_2\frac{n_{C_1C_2}}{1+n_{C_1}}$ for an individual with strategy $C_1D_2$. Finally, ${\rho_{C_1C_2}}^{n_{C_1C_2}}{\rho_{C_1D_2}}^{n_{C_1D_2}}{\rho_{D_1C_2}}^{n_{D_1C_2}}$ ${\rho_{D_1D_2}}^{g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}\binom{g-1}{n_{C_1C_2},n_{C_1D_2},n_{D_1D_2},g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}$, is the probability that a focal individual finds itself in a group with $n_{C_1C_2}$, $n_{C_1D_2}$, $n_{D_1C_2}$, and $n_{D_1D_2}$ individuals with, respectively, strategies $C_1C_2$, $C_1D_2$, $D_1C_2$, and $D_1D_2$. Here, $\binom{g-1}{n_{C_1C_2},n_{C_1D_2},n_{D_1D_2},g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}$ is the multinational coefficients (that is the number of ways that among the $g-1$ group mates of a focal individual, $n_{C_1C_2}$, $n_{C_1D_2}$, $n_{D_1C_2}$, $g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}$ individuals have strategies, respectively, $C_1C_2$, $C_1D_2$, $D_1C_2$, and $D_1D_2$). Summation over all the possible configurations gives the expected payoff of the focal individual with the given strategy from the games. Finally, as all the individuals receive a base payoff $\pi_0$, this is added to the total payoff. Using the expressions in eq. (\ref{eqscenario1Mmain}) for the expected payoff of different strategies in eq. (\ref{eqrepMmain}), I have a set of four equations which gives an analytical description of the model, in the limit of infinite population size. In the same way, it is possible to write down equations for the expected payoffs of individuals with different strategies in the second scenario. The difference with the preceding scenario is that, in the second scenario those who defect in the first round proceed to a second PGG as well. Thus, under the same notation and conventions as before, the individuals with strategies $D_1C_2$ and $D_1D_2$, obtain a payoff of, respectively, $r_2\frac{1+n_{D_1C_2}}{1+n_{D_1}}-c$ and $r_2\frac{n_{D_1C_2}}{1+n_{D_1}}$, from their second game. Here, $n_{D_1}=n_{D_1C_1}+n_{D_1D_2}$. Thus, we have for the expected payoffs of different strategies in the second scenario: \begin{align} \pi_{C_1C_2}=&\sum_{n_{D_1C_2}=0}^{g-1-n_{C_1C_2}-n_{C_1D_2}}\sum_{n_{C_1D_2}=0}^{g-1-n_{C_1C_2}}\sum_{n_{C_1C_2}=0}^{g-1}\bigg[cr_1\frac{1+n_{C_1}}{g} +cr_2\frac{1+n_{C_1C_2}}{1+n_{C_1}}\bigg]{\rho_{C_1C_2}}^{n_{C_1C_2}}{\rho_{C_1D_2}}^{n_{C_1D_2}}{\rho_{D_1C_2}}^{n_{D_1C_2}}\nonumber\\&{\rho_{D_1D_2}}^{g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}\binom{g-1}{n_{C_1C_2},n_{C_1D_2},n_{D_1C_2},g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}-2c+\pi_0,\nonumber\\ \pi_{C_1D_2}=&\sum_{n_{D_1C_2}=0}^{g-1-n_{C_1C_2}-n_{C_1D_2}}\sum_{n_{C_1D_2}=0}^{g-1-n_{C_1C_2}}\sum_{n_{C_1C_2}=0}^{g-1}\bigg[cr_1\frac{1+n_{C_1}}{g} +cr_2\frac{n_{C_1C_2}}{1+n_{C_1}}\bigg]{\rho_{C_1C_2}}^{n_{C_1C_2}}{\rho_{C_1D_2}}^{n_{C_1D_2}}{\rho_{D_1C_2}}^{n_{D_1C_2}}\nonumber\\&{\rho_{D_1D_2}}^{g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}\binom{g-1}{n_{C_1C_2},n_{C_1D_2},n_{D_1C_2},g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}-c+\pi_0,\nonumber\\ \pi_{D_1C_2}=&\sum_{n_{D_1C_2}=0}^{g-1-n_{C_1C_2}-n_{C_1D_2}}\sum_{n_{C_1D_2}=0}^{g-1-n_{C_1C_2}}\sum_{n_{C_1C_2}=0}^{g-1}\bigg[cr_1\frac{n_{C_1}}{g} +cr_2\frac{1+n_{D_1C_2}}{1+n_{D_1}}\bigg]{\rho_{C_1C_2}}^{n_{C_1C_2}}{\rho_{C_1D_2}}^{n_{C_1D_2}}{\rho_{D_1C_2}}^{n_{D_1C_2}}\nonumber\\&{\rho_{D_1D_2}}^{g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}\binom{g-1}{n_{C_1C_2},n_{C_1D_2},n_{D_1C_2},g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}-c+\pi_0,\nonumber \end{align} \begin{align} \pi_{D_1D_2}=&\sum_{n_{D_1C_2}=0}^{g-1-n_{C_1C_2}-n_{C_1D_2}}\sum_{n_{C_1D_2}=0}^{g-1-n_{C_1C_2}}\sum_{n_{C_1C_2}=0}^{g-1}\bigg[cr_1\frac{n_{C_1}}{g} +cr_2\frac{n_{D_1C_2}}{1+n_{D_1}}\bigg]{\rho_{C_1C_2}}^{n_{C_1C_2}}{\rho_{C_1D_2}}^{n_{C_1D_2}}{\rho_{D_1C_2}}^{n_{D_1C_2}}\nonumber\\&{\rho_{D_1D_2}}^{g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}\binom{g-1}{n_{C_1C_2},n_{C_1D_2},n_{D_1C_2},g-1-n_{C_1C_2}-n_{C_1D_2}-n_{D_1C_2}}+\pi_0. \end{align} Using these expressions for the expected payoffs of individuals with different strategies in eq. (\ref{eqrepMmain}), we have the analytical description of the second scenario model, in the limit of infinite population size. \subsection*{The simulations and numerical solutions} Numerical solutions of the replicator dynamics result from numerically solving the replicator dynamics of the models derived in the Methods section. Simulations of the models are performed according to the model definition. Unless otherwise stated, both the simulations and numerical solutions of the replicator dynamics are performed with an initial condition in which all the strategies are found in similar frequencies in the population pool. For the solutions of the replicator dynamics, this is assured by setting the initial frequency of all the four strategies equal to $1/4$. For simulations, this is assured by a random assignment of the strategies. The phase diagram presented in Fig. \ref{fig5}(a) is derived by locating the parameter values where a transition between different attractors occurs starting from a homogeneous initial condition. The boundary of bistability in Fig. \ref{fig5}(a) is derived by examining history dependence and checking for the existence of hysteresis in the evolution of the system. That is, the replicator dynamics are solved starting from parameter values belonging to different phases. Then, the parameter values are changed in small steps, using the stationary state of the preceding steps as the initial condition for the solution of the replicator dynamics in the next step. In this way, the boundary of bistability beyond which a solution becomes unstable is found. See the Supplementary Information for more details.
{'timestamp': '2022-01-14T02:24:58', 'yymm': '2010', 'arxiv_id': '2010.05307', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05307'}
arxiv
\section{Introduction} Attention layers enable long-range representation learning and are becoming indispensable in architectures for both Image Synthesis~\cite{biggan, sagan, daras2019local} and Natural Language Processing~\cite{albert, yang2019xlnet, devlin2018bert, dai2019transformer, t5, liu2019roberta}. Attention finds further uses in other domains like symbolic mathematics and music modeling as well ~\cite{MATHTRANSFORMER, musictransformer, child2019generating}. Unfortunately, attention layers have high computational and memory cost which scales quadratically in the size of the input sequence. This constraint is so onerous that the canonical implementation of attention for image synthesis - Self-Attention GAN~\cite{sagan} - could only afford to use one self-attention layer. For NLP, modern transformer-based models can only be trained in large industry research labs with massive infrastructure investments. For instance, the recently published GPT-3~\cite{GPT3} model uses $96$ attention layers trained on input sequences of $2048$ tokens. When fine-tuning pre-trained attention models, NLP researchers usually truncate input sentences, limiting performance on datasets with longer inputs. Recent research~\cite{show_attend_and_tell, daras2019local} indicates that dense attention is statistically and computationally inefficient~\cite{Voita_2019, michel2019sixteen, daras2019local}: it does not account for the locality inherent in many tasks. Alternatives have been proposed that are either more efficient~\cite{child2019generating, adaptively_sparse_transformers, reformer, routing_transformer, sinkhorn, dai2019transformer, lample2019large, star_transformer} or that better accommodate locality ~\cite{localattn, daras2019local}. Most such alternatives have been sparse. Sparsity can be achieved by limiting attention to pre-defined positions~\cite{localattn, daras2019local, star_transformer, child2019generating}. Recent work~\cite{adaptively_sparse_transformers, reformer, routing_transformer, sinkhorn} proposes data-driven sparsity, which allows for discovery of arbitrarily complex dependencies between input positions. Despite this progress, new state-of-the-art models~\cite{t5, GPT3, liu2019roberta, clark2020electra, GLUE, superglue} still use the original dense attention layers. There are three reasons for this: (i) alternative fast-attention mechanisms degrade the performance of the underlying model. For example, replacing dense attention layers in Transformers with memory efficient local attention~\cite{localattn} increases perplexity from $41.57$ to $44.23$ \cite{sinkhorn}. (ii) some mechanisms work well, but make very strict assumptions. For example, in Star Transformer~\cite{star_transformer} all nodes attend to a relay node which summarizes the content of the entire input sequence, but this prevents the use of causal masking, so it can only be used for encoding. (iii) some alternatives are only efficient in theory. For example, in some variants \cite{adaptively_sparse_transformers, Malaviya_2018} sparsification of the attention map happens after instantiating the matrix, and so quadratic memory is still used before instantiation. Finally, ~\cite{child2019generating, beltagy2020longformer} require highly specialized GPU-kernels and which prevents usage in several hardware settings (e.g. TPUs). The design of fast and efficient attention layers remains a challenge. \noindent \textbf{Our Contributions:} \\ \textbf{1)} We propose a novel type of balanced clustering to approximate attention. We call the underlying optimization problem Attention Biclustering and prove that finding an exact solution is computationally intractable.\\ \textbf{2)} We propose an algorithm for solving Attention Biclustering efficiently in practice. Our algorithm, SMYRF, uses Locality Sensitive Hashing (LSH) in a novel way by defining new Asymmetric transformations and an adaptive scheme that produces balanced clusters. \\ \textbf{3)} Our method, SMYRF, can handle different query and key vectors, just like normal dense attention. As a result, SMYRF layers are drop-in replacements for pre-trained models, unlike previously proposed fast-attention mechanisms such as Sinkhorn~\cite{sinkhorn}, Reformer~\cite{reformer} and Routing Transformer~\cite{routing_transformer}.\\ \textbf{4)} We show through numerous experiments that SMYRF attention layers are very effective in terms of performance, memory and speed, even without any training. We measure the memory-performance trade-off of applying SMYRF to state-of-the-art NLP and Computer Vision models, across more than a dozen tasks. For example, we are able to shrink the memory requirements of a pre-trained BigGAN~\cite{biggan} by $50\%$ while maintaining $98.2\%$ of its Inception score without re-training. \\ \textbf{5)} We finetune SMYRF on GLUE~\cite{GLUE} starting from a BERT (base) checkpoint. We demonstrate that SMYRF-BERT outperforms BERT while using $50\%$ less memory. We also show that with $75\%$ less memory, SMYRF maintains $99\%$ of BERT performance on GLUE. Due to SMYRF's portability, we are also able to conduct experiments for various memory configurations with pre-trained BERT and RoBERTa~\cite{liu2019roberta} models on IMDB. We show slight performance drops for great memory benefits. \\ \textbf{6)} We show that SMYRF can be interchanged with dense layers \textit{before} and \textit{after} training. We report performance gains by using SMYRF in a back-and-forth manner: we replace dense with SMYRF during training (to earn in memory) and we replace SMYRF with dense attention during inference (to earn in performance). The interchangeability of SMYRF with dense attention is unique, as it has not been observed in previously proposed attention alternatives~\cite{reformer, routing_transformer, sinkhorn, beltagy2020longformer, daras2019local}. \\ \textbf{7)} We are able to scale the resolution of attention for GANs, due to our reduced memory footprint. We train a BigGAN with an $128 \times 128$ SMYRF attention layer and show it outperforms the dense attention performance, decreasing FID from $26.06$ to $25.03$ in Celeba-HQ-128~\cite{celeba}. Finally, we successfully train a BigGAN with attention at resolution $256\times 256$ on a single v3-8 TPU. \\ \textbf{8)} We open-source our code and pre-trained models to encourage more related research: \href{https://github.com/giannisdaras/smyrf}{https://github.com/giannisdaras/smyrf}. \section{Background} Attention~\cite{vaswani2017attention} works by computing inner products of query and key vectors. Depending on the application, these vectors may represent embeddings for tokens or image pixels. Input of each attention layer is three sets: $\mathcal Q, \mathcal K, \mathcal V$ for query, key and value vectors respectively. Attention of $q$ to the keys set $\mathcal K$ outputs a new vector $o_q$ , which is a weighted sum of value vectors $v_i \in \mathcal V$ where each weight $w_i$ increases with the inner product $q \cdot k_i$. Specifically, the output is computed as: \begin{equation} o_q = \sum_{i=1}^{N} w_i v_i, \qquad w_i = \frac{e^{q \cdot k_i}}{\sum_{j=1}^{N} e^{q \cdot k_j}}. \label{dense} \end{equation} Here, we assumed for notational simplicity that $N = |\mathcal Q| = |\mathcal K|$. Using matrix notation, attention is equivalently defined as $\sigma(Q \cdot K^T) \cdot V$ where $Q, K, V$ are matrices with rows the embeddings for each query, key, value and the function $\sigma(.)$ computes the row-wise softmax. \section{Approximating Attention with Clustering} \subsection{Motivation} Our method is motivated by the observation that attention matrices have interesting structure in real datasets. Naively, to compute dense attention, as equation \ref{dense} shows, we need to compute all outputs $o_{q_i}$, i.e. $O(|\mathcal Q| \cdot |\mathcal K|)$, a quadratic number of inner products $q_i \cdot k_j, \ q_i \in \mathcal Q, \ k_j \in \mathcal K$. However, we observe that in most real networks, the attention weights $w_i$ are sparse, because of the softmax operation and the structure of the vectors. For example we observe that in a pre-trained BigGAN on ImageNet, on average $\bm {98.11 \pm 0.26 \%}$\footnote{The reported numbers are calculated by inspecting the attention maps of 1000 random generated images.} of keys get weight less than $0.01$ in softmax and $\bm {86.11 \pm 2.92 \%}$ of them get less than $\frac{1}{|\mathcal K|}$, where $\mathcal K$ is the number of keys. Further, we observe that the attention matrix is near low-rank, even after the softmax. By definition, the matrix $Q \cdot K^T$ is going to be of rank at most the dimension of the query and key vectors. Therefore, if the embeddings dimension is smaller than the input sequence, the attention matrix is low-rank. This is more pronounced for images and long-context language models. However, one can easily construct cases of low-rank matrices which become full rank after softmax. Our finding is that this does not happen in practice. In the Appendix we show that \textit{real attention matrices of pretrained models have a sharp decay in their singular values and hence can be well approximated by low-rank matrices}. SMYRF benefits from sparsity and low-rank structure of attention matrices. By clustering keys and queries into groups, we obtain block-diagonal structure in the approximate attention matrix, since only query-key pairs within the same cluster are computed. We show that this method leads to accurate approximations of dense attention and it can be computed much faster and with much less memory. \subsection{Problem Formulation} We formulate the assignment of keys and queries into clusters as an optimization problem. Denote with $P_{ij} = q_i^T k_j$ the element $(i, j)$ of the product matrix $P = Q \cdot K^T$ and the attention map with $M = \sigma(Q \cdot K^T)$. We will assign query and key vectors into $L$ clusters $c_1, c_2, ..., c_L$ and compute attention only within each cluster. For fast execution on TPUs/GPUs, all partial attentions should be computed in parallel. For this reason, we require that clusters are balanced: i.e. all clusters contain the same number of keys and queries. We note that the number of keys in each cluster does not have to be equal to the number of queries. Formally, each cluster contains $\frac{|\mathcal Q|}{L}$ queries and $\frac{|\mathcal K|}{L}$ keys. We denote with $\mathcal C^L$ the set of all possible assignments in $L$ balanced non-overlapping clusters. A specific assignment is denoted by $\mathcal C^L_t$ and there are $T$ possible such assignments, where $T$ is exponentially large in the number of keys and queries. $$ \mathcal C^L = \{\mathcal C_1^L, C_2^L, ... \mathcal C_T^L\}. $$ \begin{equation} \mathcal C_t^L=\{c_1, c_2, ..., c_L\}: \quad \begin{cases} c_i = \{q_1, ..., q_{\frac{|\mathcal Q|}{L}}, k_1, ..., k_\frac{|\mathcal K|}{L}\}, \quad c_i \subseteq \mathcal Q \cup \mathcal K, \ \ \forall i\in \{1, ..., L\} \\ c_x \cap c_y = \varnothing \quad \forall c_x, c_y \in \mathcal C_t^L. \end{cases} \label{balanced} \end{equation} We emphasize that every key and query is assigned in a unique cluster for any valid assignment $\mathcal C^L_t$: $c_x \cap c_y = \varnothing \quad \forall c_x, c_y \in \mathcal C_t^L.$ We also define a masking operator $\textrm{Mask}_\epsilon$ that takes as input: (i) a clustering $\mathcal C_t^L \in \mathcal C^L$ and (ii) the product matrix $P$ and replaces $(q, k)$ pairs that are not in the same cluster with $-a$, where $a \in \mathbb R^{+}$ is a constant chosen to satisfy $e^{-a} = \epsilon$ for a given $\epsilon \geq 0$. Formally: $$ \textrm{Mask}_\epsilon(\mathcal C_t^L, P_{ij}) = \begin{cases} P_{ij} \quad \textrm{iff } \exists t: (i, j) \in c_t, \\ -a, \quad \textrm{o/w}. \end{cases} $$ Intuitively, the masking operator replaces inner products of queries and keys that are not in the same cluster with an arbitrarily small number, so that the softmax will assign a score arbitrarily close to zero to these entries. We denote with $\hat P_\epsilon=\textrm{Mask}_\epsilon(\mathcal C_t^L, P)$ the product matrix after the masking. With this notation, $\hat P_0 = \textrm{Mask}_{0}( \mathcal C_t^L, P)$, is the product matrix for the within-clusters attention. \noindent \textbf{Attention Biclustering:} Under this formulation, we are searching for the cluster assignment $\mathcal{C}^L_t$ that approximates the dense attention matrix $\sigma(P)$ as well as possible, in Frobenius norm: \begin{equation} \min_{\mathcal C_t^L \in \mathcal C^L} || \sigma(\hat P_0)- \sigma(P)||_F. \label{min_problem} \end{equation} Note that $L$ must divide the number of queries and keys for this problem to be well-defined. \subsection{Complexity of Attention Biclustering} We start by showing that Attention Biclustering, the optimization problem defined in (\ref{min_problem}), is provably computationally intractable. \begin{theorem} Attention Biclustering (\ref{min_problem}) is NP-hard. \label{main_theorem} \end{theorem} We defer the proof of this theorem to the Appendix. Our proof proceeds by first establishing hardness before the softmax, using a reduction from three dimensional matching~\cite{gary}. We then leverage this to establish hardness of approximating attention through clustering after the softmax operation. We consider it interesting to establish the computational intractability of Attention Biclustering, since this clustering formulation is quite unique due to the softmax operation. Our hardness result rules out an exact polynomial solution, unless P=NP. We propose an efficient algorithm that leverages hashing to assign queries and keys to clusters. Formally proving an approximation guarantee or provable inapproximability for the attention approximation problem we proposed remains open. \subsection{Proposed algorithm: SMYRF} Our algorithm consists of the following steps:\\ \textbf{1)} We first propose novel asymmetric transformations $F, G: \mathbb R^{d} \to \mathbb R^{d'}$ such that for all given queries $q_1, q_2 \in \mathcal Q$ and keys $k \in \mathcal K$: $q_1 \cdot k \leq q_2 \cdot k \iff ||F(q_1) - G(k)||_2 \leq ||F(q_2) - G(k)||_2$. \\ \textbf{2)} We then use a Locality Sensitive Hashing (LSH) function $h:\mathbb R^{d'}\to \mathbb R$ to map transformed vectors in real numbers, so that that vectors that are close in Euclidean distance correspond to numbers that are close on the real line. \\ \textbf{3)} We sort vectors based on their LSH value and group them by adapting the thresholds to ensure $L$ balanced clusters. \\ \textbf{4)} We perform dense attention within each cluster. Our approximate attention algorithm relies on a few technical innovations: \noindent \textbf{Novel Asymmetric Transformations:} We need an efficient way to find, for any given query vector $q_i \in \mathcal Q$ the set of keys with which it has big inner products. This problem, called Maximum Inner Product Search (MIPS), can be efficiently solved by transforming query and key vectors to convert it to a Nearest Neighbor Search (NNS) as proposed in the pioneering Asymmetric LSH (Locality Sensitive Hashing) work by Shrivastava et al.~\cite{l2lsh}. We are looking for functions $F: \mathbb R^{d}\to \mathbb R^{d'}, G: \mathbb R^d \to \mathbb R^{d'}$ such as: $||F(q) - G(k)||_2^2 = D(q\cdot k), \ \forall (q, k)$ where $D:\mathbb R \to \mathbb R$ a decreasing function that depends only on the inner product $q\cdot k$. We constrain our focus on functions $D$ that decrease linearly with the inner product $q\cdot k$. Several previous works have proposed Asymmetric LSH transformations~\cite{l2lsh,xbox,h2lsh} but focus on the case where we have a \textit{single query} $q$ and multiple keys. In that case, any norm $||q||_a$ where $a=\{1, ..., \infty\}$ is constant and thus $D = D(q\cdot k, ||q||_a)$. Our central algorithmic contribution is the proposal of novel asymmetric functions: \begin{equation} F(q_i) = \left[q_i; 0; \sqrt{M_Q^2 + M_K^2 - ||q_i||_2^2} \right], \qquad G(k_i) = \left[k_i; \sqrt{M_Q^2 + M_K^2 - ||k_i||_2^2}; 0\right] \end{equation} where we use the constants $M_Q = \max_{q_i}||q_i||_2, \quad M_K = \max_{k_i}||k_i||_2$, or any other upper bound on the norms. With this transformation, all queries and keys are mapped to a $(d+2)$-dimensional ball with radius $\sqrt{M_Q^2 + M_K^2}$ and the distance of the transformed vectors decreases linearly with the inner product of the original vectors: \begin{equation} ||F(q_i) - G(k_i)||_2^2 = 2 \cdot \left( M_Q^2 + M_K^2 - q_i\cdot k_i\right). \end{equation} Note that the Euclidean distance of the transformed vectors depends only on the inner product of the original vectors and not on individual norms $||q_i||_2$ as in previous work~\cite{e2lsh, h2lsh, xbox}. We include details of comparison to the numerous prior asymmetric transformations in the Appendix. \noindent \textbf{Adaptive Clustering:} The final step of SMYRF is to use the hashed values to create \textit{balanced} clusters. These are created by forming balanced hash buckets where every group is assigned the same number of query and key vectors. We modify the E2LSH~\cite{e2lsh} hashes to create balanced clusters as follows: Instead of rounding the E2LSH to an integer value as in~\cite{e2lsh}, we adaptively set the boundaries of the $1$-d hashed space to ensure the same number of query and key vectors per interval. Computationally wise, this only requires sorting the hashes. We explain the mathematical details of our adaptive clustering scheme and the differences with E2LSH in the Appendix. \noindent \textbf{Computational Complexity and speedups:} For notational simplicity we assume $|\mathcal Q| = |\mathcal K| = N$. The total time and memory complexity of SMYRF is $O\left(H \cdot N \cdot \log N + H \cdot \frac{N^2}{L}\right)$, where: $H$ denotes hashing rounds, $N$ number of query/key vectors and $L$ number of clusters. For most of our experiments we choose $L = O(N), \ H=O(1)$, and thus complexity is $O(N\log N)$. Even though we obtain optimal complexity for $L=O(N), \ H=O(1)$, both $L, H$ are parameters that can be tuned to satisfy the desired memory-performance trade-off. Regarding speed, SMYRF accelerates a lot attention as sequence length increases. For example, for sequence length 2048, SMYRF-BERT offers $\approx 20\%$ speedup, while for $4096$ speedup increases to $\approx 50\%$. We include detailed speed plots for applying SMYRF to BERT in the Appendix. \section{Experiments} \subsection{Pre-trained models} We first illustrate that SMYRF is an excellent drop-in replacement for pre-trained dense attention. We show significant memory benefits for relatively small performance drop, \textit{with no training at all}. We use a pre-trained\footnote{Since BigGAN's official checkpoints are not publicly available, we use the authors' open-source, PyTorch~\cite{paszke2019pytorch} pre-trained models: https://github.com/ajbrock/BigGAN-PyTorch } BigGAN, which is a state-of-the-art model in Image Generation for ImageNet~\cite{ImageNet}. BigGAN has a single attention layer at resolution $64\times64$ (4096 queries). We replace BigGAN's dense attention with a SMYRF layer at the same resolution, with no other modifications. Figure \ref{image_quality} illustrates images generated by SMYRF-BigGAN for different memory savings, ranging from $99.44\%$ (first column) to $50\%$ (one to last column). Last column shows generated images using the dense attention layer ($100\%$ memory). As shown, SMYRF enables a new tradeoff in the design space. We can drastically reduce attention memory by $93.75\%$ with a small degradation or select any other point in this tradeoff depending on hardware specifications. We report a few Inception~\cite{inception_score} and FID~\cite{FID} scores for different memory savings in Table \ref{biggan_pretrained}. We emphasize that no further modification was made to this model other than replacing the attention layer. By shrinking $50\%$ the memory requirements of attention, SMYRF maintains $98.2\%$ of Inception performance without any training. In the Appendix, we also include visualizations of clustering assignments in real-world images. \begin{figure}[!htp] \begin{minipage}{0.69\textwidth} \includegraphics[width=8cm]{figs/quality_degradation.png} \captionof{figure}{\small Images generated by SMYRF-BigGAN. \\ The model is initialized with the weights of a pre-trained BigGAN \\ on ImageNet (no further training). \\ We show images for memory reduction ranging from $98.44\%$ \\ (first column) to $50\%$ (one to last column). \\ Last column shows generated images by BigGAN with dense attention.} \label{image_quality} \end{minipage} \begin{minipage}{0.30\textwidth} \includegraphics[width=5cm]{smyrf_128res.jpg} \caption{\small Generated images from SMYRF-BigGAN on Celeba-HQ-128. Attention at $128\times128$. The trained model uses $50\%$ less memory compared to original BigGAN.} \label{gen128} \end{minipage} \end{figure} \begin{table}[!htp] \begin{center} \begin{tabular}{l|l|l|l|l|l} & Memory & Rounds & $C$ & Inception & FID \\ \hline BigGAN & \multirow{1}{4em}{$100\%$} & 1 & 4096 & $\bm{93.79 \pm 1.96}$ & 11.30 \\ \hline \multirow{9}{4em}{SMYRF-BigGAN} & \multirow{3}{4em}{50\%} & 32 & 64 & $91.91 \pm 2.65$ & $12.18$ \\ & & 64 & 32 & $\bm{92.09 \pm 1.83}$ & $12.18$ \\ & & 128 & 16 & $91.59 \pm 1.83$ & $\bm{12.10}$ \\ \cline{2-6} & \multirow{3}{4em}{$25\%$} & 32 & 32 & $87.90 \pm 1.90$ & $13.34$ \\ & & 64 & 16 & $88.45 \pm 1.70 $& $13.45$ \\ & & 128 & 8 & $\bm{89.61 \pm 1.63}$ & $\bm{13.19}$ \\ \cline{2-6} & \multirow{3}{4em}{$12.5\%$} & 32 & 16 & $81.67 \pm 1.97$ & 16.08 \\ & & 64 & 8 & $\bm{82.87 \pm 1.82}$ & $\bm{16.00}$ \\ & & 128 & 4 & $82.10 \pm 2.06$ & $16.03$ \\ \bottomrule \end{tabular} \end{center} \caption{Effect of SMYRF attention approximation on a pre-trained BigGAN (with no training). Rounds denote the number of LSH hashes and $C$ the number of queries per cluster.} \label{biggan_pretrained} \end{table} \subsection{Finetuning pre-trained models} In this section, we \textit{finetune} pre-trained models with SMYRF. We show that finetuned SMYRF models, with $50\%$ memory reduction, can outperform dense attention. We also show that even with more aggressive memory-shrinking, up to $97\%$, SMYRF maintains a relatively good performance. We train SMYRF-BERT (base) on GLUE \cite{GLUE, sst, stsb, qqp, wnli, rte1, rte2, rte3, rte4, mrpc, cola, squad, N18-1101} benchmark, using sequence length 128. We compare the following five models: (i) BERT~\cite{devlin2018bert} (base), (ii) SMYRF-BERT (base) with $50\%$ memory reduction (2nd row), (iii) SMYRF-BERT (base) with $25\%$ memory reduction (3rd row), (iv) BERT (base) with input sequences truncated to $64$ tokens ($50\%$ memory reduction, 4th row), (v) BERT (base) with input sequences truncated to $32$ tokens ($25\%$ memory reduction, 5th row). We summarize results on Table \ref{glue_results}. Remarkably, SMYRF-BERT (slightly) \textbf{outperforms} original dense attention, while using $50\%$ less memory. We also underline that SMYRF-BERT with $25\%$ of original memory, maintains $\approx \bm{99\%}$ of original model performance, while the BERT-model that uses the same memory (last row) maintains only $\approx 89\%$. To demonstrate that SMYRF scales for larger models, we also run experimetns with \textbf{SMYRF-BERT large} to a subset of the GLUE tasks. Specifically, SMYRF-BERT large obtains $\mathbf{60.4\%}$ performance (Matthew's Correlation) in the CoLA task and $\mathbf{90.2\%}$ (accuracy) in the QQP task. Both scores are significantly improved compared to the scores of the SMYRF-BERT base model, which shows that the approach scales to models with more attention layers. The corresponding scores of BERT large are $60.5\%$ and $89.3\%$ which are on par with the SMYRF performance for that model. Since GLUE~\cite{GLUE} datasets contain mostly short inputs, we also experiment on the IMDB~\cite{IMDB} dataset, using sequence length $512$ tokens\footnote{Note that for fair comparison with dense attention, we train SMYRF layers and dense layers on the same sequence length, following the comparison scheme of Reformer~\cite{reformer}. As previous work has shown~\cite{beltagy2020longformer}, training on IMDB (and other long-input datasets) with bigger sequence length can help performance.}. We experiment with SMYRF-BERT (base) and we report results for various configurations (memory savings, hashing rounds and cluster size). To support our argument that our algorithm is a drop-in replacement to \textit{any} dense attention layer, we also include some results for RoBERTa~\cite{liu2019roberta} (base). Results are summarized in Table \ref{nlp_finetuning}. Notably, SMYRF-BERT maintains $97.2\%$ of dense attention performance for $87.5\%$ memory savings. In Table \ref{backandforth}, we provide results for a Back-and-Forth procedure: we finetune with SMYRF and then for inference we use dense attention. By doing that, we observe performance almost equivalent to training with dense attention, while saving computational resources with SMYRF training. This indicates interchangeability between SMYRF and dense attention, which has not been previously reported. We use it to to train in a memory efficient manner and obtain maximum final performance. \begin{table}[!htp] \begin{adjustbox}{width=\columnwidth, center} \begin{tabular}{l|l|l|l|l|l|l|l|l|l|l|l} & Avg. & $\#$ & $C$ & CoLA & MNLI-m/mm & MRPC & QNLI & QQP & RTE & SST-2 & STS-B \\ \hline BERT$_{128}$ & $82.69$ & 1 & 1 & 57.83 & $84.43/\bm{84.68}$ & $\bm{88.41}$ & $\bm{91.31}$ & 89.70 & 65.70 & $\bm{93.46}$ & $88.73$ \\ \hline \multirow{2}{4em}{SMYRF-BERT} & $\bm{83.12}$ & 2 & 32 & $58.79$ & \textbf{85.02}/84.27 & 87.69 & 91.14 & $\bm{89.72}$ & $\bm{68.59}$ & 93.23 & $\bm{89.65}$ \\ \cline{2-12} & $81.74$ & 2 & 16 & $\bm{58.90}$ & $82.86/83.49$ & $85.72$ & $89.53$ & $89.33$ & $64.98$ & $93.12$ & $87.75$ \\ \hline BERT$_{64}$ & $81.57$ & 1 & 64 & 58.80 & 82.34/82.47 & 87.02 & 90.48 & 89.69 & 61.73 & 93.00 & 88.64 \\ \hline BERT$_{32}$ & $73.56$ & 1 & 32 & $56.40$ & $64.51/63.41$ & $77.89$ & 79.81 & 88.59 & 55.23 & 92.66 & 83.53 \\ \bottomrule \end{tabular} \end{adjustbox} \caption{Results on GLUE~\cite{GLUE} (dev). $\#:$ hashing rounds. $C:$ the number of queries per cluster. SMYRF outperforms BERT while using $50\%$ less memory in each of the $12$ attention layers.} \label{glue_results} \end{table} \begin{table}[!htp] \begin{center} \begin{tabular}{l|l|l|l|l|l} & Dataset & Memory & Accuracy & Rounds & Cluster \\ \hline BERT & \multirow{8}{4em}{IMDB} & $100\%$ & $\bm{94.12\%}$ & 1 & 512 \\\cline{1-1} \cline{3-6} \multirow{5}{4em}{SMYRF-BERT} & & \multirow{1}{4em}{50\%} & $92.64\%$ & 8 & 32 \\ \cline{3-6} & & \multirow{1}{4em}{25\%} & $92.52\%$ & 16 & 8 \\ \cline{3-6} & & \multirow{1}{4em}{$12.5\%$} & $91.46$ & 8 & 8 \\ \cline{3-6} & & \multirow{1}{4em}{6.25\%} & $88.78\%$ & $8$ & $4$ \\ \cline{3-6} & & \multirow{1}{4em}{3.125\%} & $87.49\%$ & 4 & 4 \\ \cline{1-1} \cline{3-6} \multirow{1}{4em}{RoBERTa} & & $100\%$ & $\bm{94.96\%}$ & 1 & 512 \\ \cline{1-1} \cline{3-6} SMYRF-RoBERTa & & $50\%$ & $93.72$ & 8 & 32 \\ \bottomrule \end{tabular} \end{center} \caption{Finetuning BERT~\cite{devlin2018bert} (base) and RoBERTa~\cite{liu2019roberta} (base) on IMDB dataset for various configurations. For SMYRF models, we \textbf{train} and \textbf{evaluate} with SMYRF.} \label{nlp_finetuning} \end{table} \begin{table}[!htp] \centering \begin{tabular}{l|l|l|c|l} & Dataset & Memory & SMYRF Inference & Accuracy \\ \hline RoBERTa & \multirow{6}{4em}{IMDB} & $100\%$ & \ding{55} & $\bm{94.96\%}$ \\ \cline{1-1} \cline{3-5} \multirow{2}{4em}{SMYRF-RoBERTa} & & \multirow{2}{4em}{$50\%$} & \ding{55} & $93.72\%$ \\ & & & \checkmark & $\bm{94.62\%}$ \\ \cline{1-1} \cline{3-5} BERT & & $100\%$ & \ding{55} & $94.12\%$ \\ \cline{1-1} \cline{3-5} \multirow{2}{4em}{SMYRF-BERT} & & \multirow{2}{4em}{$50\%$} & \ding{55} & $92.64\%$ \\ & & & \checkmark & $\bm{93.54\%}$\\ \bottomrule \end{tabular} \caption{Interchangeability of SMYRF and dense attention. We \textbf{train} with SMYRF and \textbf{evaluate} with \textit{dense attention} for lightweight training and maximum performance.} \label{backandforth} \end{table} \subsection{Training from scratch} We also include experiments for networks trained from scratch. This shows that a non-pretrained model can learn with randomly initialized, SMYRF layers. Initially, the random weights produce less sparsity. However, the model quickly learns to create sparse attention maps and learning under our framework is possible. We use BigGAN~\cite{biggan} as the underlying model (see Appendix for details). We conduct our experiments on Celeba-HQ~\cite{celeba}, which contains $30$K images of celebrities at resolution $1024\times 1024$. We choose Celeba-HQ because: (i) images are in resolution higher than $128\times 128$, (ii) our budget is limited and Celeba-HQ requires much less training steps compared to ImageNet~\cite{ImageNet}. With SMYRF, we move attention from $64\times 64$ resolution to $128\times128$ and train with $50\%$ less memory than dense attention. In Table \ref{SMYRF128res}, we report FID for BigGAN and SMYRF-BigGAN after $120$K steps training on Celeba-HQ-128 (downsampled to $128\times 128$). SMYRF-BigGAN \textit{outperforms} BigGAN's FID by $\bm{3.95\%}$. Generated images from our model are shown in Figure \ref{gen128}. We finally move the attention layer to resolution $256\times 256$ (65k length) and we successfully train on Celeba-HQ-256 for 120K steps on a single TPU v3-8. As far as we know, no other GAN has been trained with attention in higher resolution than this. Details and generated images are included in the Appendix. \begin{table}[!htp] \begin{center} \begin{tabular}{l|l|l|l|l|l|l} & Resolution & Attention & Memory & Rounds & $C$ & FID \\ \hline BigGAN & \multirow{2}{4em}{$128\times 128$} & \multirow{1}{4em}{$64\times64$} & $100\%$ & $1$ & $4096$ & 26.06 \\ \cline{1-1} \cline{3-7} \multirow{1}{8em}{SMYRF-BigGAN} & & $128\times 128$ & $50\%$ & 4 & 2048 & $\bm{25.03}$\\ \bottomrule \end{tabular} \caption{Results on BigGAN training on Celeba-HQ-128 for 120K steps. Moving attention from $64\times 64$ to $128 \times 128$ helps performance: FID decreases from $26.06$ to $\bm{25.03}$. Memory percentages in this Table have as reference the memory a dense attention layer would use at the given resolution.} \label{SMYRF128res} \end{center} \end{table} \subsection{Comparison with other efficient attention techniques} \begin{table}[!htp] \centering \begin{tabular}{c|c} Model & IMDB (3 epochs)\\ \hline SMYRF-RoBERTa & \textbf{93.7\%} \\ E2LSH & 89.3\% \\ Reformer & 88.7\% \\ \bottomrule \end{tabular} \caption{LSH ablation experiment. The E2LSH model corresponds to the SMYRF-RoBERTa model using the E2LSH~\cite{e2lsh} hashing scheme instead of the asymmetrical transformations. The Reformer model corresponds to running SMYRF-RoBERTa with the cross polytope LSH~\cite{nearoptimallsh} scheme, which is used in the Reformer~\cite{reformer} paper.} \label{eff_attn_comp} \end{table} To validate the effectiveness of the proposed asymmetrical transformations, we replace SMYRF's hashing scheme with the E2LSH~\cite{e2lsh} scheme and the cross-polytope LSH~\cite{andoni2015practical} scheme of the Reformer and we evaluate all models on the IMDB~\cite{IMDB} dataset, after training for three epochs. The results are summarized in Table \ref{eff_attn_comp}. As shown, the asymmetrical transformations of SMYRF largely outperform all the other LSH schemes. This is expected since by design SMYRF tries to form clusters that maximize the inner products between queries and keys, while E2LSH and Reformer try to minimize euclidean distance and angular distance respectively, which is not the best objective when dealing with queries and keys with different vector representations and arbitrary norms. To compare with the Longformer~\cite{beltagy2020longformer}, we evaluate SMYRF on the Hyperpartisan News Detection~\cite{kiesel-etal-2019-semeval} dataset. For this task, Longformer reports $94.8\%$ accuracy with $4096$ context-length. SMYRF obtains $\textbf{97.2\%}$ performance while only using $512$ tokens. Longformer slightly outperforms (for $\approx 1\%$) SMYRF in the IMDB dataset but it uses $8$ times more tokens to achieve that. Unfortunately, the available RoBERTa~\cite{liu2019roberta} models have been trained with maximum positional embeddings at $512$ tokens and thus we cannot determine whether bigger sequence lengths would favor SMYRF. Nevertheless, SMYRF performs on par with other efficient attention techniques without requiring any pre-training. \section{Related work} The fact that attention maps of pre-trained layers are sparse is well-known~\cite{Voita_2019, michel2019sixteen, daras2019local, adaptively_sparse_transformers, Sukhbaatar_2019, Peters_2019}. Relevant research to our work includes efforts to leverage that sparsity by limiting attention of each element to a subset of the original sequence. ~\cite{localattn} proposes to limit attention to a sliding window around each element. Even though this simple idea is a strong baseline due to locality, this method is usually outperformed~\cite{sinkhorn, reformer, routing_transformer} by data-driven methods for assigning to each query the keys it will attend to. One recent research work that performs well with pre-defined sparsity is Longformer~\cite{beltagy2020longformer}. Longformer has been shown to perform well in downstream tasks after pre-training for $65$K gradient steps, resuming MLM training of a pre-trained RoBERTa~\cite{liu2019roberta} model. However, this work requires custom GPU kernels that do not transfer across hardware (i.e. are not efficient on TPUs). SMYRF differs from Longformer in other important aspects as well: (i) SMYRF does not require (even though it might help) further pre-training before finetuning on downstream tasks. Therefore, SMYRF is a drop-in replacement of dense attention, while Longformer~\cite{beltagy2020longformer} requires some adaptation of the original dense attention. (ii) More importantly, the fixed sparsification idea used in Longformer \cite{beltagy2020longformer} is fundamentally different from our idea of using clustering to approximate attention and (iii) SMYRF can be used interchangeably with dense attention while Longformer cannot. As we showed, a trained SMYRF attention lower can be converted back to a normal dense attention layer during inference. There are three research works that are very relevant to ours since they also propose data-driven attention within each group: (i) the Reformer \cite{reformer}, (ii) the Sparse Sinkhorn Attention~\cite{sinkhorn} paper and (iii) the Routing Transformer~\cite{routing_transformer}. Reformer~\cite{reformer} changes the dense attention layer twofold: (i) it tights vector representations of queries and keys, (ii) it sets their norm to be equal to $1$. Reformer is the first paper to propose LSH for clustering queries and keys. In Reformer, instead of using Asymmetric LSH, the authors use Angular distance LSH for clustering. This works because of (i), (ii), i.e. the Maximum Inner Product Search problem is equivalent to the Nearest Neighbor Search problem. We consider SMYRF as a generalized version of Reformer, since it employs Asymmetric LSH clustering to enable grouping of queries and keys that (i) do not have the same vectors, (ii) possibly live outside or inside the unitary $d-$dimensional disk. Apart from this, SMYRF and Reformer are similar: both networks sort vectors based on their LSH hash and both have linear attention complexity. Sinkhorn~\cite{sinkhorn} proposes a differentiable sorting module for clustering queries and keys. The sorting layer is trained end-to-end with the rest of the model. It has only been shown to work well for training from scratch and not for fine-tuning of pre-trained models. Routing Transformer~\cite{routing_transformer} proposes $k-$means clustering. In general, vectors that have small Euclidean distance are not guaranteed to have big inner product. To alleviate this, in Routing Transformer queries and keys are forced to have exactly the same vector representations and are also mapped to a $d-$dimensional unitary disk, exactly as Reformer proposed. Because of these changes, also this method cannot be applied to pre-trained models. Routing transformer has some other weaknesses as well: (i) the complexity is $O(N^{1.5})$ instead of $O(N\log N)$ which is the attention complexity of SMYRF and Reformer and (ii) the clusters are not guaranteed to be balanced. To solve (ii), ~\cite{routing_transformer} proposes to keep the top-k vectors in each cluster. However, this is not guaranteed to work well since it depends on the clusters ordering. Comparing to the aforementioned methods, SMYRF is the only method that assigns dynamically queries and keys in clusters and can be applied to pre-trained models. Due to its portability, SMYRF is the first sparse attention model to report GLUE results on par with the underlying models. As we showed, SMYRF can be used interchangeably with dense attention before, during and after training. It also has linear attention complexity, similarly to Reformer. To the best of our knowledge, we are also the first to prove that the problem that all these methods are trying to solve is NP-hard. The optimization problem that SMYRF tries to solve is connected to the problem of bi-clustering~\cite{biclustering_first_paper}. Indeed, as shown in the proof of Theorem \ref{min_problem}, the goal in Attention Biclustering is to find a clustering of rows and columns of a matrix that maximizes the sum of the values of the clusters, where each value at position $(i, j)$ depends on the inner product of query $i$ and key $j$. For bi-clustering, iterative algorithms have been proposed~\cite{cheng2000biclustering}. Iterative techniques cannot be applied in the context of attention in which everything happens in a parallel fashion for fast execution in modern hardware. Finally, there are a lot of others not attention related techniques that can be used to save memory and offer speedups. Examples of such techniques include knowledge distillation~\cite{hinton2015distilling, sanh2019distilbert}, reversible layers~\cite{gomez2017reversible}, gradient checkpointing~\cite{chen2016training}, quantization~\cite{hubara2016quantized} and pruning~\cite{80236, blalock2020state}. SMYRF and all these innovations are not mutually exclusive, i.e. they can be used together for maximum efficiency. \section{Conclusions} In this work we presented SMYRF, a novel type of balanced clustering to approximate attention. It is based on Asymmetric LSH with novel transformations and an adaptive clustering scheme. As it does not require changes to attention, SMYRF is the first sparse attention method that can be applied directly to pre-trained models. We showed powerful experimental results, in terms of performance, memory and speed. We also defined the underlying optimization problem that SMYRF tries to solve and we proved it is NP-hard. The strong experimental performance of SMYRF inclines us to believe that good approximation algorithms exist for this problem. Proving approximation guarantees for our method and discovery of better approximation algorithms are left for future work. \section{Acknowledgements} We would like to wholeheartedly thank the TensorFlow Research Cloud (TFRC) program that gave us access to v3-8 Cloud TPUs and GCP credits that we used to run our Computer Vision experiments. This research has been supported by NSF Grants CCF 1763702,1934932, AF 1901292, 2008710, 2019844 research gifts by Western Digital, WNCG IAP, computing resources from TACC and the Archie Straiton Fellowship. \newpage \section{Broader Impact} Our main contribution is to reduce the computational requirements for machine learning models with attention-layers. Thus, any broader impact is likely to come from making these models more efficient in both memory impact and inference speed. We expect that this will be mostly a good thing since it democratizes the use of big attention layers: those who want to use such models but for whom the computational resources required are too great (like university labs) will now have an easier time. Moreover, GANs and language models will become easier to deploy on phones or other embedded devices. Further, more efficient training reduces the environmental and energy footprint of deep learning research. As the number of parameters of Transformer models grows, the latter becomes critical~\cite{strubell2019energy}. Negative consequences are also possible: The idea of DeepFakes \cite{deepfakes} has been well-discussed elsewhere; a technique that makes these easier to create clearly has downsides. On the other hand, any sufficiently determined actor (e.g. a nation-state attempting to commit election-fraud) already has access to such technology, so perhaps the marginal negative impact will not be that large. Still, whenever computational requirements are reduced, the ease of taking bad actions increases along with the ease of taking good actions. Finally, the technique proposed in this paper relies heavily on the assumption that attention maps are approximately sparse. It's possible (though we have no particular reason to think that this has happened or would happen) that, at some intermediate layer of a complicated neural network, enforcing sparsity when the ground-truth maps are non-sparse could result in ignoring salient features of atypical data points, thus resulting in fairness-related issues. Determining whether these approximations cause fairness issues in general could be an interesting subject for future work. \clearpage \title{Supplementary Material \\ SMYRF: \\ Efficient Attention using Asymmetric Clustering} \author{% Giannis Daras\\ Computer Science Department \\ The University of Texas at Austin\\ \texttt{[email protected]} \\ \And Augustus Odena \\ Google Research \\ \texttt{[email protected]} \And Nikita Kitaev \\ Google Research \\ \texttt{[email protected]} \And Alexandros G. Dimakis \\ ECE Department \\ The University of Texas at Austin \\ \texttt{[email protected]} \\ } \@maketitle \section{NP-hardness of Attention Biclustering} To prove Theorem \ref{main_theorem}, we first prove the following lemma. \begin{lemma} The optimization problem: $$ \min_{\mathcal C_t^L \in \mathcal C^L} ||\hat P_{\epsilon} - P ||_F^2 $$ is NP-hard. \label{maxmass} \end{lemma} \begin{proof}[Proof of Lemma \ref{maxmass}] We will show that this problem is NP-hard, by showing that if we could solve in polynomial time all instances of this problem, we could solve in polynomial time the 3-dimensional matching problem (3-DM), which is known to be NP-complete. Following the notation of the main paper, we define $\epsilon=e^{-a}$ and $\hat P_\epsilon$ denotes the queries-keys product matrix with $-a$ in positions that correspond to queries and keys that do not belong to the same cluster. It holds that: $$ \min_{\mathcal C^L} ||\hat P_\epsilon - P||_F^2 = \min_{\mathcal C_t^L \in \mathcal C^L} \sum_{(q, k) \not \in \mathcal C_t^L} \left(q\cdot k - (-a)\right)^2 $$ $$ =\min_{\mathcal C_t^L \in \mathcal C^L} \left[ \sum_{(q, k) \in \mathcal Q \times \mathcal K} \left(q\cdot k + a \right)^2 - \sum_{(q, k) \in \mathcal C_t^L} \left(q\cdot k +a\right)^2\right] = \min_{\mathcal C_t^L \in \mathcal C^L} \left[- \sum_{(q, k) \in \mathcal C_t^L} \left(q\cdot k + a\right)^2\right] $$ \begin{equation} = \max_{\mathcal C_t^L \in \mathcal C^L} \sum_{(q, k) \in \mathcal C_t^L} \left(q \cdot k + a\right)^2 \end{equation} Since for all given sets $\mathcal Q, \mathcal K$ we can create (in polynomial time) sets $\mathcal Q', \mathcal K'$ such that: $\left(q \cdot k + a\right)^2 = q'\cdot k', \quad \forall (q, k) \in \mathcal Q \times \mathcal K, (q', k') \in \mathcal Q' \times \mathcal K'$, the problem is equally hard to solving: \begin{equation} \max_{\mathcal C_t^L \in \mathcal C^L} \sum_{(q', k') \in \mathcal C_t^L} q'\cdot k' \label{maxmasseq} \end{equation} We can refer to this latest optimization problem as the max-mass problem. Now consider the case where: $|\mathcal Q|=|\mathcal K|, \quad L=|\mathcal Q|/2$, i.e. for this problem instance we have the same amount of queries and keys and we want to group them optimally to clusters with the constraint that each cluster should contain exactly $2$ queries and $2$ keys. Note that for 1 query and one key per cluster this becomes weighted bipartite matching (which is efficiently solvable). For 1 query and $m$ keys per cluster this is a generalized matching problem, which is also polynomially solvable~\cite{generalizedmatching}. If we are able to solve the latter with a polynomial algorithm, then we can show that we can solve the 3-DM problem with a polynomial algorithm. Any instance of the 3-DM problem can be expressed with finite, disjoint sets $X, Y, Z$ and a set $T$ of triples $(x, y, z): \quad x \in X, y \in Y, z \in Z$. Visually, we can depict any instance of a 3-DM as a graph with three disjoint vertex sets, with $T$ containing the edges of the graph. For example, the 3-DM instance $X=\{1_{\textrm{red}}, 2_{\textrm{red}}\}, Y=\{1_{\textrm{blue}}, 2_{\textrm{blue}}\}, Z=\{1_{\textrm{green}}, 2_{\textrm{green}}\}, T = \{ (1_{\textrm{red}}, 1_{\textrm{blue}}, 1_{\textrm{green}}), (1_{\textrm{red}}, 2_{\textrm{blue}}, 2_{\textrm{green}}), (2_{\textrm{red}}, 1_{\textrm{blue}}, 1_{\textrm{green}})\}$ is shown in (1,1) of Figure \ref{np-hardness}. We are looking for a set $T' \subseteq T$ in which every vertex is covered exactly once. Finding this solution, in case it exists, it is known to be an NP-hard problem. For this example, there is a valid solution, which is shown in (1, 2) of Figure \ref{np-hardness}. We can transform any instance in the following way: we create one query and one key vector for each vertex $x \in X$ with the property that their inner product is some large positive constant $r_1\in \mathbb R^{+}$. We can visualize this using red edges, following the previous example where we denoted with red color the vertices of $X$. We also set the inner product of any key vector that corresponds to vertex of $X$ with all the other query vectors to be $0$. Visually, a ``missing" edge means that the inner product of the corresponding vectors is $0$ (no-reward). We also create a key vector for each vertex $y \in Y$ with the property that if $(x, y, z) \in T$ for some $z$, then the key vector for $y$ and the query vector for $x$ have inner product $r_1$, else $0$. We can show the non-zero edges of this category visually with blue color, following the previous example. Note that blue and red edges are equivalent in terms of the inner product between the vertices they connect, since both have inner product $r_1$. Finally, we create a query vector for each $z \in Z$ with the property that if $(x, y, z) \in T$ for some $x$ then the key vector for $y$ and the query vector for $z$ have inner product $r_2$, else $0$ where $r_2 \in \mathbb R^{+}$ is a small positive constant. Again, we can show the non-zero edges of this category with green color, following the previous example. For the given example, the transformation is shown in (2, 1) of Figure \ref{np-hardness}. We have hypothesized that we have a polynomial algorithm to solve the max-mass problem of (\ref{maxmasseq}). The key observation for our proof is that, by construction, the best cluster in terms of potential accumulated mass is a cluster with one red, one blue and one green edge, as the ones shown right of the dashed bar of Figure \ref{np-hardness-cases}. Indeed, the only way to obtain a cluster of more mass is to group two blue vertices with two red vertices, as shown in (1, 1) of Figure \ref{np-hardness-cases}. By doing that, you earn one more $r_1$ compared to the clustering shown in (1, 2) of Figure \ref{np-hardness-cases}, but you lose $2\cdot r_1$, which are the rewards that they red keys could give (as they are left with no connections). Thus, the two clusterings on the right side of Figure \ref{np-hardness-cases} are preferable compared to any other potential two clustering that can be obtained by choosing the left grouping. Since we have proved that the best possible clustering is one with one red, one blue and one green edge, it is now left to prove that if there is a 3-DM, then it is possible to group all queries and keys into clusters with this optimality property. Indeed, if there is a 3-DM, we can cover each vertex exactly one time, by matching any vertex of $X$ with a vertex from $Y$ and a vertex from $Z$. With our transformation, this means that we can group each red node with itself and one blue and one green vertex, which is an optimal cluster as it contains one red, one blue and one green edge. Thus, solving polynomially our problem would mean that we could also solve in polynomial time the 3-DM, which is known to be NP-hard. \begin{figure}[!htp] \centering \includegraphics[width=0.65\textwidth]{figs/NP-hardness.png} \caption{(1, 1): Instance of $3-$DM. We denote with red color the $X$ vertex set, with blue the $Y$ vertex set and with green the $Z$ vertex set. (2, 1): Ours transformation for the reduction. Red and blue edges have reward $r_1$, while green edges have reward $r_2<<r_1$. Missing edges have reward $0$. We create one query and one key for each vertex of $X$. We also create one key (blue color) for each vertex of $Y$ and one query (green color) for each vertex of $Z$. Connections between red queries and blue keys, as well as, connections between blue keys and green queries follow the problem instance. (2, 2): Optimal queries, keys clustering in groups of 2 for the max-mass \ref{maxmasseq} problem. (1, 2): Transformation of (2, 2) solution back to the $3-$DM instance.} \label{np-hardness} \end{figure} \begin{figure}[!htp] \centering \includegraphics[width=0.6\textwidth]{figs/NP-hardness-cases.png} \caption{Illustration of potential clusterings. (1, 1): sub-optimal clustering. (1, 2): optimal clusterings. Even though the clustering at the left side obtains more mass compared to any of the clusterings in the right side, it loses entirely the rewards that red keys can give. Indeed, clustering on the left side has one $r_1$ reward more than any of the two clusterings on the right, but in further clusterings red keys $\{1, 2\}$ will not be matched with anything (by construction) and thus a total reward of $2r_1$ will be lost.} \label{np-hardness-cases} \end{figure} \end{proof} \begin{proof}[Proof of Theorem \ref{main_theorem}] We will show that if we can solve in polynomial time the problem: $\min_{\mathcal C^L} ||\sigma(\hat P_0) - \sigma(P)||_F^2$, then we can also solve in polynomial time the problem $\min_{\mathcal C^L}||\hat P_\epsilon - P||_F^2$ (for an appropriate $\epsilon$) which we have proven to be NP-hard. We are given sets $\mathcal Q, \mathcal K$ and a number $L$. For each $q_i \in \mathcal Q$, we create a key vector $k_{q_i}$ such as $q_j \cdot k_{q_i} = \begin{cases} a, \quad \textrm{if} \ i=j \\ -\infty, \quad \textrm{o/w} \end{cases}$, where $a$ is a positive constant the choice of which we will determine later in this proof. We denote the augmented key set with $\mathcal K'$. We will now solve, with our hypothetical polynomial algorithm, the following optimization problem for our new input set: $$\min_{\mathcal C^L} ||\sigma(\hat P_0) - \sigma(P)||_F^2 $$ It holds that: $$ \min_{\mathcal C^L} || \sigma(\hat P_0) - \sigma(P) ||_F^2 = \min_{\mathcal C_t^L \in \mathcal C^L}\sum_{(q, k) \not \in \mathcal C_t^L}\left(\frac{e^{q\cdot k}}{q_D}\right)^2 + \sum_{(q, k) \in \mathcal C_t^L} \left( \frac{e^{q\cdot k}}{q_D} - \frac{e^{q\cdot k}}{q_{\mathcal C_t^L}}\right)^2 $$ $$ = \max_{\mathcal C_t^L \in \mathcal C^L}\sum_{(q, k) \in \mathcal C_t^L} e^{2q\cdot k} \cdot \left(\frac{2}{q_D \cdot q_{\mathcal C_t^L}} - \frac{1}{q_{\mathcal C_t^L}^2} \right), $$ where $q_D$ denotes the denominator of the dense softmax and $q_{C_t^L}$ denotes the denominator of the cluster softmax, i.e. $q_D = \sum_{k \in \mathcal K} e^{q \cdot k}$ and $q_{C_t^L} = \sum_{k \in \mathcal C_t^L} e^{q\cdot k}$ for a given cluster $\mathcal C_t^L \in \mathcal C^L$. We will now show that for a proper choice of $a$, this problem is equivalent to: $$ \max_{\mathcal C_t^L \in \mathcal C} \sum_{(q,k) \in \mathcal C_t^L} e^{2q\cdot k}. $$ Let $R_q =\frac{2}{q_D q_{C_t^L}} - \frac{1}{q^2_{C_t^L}}$. As we increase the value of $a$, the inner product of its query with its' special key gets significantly bigger compared to other inner products and thus for large enough values of $a$, we know that each query will get clustered with its' special key. We can control how close $q_D, q_{\mathcal C_t^L}$ are by setting appropriately the $a$ value. Specifically, we choose $a$ such that $q_D (1-\epsilon) < q_{\mathcal C_t^L}, \ \forall q \in \mathcal Q, \ \mathcal C_t^L \in \mathcal C^L$, where $\epsilon=\epsilon(a)$ a small positive constant the choice of which we will determine soon. By definition, $q_{\mathcal C_t^L}$ is always smaller than $q_D$, and thus we for that choice of $a$ we have $q_D(1-\epsilon) < q_{\mathcal C_t^L} < q_D$. Then, $R_q > \frac{2}{q_D^2} - \frac{1}{q_D^2 (1-\epsilon)^2} = \frac{1}{q_D^2} (2 - \frac{1}{(1-\epsilon)^2}) = \frac{1-\epsilon'}{q_D^2}$ where $1 + \epsilon' = \frac{1}{(1-\epsilon)^2}$. But also, $R_q = \frac{2q_{\mathcal C_t^L} - q_D}{q_{\mathcal C_t^L}^2q_D} < \frac{2q_D - q_D}{q_{\mathcal C_t^L}^2q_D} = \frac{1}{q_{\mathcal C_t^L}^2} < \frac{1}{(1-\epsilon)^2q_D} = (1 + \epsilon')\frac{1}{q_D^2}$. Then, we have that: \begin{equation} \frac{1-\epsilon'}{q_D^2} < R_q < \frac{1 + \epsilon'}{q_D^2}. \label{boundR} \end{equation} Now consider the following optimization problems: $$ \begin{cases} P_0: \quad \max \sum_{(q, k) \in \mathcal C_t^L} e^{2qk} R_q \\ P_1: \quad \max \sum_{(q, k) \in \mathcal C_t^L} \frac{e^{2qk}}{q_D} \end{cases}. $$ Let $F(c), G(c)$ the objective functions of $P_0, P_1$ respectively. Using (\ref{boundR}), we get that: \begin{equation} (1-\epsilon') G(c) \leq F(c) \leq (1 + \epsilon ') F(c). \label{boundGF} \end{equation} Our claim is that for a suitable choice of $\epsilon'$, i.e. for a suitable choice of $a$, it holds that $\argmax P_0 = \argmax P_1$\footnote{We assume that if there is a set of optimal solutions, then we pick with the same order from that set for both problems.}.We prove that by contradiction. Let $c_1$ be the optimal choice of $P_0$ and $c_2$ be the optimal choice of $P_1$. Then, we know that $F(c_1) > F(c_2)$ and $G(c_2) > G(c_1)$. Using (\ref{boundGF}), we get that: \begin{equation} (1-\epsilon') G(c_1) - (1 + \epsilon')G(c_2) < F(c_1) - F(c_2) < (1+\epsilon')G(c_1) - (1-\epsilon') G(c_2). \label{solbound} \end{equation} We denote with $d$ the gap between the optimal value $F(c_1)$ and the non optimal solution $F(c_2)$, i.e. $d = F(c_1) - F(c_2)$. Then, from (\ref{solbound}), we get that: $$ d < (1 + \epsilon')G(c_1) - (1-\epsilon')G(c_2) - (1-\epsilon')G(c_1) + (1+\epsilon')G(c_2) = 2e' (G(c_1) + G(c_2)). $$ Let $\theta_1$ the maximum value of $G(c_1) + G(c_2)$ among all the clusterings $c_1, c_2 \in C^L$, i.e. among all the possible valid clusterings in $L$ groups. Then, $d < 2\epsilon' \theta_1$. However, since $F$ is a function that maps from discrete clusterings to real numbers, two non-optimal solutions of $F(c)$ differ for at least a minimum distance. In that case, the minimum distance should be at least $e^{p_{\min}}R_{\min}$, where $p_{\min}$ is the minimum product between any query and any key and $R_{\min}$ is the minimum value that $R$ can take for any clustering. Let $\theta_2 = e^{p_{\min}}R_{\min}$. Then, $d \geq \theta_2$. If we choose $\epsilon'$ such that: $2\epsilon' \theta_1 < \theta_2$ then we have a contradiction. This is always possible since we can set the value of $\epsilon'$ to arbitrarily small values as we grow $a$ arbitrarily big. Thus, we proved that the problems $P_0, P_1$ have the same $\argmax$ for a proper choice of $a$. Then, for that choice of $a$ the problem $\min_{C^L} ||\sigma(\hat P_0) - \sigma(P)||_F^2$ is equivalent to $P_1$ which is equivalent to the problem: $$ \max_{\mathcal C_t^L \in \mathcal C} \sum_{(q,k) \in \mathcal C_t^L} e^{2q\cdot k}, $$ since $q_D$ does not affect the choice of optimal clusters. In the latter problem, we can replace all queries $q$ and keys $k$ with new vectors $q', k'$ such that: $q'\cdot k' = e^{2q\cdot k}$. This is equally hard to solving: $$ \max_{\mathcal C_t^L \in \mathcal C} \sum_{(q,k) \in \mathcal C_t^L} q\cdot k $$ which we proved to be NP-hard. \end{proof} \section{Code} To encourage further research in sparse attention models, we open-source all our code and we release a Python package, named \texttt{smyrf}. The repository for the code is the following: \href{https://github.com/giannisdaras/smyrf}{https://github.com/giannisdaras/smyrf} . \texttt{smyrf} implements SMYRF attention for Pytorch~\cite{paszke2019pytorch}. We plan to release implementation for Tensorflow~\cite{tensorflow} soon as well. \texttt{smyrf} contains various examples on pre-training and finetuning state-of-the-art models for Computer Vision and Natural Language Processing tasks. Regarding examples, at the moment \texttt{smyrf} includes: \begin{itemize} \item a TPU-compatible implementation of SMYRF-BigGAN, based on the official Pytorch implementation (\href{https://github.com/ajbrock/BigGAN-PyTorch}{https://github.com/ajbrock/BigGAN-PyTorch}) for GPUs. \item code for training SMYRF-BigGAN on Celeba-HQ on a single TPU device. \item interactive notebooks showing how to use a pre-trained BigGAN for image generation with SMYRF on Celeba-HQ and ImageNet. \item tools to visualize cluster memberships for pixels of SMYRF generated images. \item code for replacing dense attention with SMYRF layers for state-of-the-art pre-trained NLP models, compatible with HuggingFace's Transformers~\cite{wolf2019huggingfaces} library. \item interactive notebooks for fine-tuning pre-trained NLP models on GLUE~\cite{GLUE} and IMDB~\cite{IMDB}. \item tools for profiling SMYRF's performance compared to dense attention. \end{itemize} We also share the weights of SMYRF-BigGAN trained on Celeba-HQ at resolutions $128\times 128$ and at $256\times 256$ with attention at $128\times 128, 256\times 256$ respectively. Although these models are outperformed by non-attention GANs (e.g. StyleGAN~\cite{stylegan2, stylegan1}), we believe that releasing them will help researchers understand better attention at higher resolutions. Hopefully, SMYRF will motivate the usage of more attention layers on new GAN architectures. \section{Singular values decay for pre-trained models} As noted in the paper, row-wise softmax can change the rank of a matrix. For example, the matrix $\begin{bmatrix} 1 & 0 \\ 2 & 0 \end{bmatrix}$ has rank $1$, while the matrix $\sigma\left(\begin{bmatrix} 1 & 0 \\ 2 & 0 \end{bmatrix}\right) = \begin{bmatrix} 0.7311 & 0.2689 \\ 0.8808 & 0.1192 \end{bmatrix}$ has rank $2$. Back to the context of attention, we have defined the product matrix $P = Q\cdot K^T$, where $Q:\mathbb R^{|\mathcal Q| \times d }$ represents the queries matrix and $K:\mathbb R^{|\mathcal K| \times d}$ the keys matrix. By the definition of rank, if the embeddings dimension is smaller than the sequence length dimension, i.e. $d < \min(|\mathcal Q|, |\mathcal K|)$, then P is low rank. However, the attention matrix after softmax, i.e. $\sigma(P)$, could be a full rank matrix. In this section, we provide experimental evidence that attention maps produced by pre-trained models are actually near low-rank. Figures \ref{sing_decay_biggan}, \ref{sing_decay_bert} depict the singular values of the attention maps (for a random input\footnote{We experimented with different random inputs and there is no qualitative difference in the decay of singular values)}) for a pre-trained BigGAN (attention map dimensions: $4096\times 1024$) and a pre-trained BERT (shown attention map dimensions: $64\times 64$, $256\times 256$). For the pre-trained BigGAN (Figure \ref{sing_decay_biggan}) the decay in singular values is exponential. Specifically, in Figure \ref{sing_decay_biggan} most singular values are very close to 0, which means that the attention map is effectively low rank. Figure \ref{sing_decay_bert} shows decay of singular values for a pre-trained BERT for sequence lengths: (a) 64, (b) 128. We illustrate decay for 144 heads (12 heads for each one of the 12 layers). For the majority of heads, singular values decay exponentially. We also see that the heads that do not demonstrate exponential decay in the singular values maintain this property for both inputs (e.g. see the red line in both plots). In our experiments, we find that these heads are harder to approximate with SMYRF. \begin{figure}[!htp] \centering \includegraphics[width=0.75\textwidth]{figs/singular_values_biggan.png} \caption{Decay of singular values of the attention map (after softmax) of a pre-trained BigGAN. Decay of singular values is exponential, which means that the matrix after softmax is effectively low rank.} \label{sing_decay_biggan} \end{figure} \begin{figure}[!htp] \begin{subfigure}{\textwidth} \centering \includegraphics[width=0.75\textwidth]{figs/singular_values_bert_64.png} \caption{} \label{sing_decay_bert64} \end{subfigure} \begin{subfigure}{\textwidth} \centering \includegraphics[width=0.75\textwidth]{figs/singular_values_bert_256.png} \caption{} \label{sing_decay_bert128} \end{subfigure} \caption{Decay of singular values for a pre-trained BERT for sequence lengths: (a) 64, (b) 128. We show decay of singular values 144 heads (12 heads for each one of the 12 layers). For the majority of heads, singular values decay exponentially. We also see that the heads that do not demonstrate exponential decay in the singular values maintain this property for both inputs (e.g. see the red line in both plots). We find that these heads are harder to approximate with SMYRF.} \label{sing_decay_bert} \end{figure} \section{Cluster memberships for generated images of a pre-trained BigGAN} In this section, we visualize how SMYRF's adaptive clustering algorithm assigns queries in clusters for a pre-trained BigGAN. This inspection gives useful insights into how the algorithm actually works in practice. Top row of Figure~\ref{vismemberships} shows a random maltese dog generated by a pre-trained BigGAN~\cite{biggan}. The second row, illustrates how a single SMYRF hashing round assigns queries and keys for this particular image in two clusters: the first cluster is denoted with gray and the second with white color. As shown, SMYRF assignments preserve locality while enabling the modeling of arbitrary complex dependencies between input pixels. Indeed, pixels in the same neighborhoods are mostly organized in the same cluster. This observation is even more pronounced for background pixels (see big gray blocks). However, we also see that distant pixels sometime belong to the cluster as well. By only looking at the assignments in clusters (second row), we can infer that the image is roughly separated in three parts: the top part (mostly gray pixels), the middle part (mostly white pixels) and the bottom part (mostly gray pixels). These parts correspond to the top background, the dogs' face and the bottom background respectively. Third row of Figure~\ref{vismemberships} illustrates (for the same image) assignments in 128 clusters. Each cluster contains 32 queries and is denoted with a distinct color. Again, we observe that clusters are often local. Indeed, usually consecutive pixels or nearly consecutive pixels are denoted with the same color. For such large number of clusters, it becomes very difficult to extract semantic information from the clustering map without looking at the original image. However, by careful looking at both the attention map and the generated image we can make interesting observations. For instance, we see that distant background pixels are clustered together with much greater frequency compared to other distant non-background pixels. In other words, SMYRF often clusters together background pixels even if they belong to distant grid positions in the generated image (see for example colors in top and last row of the grid). \begin{figure}[!htp] \centering \begin{subfigure}{\textwidth} \centering \includegraphics[]{figs/sample_memberships.png} \caption{Generated maltese dog from a pre-trained BigGAN.} \label{sample_memberships} \end{subfigure} \bigbreak \begin{subfigure}{0.6\textwidth} \includegraphics[width=\textwidth]{figs/2clusters.png} \caption{Visualization of SMYRF cluster assignments for this image (single hash). Total number of clusters: 2.} \label{2c} \end{subfigure} \bigbreak \begin{subfigure}{0.6\textwidth} \includegraphics[width=\textwidth]{figs/128clusters.png} \caption{Visualization of SMYRF cluster assignments for this image (single hash). Total number of clusters: 128.} \label{128c} \end{subfigure} \caption{Visualization of clustering assignments for a generated image by a pre-trained BigGAN.} \label{vismemberships} \end{figure} \section{SMYRF Clustering} \subsection{Asymmetric Locality Sensitive Hashing (ALSH)} SMYRF clusters depend on the hashing indices of asymmetrically transformed queries and keys. As mentioned in the paper, we are looking for functions $F: \mathbb R^{d}\to \mathbb R^{d'}, G: \mathbb R^d \to \mathbb R^{d'}$ such as: $||F(q) - G(k)||_2^2 = D(q\cdot k), \ \forall (q, k)$ where $D:\mathbb R \to \mathbb R$ a decreasing function that depends only on the inner product $q\cdot k$. Essentially, functions $F, G$ are applied to queries and keys to convert the problem of Maximum Inner Product Search (MIPS) to Nearest Neighbor Search (NNS). For the latter problem, a lot lot of effective Locality Sensitive Hashing (LSH) functions have been proposed (e.g. ~\cite{e2lsh, VoronoiLSH, nearoptimallsh}). The novel idea of converting MIPS to NNS is called Asymmetric Locality Sensitive Hashing (ALSH) and was first introduced in~\cite{l2lsh}. Since then, a lot of different asymmetric transformations have been proposed~\cite{h2lsh, e2lsh, xbox}. In this section, we show why previously proposed transformations are not suitable for our problem and how our novel asymmetric transformations, defined in Equation 4, relate to previous work. We list the asymmetric transformations that have been widely used to convert a MIPS to NNS: \[ \left\lbrace \begin{tabular}{@{}p{15cm}p{15cm}} \cite{l2lsh}: $F(q_i) = \left[q_i; \frac{1}{2}, ...; \frac{1}{2}\right], \ G(k_i) = \left[ Uk_i; ||Uk_i||_2^2; ...;||Uk_i||_2^{2^m}\right]$ \\ \\ \cite{xbox}: $F(q_i) = \left[q_i ; 0\right], \ G(k_i) = \left[k_i; \sqrt{M_K^2 - ||k_i||_2^2}\right]$ \\ \\ \cite{h2lsh}: $F(q) = \frac{M_K}{||q||_2}\cdot \left[ q;0\right], \ G(k) = \left[k; \sqrt{M_K^2 - ||k||_2^2}\right]$ \\ \end{tabular}\right. \] where $M_K = \max_{k}||k||_2$ and U a positive constant such as: $||U\cdot k_i||_2^{2^{m + 1}} \to 0, \ \forall k_i \in \mathcal K$. The corresponding Euclidean distances of the transformed vectors are given below: \[ \left\lbrace \begin{tabular}{@{}p{15cm}p{15cm}} \cite{l2lsh}: $||F(q_i) - G(k_i)||_2^2 = ||q_i||_2^2 + \frac{m}{4} - 2Uq_i\cdot k_i + ||U \cdot k_i||_2^{2^{m+1}}$\\ \\ \cite{xbox}: $ ||F(q_i) - G(k_i)||_2^2 = ||q_i||_2^2 + M_K^2 - 2 q_i \cdot k_i$ \\ \\ \cite{h2lsh}: $||F(q_i) - G(k_i)||_2^2 = 2\cdot M_K^2 -2\frac{M_K}{||q_i||}\cdot q_i\cdot k$ \end{tabular}\right. \] In all these transformations the Euclidean distance of the transformed vectors, i.e. $||F(q_i) - G(k_i)||_2$ decreases linearly with the inner product $q_i\cdot k_i$. However, an extra term, $p(||q_i||)$, appears. Indeed, these transformations were proposed for the case of a single query (e.g. a user) and multiple keys (e.g. movies) and for such applications $||q_i||$ is considered constant. On the contrary, for our setting, the transformations of \cite{l2lsh, h2lsh, xbox} cannot be applied since $||q||_2$ is no longer a constant. To illustrate this better, consider the case where $q_1, q_2 \in \mathcal Q$ with $q_1 \neq q_2$ and $k \in \mathcal K$ a key such as: $q_1 \cdot k = q_2 \cdot k$. Since we are looking for big inner products, we expect to have transformations $F, Q: ||F(q_1) - G(k) ||_2 = ||F(q_2) - G(k)||_2$. For \cite{l2lsh, xbox}, if $||q_1||_2 < ||q_2||_2$ then $||F(q_1) - G(k)||_2 < ||F(q_2) - G(k)||_2$ and for \cite{h2lsh}: $||F(q_1) - G(k)||_2 > ||F(q_2) - G(k)||_2$. Thus, all \cite{l2lsh, h2lsh, xbox} do not satisfy our desired property, i.e. $||F(q_1) - G(k)||_2 = ||F(q_2) - G(k)||_2$. To solve this problem, we propose (see main paper) the novel asymmetric functions: \begin{equation} F(q_i) = \left[q_i; 0; \sqrt{M_Q^2 + M_K^2 - ||q_i||_2^2} \right], \qquad G(k_i) = \left[k_i; \sqrt{M_Q^2 + M_K^2 - ||k_i||_2^2}; 0\right] \end{equation} where we use the constants $M_Q = \max_{q_i}||q_i||_2, \quad M_K = \max_{k_i}||k_i||_2$, or any other upper bound on the norms. With this transformation, all queries and keys are mapped to a $(d+2)$-dimensional ball with radius $\sqrt{M_Q^2 + M_K^2}$ and the distance of the transformed vectors decreases linearly with the inner product of the original vectors: \begin{equation} ||F(q_i) - G(k_i)||_2^2 = 2 \cdot \left( M_Q^2 + M_K^2 - q_i\cdot k_i\right). \end{equation} Note that the Euclidean distance of the transformed vectors depends only on the inner product of the original vectors and not on individual norms $||q_i||_2$ as in previous work. \subsection{Adaptive Clustering} The next step, after the asymmetric transformations, is to map the transformed queries $F(q)$ and keys $G(k)$ to real numbers, so that if $||F(q) - G(k)||_2$ is small, then $|h(F(q)) - h(G(k))|$ is also small with high probability, where $h:\mathbb R^{d'} \to \mathbb R$ is the mapping function. After mapping, we sort independently queries and keys based on their hash and we split them into groups of equal size. There are numerous hashing functions ~\cite{andoni2015practical, e2lsh, VoronoiLSH, qlsh} $h:\mathbb R^{d'} \to \mathbb R$ that belong to the LSH family that we can leverage to achieve that. One of the most widely adopted hash functions for locality sensitive hashing is E2LSH~\cite{e2lsh}: \begin{equation} h_{\textrm{E2LSH}}(u) = \left \lfloor \frac{(u \cdot a) + b}{r} \right \rfloor \label{e2lsh_hash} \end{equation} where $a=(a_1, ..., a_d') \in \mathbb R^{d'}$ with $a_i \in \mathcal N(0, 1)$ and $b \in \mathcal U(0, r)$ and $r$ is a scalar parameter which controls LSH sensitivity. Since we re-group vectors by sorting on their LSH index, the floor operator and the division with $r$ are not needed. Our simplified hashing function is defined as: \begin{equation} h_{\textrm{ours}}(u) = (u\cdot a) + b \label{simplified_e2lsh} \end{equation} We roughly removed a division by a constant. Thus, this simplified hashing function preserves the locality-sensitive properties of E2LSH~\cite{e2lsh}. Namely, if $||u_1 - v_1||_2 \leq || u_2 - v_2||_2$ then with high probability: $|h(u_1) - h(v_1)| \leq |h(u_2) - h(v_2)|, \ \forall u_1, u_2, v_1, v_2 \in \mathbb R^{d'}$. \subsection{Merging hashing rounds} In our experiments, we run multiple hashing rounds each time, similarly to \cite{reformer}. Each time we run LSH, we end up with a (possibly) different clustering assignment and thus (possibly) different attention output. Specifically, we repeat the process $H$ times (where $H$ is usually a small constant, e.g. 8) to reduce the probability that we miss big inner products. In this section, we explain how we merge the partial attention outputs (made from different hashing rounds) into a single attention output. Without loss of generality, we will present the merging algorithm for a single query $q$. At each clustering round $h$ we get (from the adaptive clustering) a set of key vectors $\mathcal K_{h_q} \subseteq \mathcal K$. The corresponding attention output is: $$ o_q^h = \sum_{k \in \mathcal K_{h_q}} w_k v_k, \qquad w_k = \frac{e^{q \cdot k}}{\sum_{k' \in \mathcal K_{h_q}} e^{q \cdot k'}} $$ We merge the attention outputs of the different rounds with a weighted sum. The weight, $a_h$, for each round $h$, is the fraction of the softmax mass that was acquired in this round to the total mass acquired by all rounds. Formally the attention output $o_q'$ for query $q$ is computed as: \begin{equation} o_q' = \sum_{h=1}^{H}a_h \cdot \sum_{k \in \mathcal K_{h_q}} w_k v_k, \qquad w_k = \frac{e^{q \cdot k}}{\sum_{k' \in \mathcal K_{h_q}} e^{q \cdot k'}}, \qquad a_h = \frac{ \sum_{k' \in \mathcal K_{h_q}} e^{q \cdot k'}}{\sum_{n=1}^{H}\sum_{k' \in \mathcal K_{n_q}} e^{q \cdot k'}} \label{merging_scheme} \end{equation} To explain this merging scheme, we will show that under certain assumptions, this merging scheme can lead to exact approximation of the real attention output. We start by listing these assumptions. \begin{assumption}[Sparsity of weights] For any given query $q \in \mathcal Q$, the key set $\mathcal K$ has at most $T$ and at least one vectors $k_i \in \mathcal K_q$ such as: $$ k_i \in \mathcal K_q, \ k_j \not \in \mathcal K_q \Rightarrow \frac{e^{q \cdot k_j}}{e^{q \cdot k_i}} = 0 $$ \label{sparsity} \end{assumption} From Assumption \ref{sparsity}, it follows that at most $T$ and at least one key vector $k_i$ gets a non-zero score, $w_i \neq 0$, after softmax. \begin{assumption}[Fairness of LSH clustering] For any given query $q \in \mathcal Q$ and two keys $k_1, k_2 \in \mathcal K$, if $w_{k_1} \neq 0 \ \wedge w_{k_2} \neq 0$, then $\sum_{n=1}^{H} \sum_{k_1 \in \mathcal K_{n_q}} 1 = \sum_{n=1}^{H} \sum_{k_2 \in \mathcal K_{n_q}} 1$ \label{lsh_fairness} where $H$ denotes the hashing rounds and $\mathcal K_{n_q}$ denotes the chosen key set for query $q$ at hash round $n$. \end{assumption} Assumption \ref{lsh_fairness} simply states that each query is clustered the same number of times with all its' big inner products along the different hashing rounds. \begin{assumption}[Effectiveness of LSH clustering] There is a small constant $H$, which denotes the number of hashing rounds, such as: $$ \forall k \in \mathcal K: \ w_q \neq 0 \Rightarrow \exists n: \ 1 \leq n \leq H \ \wedge \ \ k \in \mathcal K_{q_n}. $$ \label{good_clustering} \end{assumption} The latter assumption states that we need a small number of hashing rounds $H$ to catch all big inner products of a given query. We state the following theorem: \begin{theorem} If Assumptions \ref{sparsity}, \ref{lsh_fairness}, \ref{good_clustering} hold, then our approximation algorithm is exact. \label{exactness} \end{theorem} \begin{proof}[Proof of Theorem \ref{exactness}] With our merging scheme (Equation \ref{merging_scheme}), the attention output is: \begin{equation} o_q' = \sum_{h=1}^{H}\sum_{k\in \mathcal K_{h_q} } \left( \frac{ \sum_{k' \in \mathcal K_{h_q}} e^{q \cdot k'}}{\sum_{n=1}^{H}\sum_{k' \in \mathcal K_{n_q}} e^{q \cdot k'}} \cdot \frac{e^{q \cdot k}}{\sum_{k' \in \mathcal K_{h_q}} e^{q \cdot k'}} \right) \cdot v_k = \sum_{h=1}^{H} \frac{\sum_{k\in \mathcal K_{h_q} } e^{q\cdot k}\cdot v_k }{\sum_{n=1}^{H}\sum_{k' \in \mathcal K_{n_q}} e^{q \cdot k'}} \end{equation} Under Assumption \ref{sparsity}, the dense attention output for this query is the vector: $$ o_q = \sum_{k \in \mathcal K_q} \frac{e^{q \cdot k}}{\sum_{k' \in \mathcal K_q} e^{q \cdot k'}} \cdot v_k $$ where $K_q$ is the set of keys $k_i$ for query $q$ for which $w_i \neq 0$. Under Assumption \ref{good_clustering}, all keys that have big inner product with a given query $q$ are clustered with that query, at least one time. Also, under Assumption \ref{lsh_fairness}, all these keys are clustered the same amount of times with each query. We will denote the amount of a query is clustered with each one of its' big inner products with $N_q$. It holds that: \begin{equation} \sum_{n=1}^{H}\sum_{k' \in \mathcal K_{n_q}} e^{q \cdot k'} = N_q \cdot \sum_{k' \in \mathcal K_q} e^{q\cdot k'} \label{exact_denom} \end{equation} By substitution in Equation \ref{exact_denom}, we get: \begin{equation} o_q = \frac{\sum_{n=1}^{H} \sum_{k\in \mathcal K_{h_q}}e^{q\cdot k}\cdot v_q}{N_q \cdot \sum_{k' \in \mathcal K_q} e^{q\cdot k'}} \label{before_exact} \end{equation} Under Assumptions \ref{sparsity}, \ref{lsh_fairness} small inner products get a zero-score and all big inner products are clustered $N_q$ times each. Thus, we can write for the nominator: $\sum_{n=1}^{H} \sum_{k\in \mathcal K_{h_q}}e^{q\cdot k}\cdot v_q = N_q \sum_{k \in \mathcal K_q} e^{q\cdot k'}$. Substituting to Equation \ref{before_exact}, we get: $$ o_q' = \sum_{k \in K_q}\frac{e^{q \cdot k}}{\sum_{k' \in \mathcal K_q} e^{q \cdot k'}} v_k = o_q $$ \end{proof} In this section, we explained in detail our merging scheme. We also showed that under certain assumptions on the data, this scheme leads to exact approximations of dense attention output. We fully understand that the assumptions are far too tight to hold in practice and since distortion is introduced. However, as we demonstrated in the Experiments section, the distortion is negligible even for large memory reductions, since SMYRF can perform on par (or even better, e.g. GLUE) with dense attention, especially on downstream Natural Language Processing tasks, using a fraction of the original memory. \section{Complexity analysis and speedups} In the paper, we presented shortly the complexity of our algorithm. In this section, we explain it in more detail and we also include speed plots that demonstrate the effectiveness of SMYRF for long sequences. \subsection{Complexity Analysis} For the complexity analysis, we assume for simplicity that $|\mathcal Q|=|\mathcal K| = N$, i.e. the number of available queries is equal to the number of available keys. We run the algorithm $H$ times (i.e. rounds of LSH). Each run has two stages: \begin{itemize} \item[--] Clustering in L clusters (of equal size). For clustering, we hash all points with LSH which requires complexity $O(N)$ and then we sort points based on their hash, which requires complexity $O( N\cdot \log N)$. Overall, the complexity is $O(N \cdot \log N)$. \item[--] Within clusters attention. Attention within each cluster has quadratic cost with respect to the cluster size. Each cluster has size $\frac{N}{L}$, so the complexity of attention in a single cluster is $O(\frac{N^2}{L^2})$. We have $L$ such clusters, and thus the overall complexity is $O(\frac{N^2}{L})$. \end{itemize} The total complexity is: $O\left(H \cdot N \cdot \log N + H \cdot \frac{N^2}{L}\right)$. We choose $L = O(N)$, i.e. each query attends to a small constant number of keys. We obtain complexity: $O(H \cdot N \cdot \log N)$. \subsection{Speedups} In this subsection, we present two speed plots to demonstrate the speed effectiveness of SMYRF for large sequences. The first plot, Figure \ref{fixedmemory}, shows elapsed time for SMYRF-BERT (base) GPU inference for various batch-sequence length configurations. In all these experiments $\textrm{batch size} \times N = 65$K, where $N$ denotes the sequence length. We underline that SMYRF has (almost) constant speed in all these configurations while the speed of dense attention decreases rapidly us the sequence length increases. Notably, SMYRF is already faster than dense attention in sequence length $1024$ tokens. The second plot, Figure \ref{fixedbatch}, shows seconds per iteration for SMYRF-BERT (base) GPU inference for various hashes-cluster configurations. In all these experiments, batch size is fixed to $1$. As shown, all different configurations significantly outperform (in terms of speed) dense attention as the sequence length increases. \begin{figure}[!htp] \centering \includegraphics[width=\textwidth]{figs/speed65k.png} \caption{Elapsed time for SMYRF-BERT (base) GPU inference for various batch-sequence length configurations. Elapsed time for SMYRF is almost constant for all configurations. Elapsed time for dense attention worsens a lot as we increase the sequence length.} \label{fixedmemory} \end{figure} \begin{figure}[!htp] \centering \includegraphics[width=\textwidth]{figs/speed_batch1.png} \caption{Seconds/iteration for SMYRF-BERT (base) GPU inference for various hashes-cluster configurations. In all experiments batch size is fixed to $1$. SMYRF has approximate the same speed with dense attention at 1024 tokens. However, as the number of tokens increases, SMYRF is significantly faster than dense attention.} \label{fixedbatch} \end{figure} \section{Experimental details} \subsection{Natural Language Processing experiments} In this section, we provide some details about the experimental settings for the Natural Language Processing experiments. \subsubsection{IMDB} IMDB~\cite{IMDB} contains 25,000 train and 25,000 dev labeled movie reviews. The task is to identify if a given movie review is positive or negative. The average sentence length in IMDB is 300 tokens and the 95th percentile of context length is 705 tokens. In our experiments, we truncated/padded all sentences to $512$ tokens. For all our experiments, we trained for 3 epochs, with batch size 8. We used Adam~\cite{adam} as our optimizer with learning rate $3\cdot 10^{-5}$. The dataset is available publicly in this link: \href{https://ai.stanford.edu/~amaas/data/sentiment/}{https://ai.stanford.edu/~amaas/data/sentiment/}. The experiments on IMDB run on a single GPU provided by Google Colab. \subsubsection{GLUE} GLUE~\cite{GLUE} is a standard multitask benchmark for Natural Language Processing. For a full description of tasks, dataset statistics and files, please refer to the official website: \href{https://gluebenchmark.com/}{https://gluebenchmark.com/}. Following previous literature (e.g.~\cite{liu2019roberta, devlin2018bert, yang2019xlnet, clark2020electra}), for our GLUE experiments we truncate/pad all input sentences to $128$ tokens. For GLUE, we trained for 3 epochs at batch size 16, warming up for 10\% of the total training time. The learning rate was selected via grid search among the values $\{5\cdot 10^{-5}, 3\cdot 10^{-5}, 2\cdot 10^{-5}\}$. We run the GLUE experiments on TPUs. \subsection{Training SMYRF-BigGAN on Celeba-HQ} In the paper we presented results for training SMYRF-BigGAN from scratch on Celeba-HQ~\cite{celeba}. As explained, we trained on Celeba-HQ (and not ImageNet~\cite{ImageNet}) in order to save computational resources. In this section, we provide the details for these experiments. First of all, as the name suggests, we used as the underlying model, BigGAN~\cite{biggan}. For our experiments we disabled BigGAN's hierarchical latent codes, shared embeddings and skip-z connections since Celeba-HQ has one single class (humans) and these architectural choices were introduced to model multiple classes (e.g. 1000 classes on ImageNet). We also found that for the single-class Celeba-HQ we didn't have to use very large batch sizes for stable training. For all our experiments, we used batch size $32$. Following the BigGAN paper, we used Two Time Scale Update Rule (TTUR)~\cite{FID} with Adam~\cite{adam} optimizer, G$_{\textrm{lr}}=2\cdot 10^{-4}$, D$_{\textrm{lr}}=5\cdot 10^{-5}$, $\beta_1=0$ and $\beta_2=0.999$. BigGAN for resolutions $\{128\times 128, 256\times 256\}$, is trained with a single attention layer at resolution $64\times 64$. The authors mention that they stick attention to low resolution to save computational resources. We take advantage of SMYRF's reduced memory requirements to train with attention at resolution $128\times 128$ and $256\times 256$. For both experiments, we remove the dense attention layer and we add a SMYRF attention layer. Since our goal is to demonstrate the ability of SMYRF layers to train successfully from scratch, there is no reason to use higher (image) resolutions than the attention resolution and thus SMYRF is the final layer (before Tanh~\cite{tanh}) in the architecture. In other words, we train on image resolutions $128\times 128, 256\times 256$ respectively. Training on resolution $128\times 128$ has the side-benefit that we can compare directly with the original BigGAN model (with dense attention at $64\times 64$). As we demonstrated in the Experiments section of the paper, moving attention from $64\times 64$ to $128\times 128$ can lead to $\approx 4\%$ FID~\cite{FID} improvement after $120$K training steps\footnote{We note that in order to save computational resources we stopped training for both models on 120K iterations, before mode-collapse. That means that further training could possibly lead to even better FID scores for both models.}. We present random generated images from SMYRF-BigGAN with attention at resolution $256\times 256$ at Figure~\ref{gen256}. As explained in the Things that did not work section, training with SMYRF from scratch is harder as the sequence length increases. The main reason is that during the early stages of training attention maps are not sparse and thus our approximation's algorithm output is not close to the dense attention output. We noticed that the overall performance of SMYRF-BigGAN-256 is lower compared to SMYRF-BigGAN-128 and the generated images seem slightly less realistic. Despite the aforementioned shortcomings, this experiment demonstrated that it is possible to successfully train an attention GAN with attention at $256\times 256$ resolution on a \textit{single} TPUv3-8 device. The training at $128\times 128$ resolution lasts approximately 1.5 day and at $256\times 256$ resolution approximately 2 days. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{figs/smyrf_256res.jpg} \caption{Generated images from SMYRF-BigGAN on Celeba-HQ-256. Attention at $256\times256$. The trained model uses $50\%$ less memory compared to the memory dense attention would use.} \label{gen256} \end{figure} \section{Things that did not work} In this section, we discuss some negative results we encountered in the process of writing this paper. Our goal is to share our experience with the research community about the observed shortcomings of some approaches so that future research can re-formulate them, reject them or even contradict our findings. We also include some suggestions on potential ways to alleviate such problems that we did not have the time to explore in this paper. \subsection{Learning from scratch under extreme sparsity} Our initial goal was to train a SMYRF model from scratch with extreme memory reductions, e.g. to the magnitude of $99\%$. Such reduction could enable the training of SMYRF-BigGAN with attention at $1024\times1024$. However, our preliminary experiments with BigGAN~\cite{biggan}, failed (mode-collapse very early in the training process). We tried to investigate this further and we found that during the early stages of the training the Frobenius norm of the difference between the SMYRF and the dense attention map is really high. We believe that this is due to the non-sparsity of the attention maps in the early stages of the training. It is also possible that their eigenvalues decay slower which means that their effective rank is higher compared to pre-trained models. One way to solve the problem is to dynamically adapt the memory reduction (e.g. by selecting the number of hashes) during the training. One way to achieve that is to use as many hashes as need to achieve a certain bound for the Frobenius norm. In the early stages of training, we expect that more hashes are needed for an accurate reconstruction. The number of hashes should decay as the training progresses and the attention maps become more sparse and have lower rank. One disadvantage of this approach is that at the early stages of the training, more memory is needed. However, we observed that the period of time in which the attention maps are not very sparse is minor compared to the whole training time for BigGAN and thus this approach can lead to significant savings. We aim to explore this more in the future. \subsection{Better LSH based clustering schemes} The biggest advantage of clustering with an LSH-based scheme is that the attention complexity is linear (compared to K-means clustering for example, see Routing Transformer~\cite{routing_transformer}). However, while inspecting SMYRF, we found that LSH-clustering is the biggest bottleneck to greater performances. For example, if each query attends to at its' top-k (in terms of inner product) keys (instead of the keys assigned with LSH), the performance improves considerably. Finding exactly the top-k keys for each query is expensive (especially in high dimensions) and thus this approach is not viable. However, this observation motivates research in finding even more effective LSH-based clustering schemes. Even though we tried other ALSH variants, we did not manage to find something that works better than our proposed transformations till now. We consider this problem an interesting future direction since ALSH has been widely explored only for the case of a single query and multiple keys. In this paper, we did the first step in extending this to multiple queries, but we are inclined to believe that further research can lead to even better results in this direction. \bibliographystyle{unsrt}
{'timestamp': '2020-10-13T02:24:36', 'yymm': '2010', 'arxiv_id': '2010.05315', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05315'}
arxiv
\section{Introduction}\label{Sec_1} A \textit{$Z$-channel} (also called a \textit{binary asymmetric channel}) is a channel with binary input and binary output where a transmitted $0$ is always received correctly but a transmitted $1$ may be received as either $1$ or $0$. These channels have many applications, for example, some data storage systems and optical communication systems can be modelled using these channels. In 1965, Varshamov and Tenengolts \cite{VATE} introduced an important class of codes, known as the Varshamov--Tenengolts codes or VT-codes, that are capable of correcting asymmetric errors on a $Z$-channel (see also \cite{STYO, VAR}). Levenshtein \cite{LEV1, LEV2}, by giving an elegant decoding algorithm, showed that these codes could also be used for correcting a single deletion or insertion. Using the Varshamov--Tenengolts codes, Gevorkyan and Kabatiansky \cite{GEKA} constructed a class of binary codes of a specific length correcting single localized errors whose cardinality attains the ordinary Hamming bound. \begin{definition} Let $n$ be a positive integer and $0\leq b\leq n$ be a fixed integer. The Varshamov--Tenengolts code $VT_b(n)$ is the set of all binary vectors $\langle y_1,\ldots,y_n \rangle$ such that $$ \sum_{i=1}^{n}iy_i \equiv b \pmod{n+1}. $$ \end{definition} For example, $VT_0(5)=\lbrace 00000, 10001, 01010, 11100, 00111, 11011 \rbrace$, where we have shown vectors as strings. So, $|VT_0(5)|=6$. The \textit{Hamming weight} of a string over an alphabet is defined as the number of non-zero symbols in the string. Equivalently, the Hamming weight of a string is the Hamming distance between that string and the all-zero string of the same length. For example, the Hamming weight of $01010$ is $2$, and the number of codewords in $VT_0(5)$ with Hamming weight $2$ is $2$. Varshamov in his fundamental paper ``On an arithmetic function with an application in the theory of coding" (\cite{VAR2}) proved that the maximum number of codewords in the Varshamov--Tenengolts code $VT_b(n)$ is achieved when $b=0$, that is, $|VT_0(n)| \geq |VT_b(n)|$ for all $b$. Several natural questions arise: What is the number of codewords in the Varshamov--Tenengolts code $VT_b(n)$, that is, $|VT_b(n)|$? Given a positive integer $k$, what is the number of codewords in $VT_b(n)$ with Hamming weight $k$, that is, with exactly $k$ $1$'s? Ginzburg \cite{GIN} in 1967 considered the first question and proved an explicit formula for $|VT_b(n)|$. In this paper, we deal with both questions and obtain explicit formulas for them via a novel approach, namely, \textit{connecting the Varshamov--Tenengolts codes to linear congruences with distinct coordinates}. We even go further and show that the number of solutions of these congruences is related to several other combinatorial problems, some of which have appeared in seemingly unrelated contexts. (For example, as we will discuss in Section~\ref{Sec_4}, Razen, Seberry, and Wehrhahn \cite{RSW} considered two special cases of a function considered in this paper and gave an application in coding theory in finding the complete weight enumerator of a code generated by a circulant matrix.) This provides a general framework and gives new insight into all these problems which might lead to further work. Let us now describe these congruences. Throughout the paper, we use $(a_1,\ldots,a_k)$ to denote the greatest common divisor (gcd) of the integers $a_1,\ldots,a_k$, and write $\langle a_1,\ldots,a_k\rangle$ for an ordered $k$-tuple of integers. Let $a_1,\ldots,a_k,b,n\in \mathbb{Z}$, $n\geq 1$. A linear congruence in $k$ unknowns $x_1,\ldots,x_k$ is of the form \begin{align} \label{cong form} a_1x_1+\cdots +a_kx_k\equiv b \pmod{n}. \end{align} By a solution of (\ref{cong form}), we mean an $\mathbf{x}=\langle x_1,\ldots,x_k \rangle \in \mathbb{Z}_n^k$ that satisfies (\ref{cong form}). The following result, proved by D. N. Lehmer \cite{LEH2}, gives the number of solutions of the above linear congruence: \begin{proposition}\label{Prop: lin cong} Let $a_1,\ldots,a_k,b,n\in \mathbb{Z}$, $n\geq 1$. The linear congruence $a_1x_1+\cdots +a_kx_k\equiv b \pmod{n}$ has a solution $\langle x_1,\ldots,x_k \rangle \in \mathbb{Z}_{n}^k$ if and only if $\ell \mid b$, where $\ell=(a_1, \ldots, a_k, n)$. Furthermore, if this condition is satisfied, then there are $\ell n^{k-1}$ solutions. \end{proposition} Counting the number of solutions of the above congruence with some restrictions on the solutions is also a problem of great interest. As an important example, one can mention the restrictions $(x_i,n)=t_i$ ($1\leq i\leq k$), where $t_1,\ldots,t_k$ are given positive divisors of $n$. The number of solutions of the linear congruences with the above restrictions, which we called {\it restricted linear congruences} in \cite{BKSTT}, was first considered by Rademacher \cite{Rad1925} in 1925 and Brauer \cite{Bra1926} in 1926, in the special case of $a_i=t_i=1$ $(1\leq i \leq k)$. Since then, this problem has been studied, in several other special cases, in many papers (very recently, we studied it in its `most general case' in \cite{BKSTT}) and has found very interesting applications in number theory, combinatorics, geometry, physics, computer science, and cryptography; see \cite{BKS2, BKSTT, BKSTT2, JAWILL} for a detailed discussion about this problem and a comprehensive list of references. Another restriction of potential interest is imposing the condition that all $x_i$ are {\it distinct} modulo $n$. Unlike the first problem, there seems to be very little published on the second problem. Recently, Grynkiewicz et al. \cite{GPP}, using tools from additive combinatorics and group theory, proved necessary and sufficient conditions under which the linear congruence $a_1x_1+\cdots +a_kx_k\equiv b \pmod{n}$, where $a_1,\ldots,a_k,b,n$ ($n\geq 1$) are arbitrary integers, has a solution $\langle x_1,\ldots,x_k \rangle \in \mathbb{Z}_{n}^k$ with all $x_i$ distinct modulo $n$; see also \cite{ADP, GPP} for connections to zero-sum theory. So, it would be an interesting problem to give an explicit formula for the number of such solutions. Quite surprisingly, this problem was first considered, in a special case, by Sch\"{o}nemann \cite{SCH} almost two centuries ago(!) but his result seems to have been forgotten. Sch\"{o}nemann \cite{SCH} proved an explicit formula for the number of such solutions when $b=0$, $n=p$ a prime, and $\sum_{i=1}^k a_i \equiv 0 \pmod{p}$ but $\sum_{i \in I} a_i \not\equiv 0 \pmod{p}$ for all $I\varsubsetneq \lbrace 1, \ldots, k\rbrace$. Very recently, the authors \cite{BKS6} generalized Sch\"{o}nemann's theorem using Proposition~\ref{Prop: lin cong} and a result on graph enumeration recently obtained by Ardila et al. \cite{ACH}. Specifically, we obtained an explicit formula for the number of solutions of the linear congruence $a_1x_1+\cdots +a_kx_k\equiv b \pmod{n}$, with all $x_i$ distinct modulo $n$, when $(\sum_{i \in I} a_i, n)=1$ for all $I\varsubsetneq \lbrace 1, \ldots, k\rbrace$, where $a_1,\ldots,a_k,b,n$ $(n\geq 1)$ are arbitrary integers. Clearly, this result does not resolve the problem in its full generality; for example, it does not cover the important case of $a_i=1$ ($1\leq i\leq k$) and this is what we consider in this paper with an entirely different approach. Specifically, we give an explicit formula for the number $N_n(k,b)$ of such solutions when $a_i=1$ ($1\leq i\leq k$), and do the same when in addition all $x_i$ are \textit{positive} modulo $n$. Our main tools in this paper are properties of Ramanujan sums and of the discrete Fourier transform of arithmetic functions which are reviewed in the next section. In Section~\ref{Sec_3}, we derive the explicit formulas, and discuss applications to the Varshamov--Tenengolts codes. In Section~\ref{Sec_4}, we discuss connections to several other combinatorial contexts. \section{Ramanujan sums and discrete Fourier transform} \label{Sec_2} Let $e(x)=\exp(2\pi ix)$ be the complex exponential with period 1. For integers $m$ and $n$ with $n \geq 1$ the quantity \begin{align}\label{def1} c_n(m) = \mathlarger{\sum}_{\substack{j=1 \\ (j,n)=1}}^{n} e\!\left(\frac{jm}{n}\right) \end{align} is called a {\it Ramanujan sum}. It is the sum of the $m$-th powers of the primitive $n$-th roots of unity, and is also denoted by $c(m,n)$ in the literature. From (\ref{def1}), it is clear that $c_n(-m) = c_n(m)$. Clearly, $c_n(0)=\varphi (n)$, where $\varphi (n)$ is {\it Euler's totient function}. Also, $c_n(1)=\mu (n)$, where $\mu (n)$ is the {\it M\"{o}bius function}. The following theorem, attributed to Kluyver~\cite{KLU}, gives an explicit formula for $c_n(m)$: \begin{theorem} \label{thm:Ram Mob} For integers $m$ and $n$, with $n \geq 1$, \begin{align}\label{for:Ram Mob} c_n(m) = \mathlarger{\sum}_{d\, \mid\, (m,n)} \mu \!\left(\frac{n}{d}\right)d. \end{align} \end{theorem} By applying the M\"{o}bius inversion formula, Theorem~\ref{thm:Ram Mob} yields the following property: For $m,n\geq 1$, \begin{align} \label{Orth1 for cons} \sum_{d\, \mid\, n} c_{d}(m)&= \begin{cases} n, & \text{if $n\mid m$},\\ 0, & \text{if $n\nmid m$}. \end{cases} \end{align} The {\it von Sterneck number} (\cite{von}) is defined by \begin{align}\label{def3} \Phi(m,n)=\frac{\varphi (n)}{\varphi \left(\frac{n}{\left(m,n\right)}\right)}\mu \!\left(\frac{n}{\left(m,n\right)} \right). \end{align} A crucial fact in studying Ramanujan sums and their applications is that they coincide with the von Sterneck number. This result is attributed to Kluyver~\cite{KLU}: \begin{theorem} \label{thm:von rama} For integers $m$ and $n$, with $n \geq 1$, we have \begin{align}\label{von rama for} \Phi(m,n)=c_n(m). \end{align} \end{theorem} A function $f:\mathbb{Z} \to \mathbb{C}$ is called {\it periodic} with period $n$ (also called {\it $n$-periodic} or {\it periodic} modulo $n$) if $f(m + n) = f(m)$, for every $m\in \mathbb{Z}$. In this case $f$ is determined by the finite vector $(f(1),\ldots,f(n))$. From (\ref{def1}) it is clear that $c_n(m)$ is a periodic function of $m$ with period $n$. We define the {\it discrete Fourier transform} (DFT) of an $n$-periodic function $f$ as the function $\widehat{f}={\cal F}(f)$, given by \begin{align}\label{FFT1} \widehat{f}(b)=\mathlarger{\sum}_{j=1}^{n}f(j)e\! \left(\frac{-bj}{n}\right)\quad (b\in \mathbb{Z}). \end{align} The standard representation of $f$ is obtained from the Fourier representation $\widehat{f}$ by \begin{align}\label{FFT2} f(b)=\frac1{n} \mathlarger{\sum}_{j=1}^{n}\widehat{f}(j)e\!\left(\frac{bj}{n}\right) \quad (b\in \mathbb{Z}), \end{align} which is the {\it inverse discrete Fourier transform} (IDFT); see, e.g., \cite[p.\ 109]{MOVA}. \section{Solutions with distinct coordinates}\label{Sec_3} In this section, we obtain an explicit formula for the number of solutions $\langle x_1,\ldots,x_k \rangle \in \mathbb{Z}_{n}^k$ of the linear congruence $x_1+\cdots +x_k\equiv b \pmod{n}$, with all $x_i$ distinct modulo $n$. First, we need some preliminary results. \begin{lemma}\label{lem: cyclo 1} Let $n$ be a positive integer and $m$ be a non-negative integer. We have $$ \mathlarger{\prod}_{j=1}^{n}\left(1-ze^{2\pi ijm/n}\right)=(1-z^{\frac{n}{d}})^d, $$ where $d=(m,n)$. \end{lemma} \begin{proof} It is well-known that (see, e.g., \cite[p. 167]{STAN}) $$ 1-z^n=\mathlarger{\prod}_{j=1}^{n}\left(1-ze^{2\pi ij/n}\right). $$ Now, letting $d=(m,n)$, we obtain \begin{align*} \mathlarger{\prod}_{j=1}^{n}\left(1-ze^{2\pi ijm/n}\right) &= \mathlarger{\prod}_{j=1}^{n} \left(1-ze^{2\pi ij\frac{m/d}{n/d}}\right)\\ &= \left(\mathlarger{\prod}_{j=1}^{n/d}\left(1-ze^{2\pi ij\frac{m/d}{n/d}}\right)\right)^d\\ &{\stackrel{(\frac{m}{d},\frac{n}{d})=1}{=}} \left(\mathlarger{\prod}_{j=1}^{n/d}\left(1-ze^{\frac{2\pi ij}{n/d}}\right)\right)^d=(1-z^{\frac{n}{d}})^d. \end{align*} \end{proof} Similarly, we can prove that: \begin{lemma}\label{lem: cyclo 2} Let $n$ be a positive integer and $m$ be a non-negative integer. We have $$ \mathlarger{\prod}_{j=1}^{n}\left(z-e^{2\pi ijm/n}\right)=(z^{\frac{n}{d}}-1)^d, $$ where $d=(m,n)$. \end{lemma} Now, we simply get: \begin{corollary}\label{cor: cyclo 1} Let $n$ be a positive integer and $m$, $k$ be non-negative integers. The coefficient of $z^k$ in $$ \mathlarger{\prod}_{j=1}^{n}\left(1+ze^{2\pi ijm/n}\right), $$ is $(-1)^{k+\frac{kd}{n}}\binom{d}{\frac{kd}{n}}$, where $d=(m,n)$. Note that the binomial coefficient $\binom{d}{\frac{kd}{n}}$ equals zero if $\frac{kd}{n}$ is not an integer. \end{corollary} Now, we are ready to obtain an explicit formula for the number of solutions of the linear congruence. \begin{theorem} \label{main thm dist ai=1} Let $n$ be a positive integer and $b \in \mathbb{Z}_n$. The number $N_n(k,b)$ of solutions $\langle x_1,\ldots,x_k \rangle \in \mathbb{Z}_{n}^k$ of the linear congruence $x_1+\cdots +x_k\equiv b \pmod{n}$, with all $x_i$ distinct modulo $n$, is \begin{align} \label{main thm dist ai=1: for} N_n(k,b)=\frac{(-1)^k k!}{n}\mathlarger{\sum}_{d\, \mid \, (n,\;k)}(-1)^{\frac{k}{d}}c_{d}(b)\binom{\frac{n}{d}}{\frac{k}{d}}. \end{align} \end{theorem} \begin{proof} It is well-known that (see, e.g., \cite[pp. 3-4]{GUP}) the number of partitions of $b$ into exactly $k$ \textit{distinct} parts each taken from the given set $A$, is the coefficient of $q^bz^k$ in $$ \mathlarger{\prod}_{j \in A}\left(1+zq^j\right). $$ Now, take $A=\mathbb{Z}_n$ and $q=e^{2\pi im/n}$, where $m$ is a non-negative integer. Then, the number $P_n(k,b)$ of partitions of $b$ into exactly $k$ \textit{distinct} parts each taken from $\mathbb{Z}_n$ (that is, the number of solutions of the above linear congruence, with all $x_i$ distinct modulo $n$, if order does not matter), is the coefficient of $e^{2\pi ibm/n}z^k$ in $$ \mathlarger{\prod}_{j=1}^{n}\left(1+ze^{2\pi ijm/n}\right). $$ This in turn implies that $$ \mathlarger{\sum}_{b=1}^{n}P_n(k,b)e^{2\pi ibm/n} = \text{the coefficient of $z^k$ in $\mathlarger{\prod}_{j=1}^{n}\left(1+ze^{2\pi ijm/n}\right)$}. $$ Let $e(x)=\exp(2\pi ix)$. Note that $N_n(k,b)=k!P_n(k,b)$. Now, using Corollary~\ref{cor: cyclo 1}, we get $$ \mathlarger{\sum}_{b=1}^{n}N_n(k,b)e\left(\frac{bm}{n}\right) = (-1)^{k+\frac{kd}{n}}k!\binom{d}{\frac{kd}{n}}, $$ where $d=(m,n)$. Now, by (\ref{FFT1}) and (\ref{FFT2}), we obtain \begin{align*} N_n(k,b) &= \frac{(-1)^{k}k!}{n}\mathlarger{\sum}_{m=1}^{n}(-1)^{\frac{kd}{n}}e\left(\frac{-bm}{n}\right)\binom{d}{\frac{kd}{n}}\\ &= \frac{(-1)^{k}k!}{n}\mathlarger{\sum}_{d\, \mid \, n}\mathlarger{\sum}_{\substack{m=1 \\ (m,\;n)=d}}^{n}(-1)^{\frac{kd}{n}}e\left(\frac{-bm}{n}\right)\binom{d}{\frac{kd}{n}}\\ &{\stackrel{m'=m/d}{=}} \;\; \frac{(-1)^{k}k!}{n}\mathlarger{\sum}_{d\, \mid \, n}\mathlarger{\sum}_{\substack{m'=1 \\ (m',\;n/d)=1}}^{n/d}(-1)^{\frac{kd}{n}}e\left(\frac{-bm'}{n/d}\right)\binom{d}{\frac{kd}{n}}\\ &= \frac{(-1)^{k}k!}{n}\mathlarger{\sum}_{d\, \mid \, n}(-1)^{\frac{kd}{n}}c_{n/d}(-b)\binom{d}{\frac{kd}{n}}\\ &= \frac{(-1)^{k}k!}{n}\mathlarger{\sum}_{d\, \mid \, n}(-1)^{\frac{kd}{n}}c_{n/d}(b)\binom{d}{\frac{kd}{n}}\\ &= \frac{(-1)^{k}k!}{n}\mathlarger{\sum}_{d\, \mid \, n}(-1)^{\frac{k}{d}}c_{d}(b)\binom{\frac{n}{d}}{\frac{k}{d}}\\ &= \frac{(-1)^{k}k!}{n}\mathlarger{\sum}_{d\, \mid \, (n,\;k)}(-1)^{\frac{k}{d}}c_{d}(b)\binom{\frac{n}{d}}{\frac{k}{d}}. \end{align*} \end{proof} \begin{corollary} \label{special cases: b=0,1} If $n$ or $k$ is odd then from (\ref{main thm dist ai=1: for}) we obtain the following important special cases of the function $P_n(k,b)=\frac{1}{k!}N_n(k,b)$: \begin{align} \label{special case: b=0} P_n(k,0)= \frac{1}{n}\mathlarger{\sum}_{d\, \mid \, (n,\;k)}\varphi(d)\binom{\frac{n}{d}}{\frac{k}{d}}, \end{align} \begin{align} \label{special case: b=1} P_n(k,1)= \frac{1}{n}\mathlarger{\sum}_{d\, \mid \, (n,\;k)}\mu(d)\binom{\frac{n}{d}}{\frac{k}{d}}. \end{align} \end{corollary} \begin{corollary} If $(n,k)=1$ then (\ref{main thm dist ai=1: for}) is independent of $b$ and simplifies as $$N_n(k)=\frac{k!}{n}\binom{n}{k}.$$ (Of course, this can also be proved directly.) If in addition we have $n=2k+1$ then $$ P_n(k)=\frac{1}{k!}N_n(k)=\frac{1}{2k+1}\binom{2k+1}{k}=\frac{1}{k+1}\binom{2k}{k}, $$ which is the Catalan number. \end{corollary} \begin{rema} Using (\ref{Orth1 for cons}), it is easy to see that (\ref{main thm dist ai=1: for}) also works when $k=0$. \end{rema} Now, we introduce the important function $T_n(b)$ which is the sum of $P_n(k,b)$ over $k$. There are several interpretations for the function $T_n(b)$, for example, $T_n(b)$ can be interpreted as the number of subsets of the set $\lbrace 1, 2, \ldots, n \rbrace$ which sum to $b$ modulo $n$. \begin{corollary}\label{nice function} Let $T_n(b):=\sum_{k=0}^{n}\frac{1}{k!}N_n(k,b)=\sum_{k=0}^{n}P_n(k,b)$. Then we have \begin{align} \label{nice function: for} T_n(b)=\frac{1}{n}\mathlarger{\sum}_{\substack{d\, \mid \, n \\ d \; \textnormal{odd}}}c_{d}(b)2^{\frac{n}{d}}. \end{align} \end{corollary} \begin{proof} We have \begin{align*} T_n(b)&= \mathlarger{\sum}_{k=0}^{n} \frac{(-1)^{k}}{n}\mathlarger{\sum}_{d\, \mid \, (n,\;k)}(-1)^{\frac{k}{d}}\binom{\frac{n}{d}}{\frac{k}{d}}c_{d}(b)\\ &= \frac{1}{n}\mathlarger{\sum}_{d\, \mid \, n}c_{d}(b)\mathlarger{\sum}_{\substack{k=0 \\ d\, \mid \,k}}^{n}(-1)^{k+\frac{k}{d}}\binom{\frac{n}{d}}{\frac{k}{d}}\\ &= \frac{1}{n}\mathlarger{\sum}_{\substack{d\, \mid \, n \\ d \; \textnormal{odd}}}c_{d}(b)\mathlarger{\sum}_{\substack{k=0 \\ d\, \mid \,k}}^{n}(-1)^{k+\frac{k}{d}}\binom{\frac{n}{d}}{\frac{k}{d}} +\frac{1}{n}\mathlarger{\sum}_{\substack{d\, \mid \, n \\ d \; \textnormal{even}}}c_{d}(b)\mathlarger{\sum}_{\substack{k=0 \\ d\, \mid \,k}}^{n}(-1)^{k+\frac{k}{d}}\binom{\frac{n}{d}}{\frac{k}{d}} \\ &=\frac{1}{n}\mathlarger{\sum}_{\substack{d\, \mid \, n \\ d \; \textnormal{odd}}}c_{d}(b)2^{\frac{n}{d}}. \end{align*} Note that in the last equality we have used the fact that if $d \mid n$ and $d$ is even then $$ \mathlarger{\sum}_{\substack{k=0 \\ d\, \mid \,k}}^{n}(-1)^{k+\frac{k}{d}}\binom{\frac{n}{d}}{\frac{k}{d}} = \mathlarger{\sum}_{\substack{k=0 \\ d\, \mid \,k}}^{n}(-1)^{\frac{k}{d}}\binom{\frac{n}{d}}{\frac{k}{d}}= 0. $$ \end{proof} What is the number of subsets of the set $\lbrace 1, 2, \ldots, n-1 \rbrace$ which sum to $b$ modulo $n$? Using Corollary~\ref{nice function}, we can obtain an explicit formula for the number of such subsets (see also \cite{MAZ}). \begin{corollary}\label{nice function 2} The number $T'_n(b)$ of subsets of the set $\lbrace 1, 2, \ldots, n-1 \rbrace$ which sum to $b$ modulo $n$ is \begin{align} \label{nice function 2: for} T'_n(b)=\frac{1}{2}T_n(b)=\frac{1}{2n}\mathlarger{\sum}_{\substack{d\, \mid \, n \\ d \; \textnormal{odd}}}c_{d}(b)2^{\frac{n}{d}}. \end{align} \end{corollary} \begin{proof} Let $A$ be a subset of the set $\lbrace 1, 2, \ldots, n-1 \rbrace$ which sum to $b$ modulo $n$. Then $A$ and $A\cup \lbrace n \rbrace$ are both subsets of the set $\lbrace 1, 2, \ldots, n \rbrace$ and both sum to $b$ modulo $n$. Therefore, $T'_n(b)=\frac{1}{2}T_n(b)$. \end{proof} Ginzburg \cite{GIN} in 1967 proved an explicit formula for the number of codewords in the $q$-ary Varshamov--Tenengolts codes, where $q$ is an arbitrary positive integer. This result was later rediscovered by Stanley and Yoder \cite{STYO} in 1973, and in the binary case (that is, when $q=2$) by Sloane \cite{SLO} in 2002. Now, we give a short proof for the binary case which we derive as a consequence of our results. \begin{corollary}\label{VT exa tot} The number $|VT_b(n)|$ of codewords in the Varshamov--Tenengolts code $VT_b(n)$ is \begin{align} \label{VT exa tot: for} |VT_b(n)|=\frac{1}{2(n+1)}\mathlarger{\sum}_{\substack{d\, \mid \, n+1 \\ d \; \textnormal{odd}}}c_{d}(b)2^{\frac{n+1}{d}}. \end{align} \end{corollary} \begin{proof} Let $\langle y_1,\ldots,y_n \rangle$ be a codeword in $VT_b(n)$. Note that $\sum_{i=1}^{n}iy_i$ is just the sum of some elements of the set $\lbrace 1, 2, \ldots, n \rbrace$. Therefore, finding the number of codewords in $VT_b(n)$ boils down to finding the number of subsets of the set $\lbrace 1, 2, \ldots, n \rbrace$ which sum to $b$ modulo $n+1$. The result now follows by a direct application of Corollary~\ref{nice function 2}. \end{proof} In some applications (for example, in coding theory) we also need to consider the case that all $x_i$ are \textit{positive} and \textit{distinct} modulo $n$. Now, we obtain an explicit formula for the number of such solutions. \begin{theorem} \label{main thm dist pos ai=1} Let $n$ be a positive integer and $b \in \mathbb{Z}_n$. The number $N_n^{>0}(k,b)$ of solutions $\langle x_1,\ldots,x_k \rangle \in \mathbb{Z}_{n}^k$ of the linear congruence $x_1+\cdots +x_k\equiv b \pmod{n}$, with all $x_i$ positive and distinct modulo $n$, is \begin{align} \label{main thm dist pos ai=1: for} N_n^{>0}(k,b)=\frac{(-1)^k k!}{n}\mathlarger{\sum}_{d\, \mid \, n}(-1)^{\lfloor\frac{k}{d}\rfloor}c_{d}(b)\binom{\frac{n}{d}-1}{\lfloor\frac{k}{d}\rfloor}. \end{align} \end{theorem} \begin{proof} Clearly, $N_n^{>0}(k,b)=N_n(k,b)-N_n^{0}(k,b)$, where $N_n^{0}(k,b)$ denotes the number of solutions $\langle x_1,\ldots,x_k \rangle \in \mathbb{Z}_{n}^k$ with all $x_i$ distinct modulo $n$ and one of $x_i$ is zero modulo $n$. Also, clearly, $N_n^{0}(k,b)=kN_n^{>0}(k-1,b)$. Thus, \begin{align}\label{relation bet N and N>0} N_n(k,b)=N_n^{>0}(k,b)+kN_n^{>0}(k-1,b). \end{align} Now, we use Theorem~\ref{main thm dist ai=1}. We have \begin{align*} N_n(k,b)&= \frac{(-1)^k k!}{n}\mathlarger{\sum}_{d\, \mid \, (n,\;k)}(-1)^{\frac{k}{d}}c_{d}(b)\binom{\frac{n}{d}}{\frac{k}{d}}\\ &= \frac{(-1)^k k!}{n}\mathlarger{\sum}_{d\, \mid \, (n,\;k)}(-1)^{\frac{k}{d}}c_{d}(b)\left(\binom{\frac{n}{d}-1}{\frac{k}{d}}+\binom{\frac{n}{d}-1}{\frac{k}{d}-1}\right)\\ &= \frac{(-1)^k k!}{n}\mathlarger{\sum}_{d\, \mid \, n}c_{d}(b)\left((-1)^{\frac{k}{d}}\binom{\frac{n}{d}-1}{\frac{k}{d}}-(-1)^{\frac{k}{d}-1}\binom{\frac{n}{d}-1}{\frac{k}{d}-1}\right)\\ &= \frac{(-1)^k k!}{n}\mathlarger{\sum}_{d\, \mid \, n}c_{d}(b)\left((-1)^{\lfloor\frac{k}{d}\rfloor}\binom{\frac{n}{d}-1}{\lfloor\frac{k}{d}\rfloor}-(-1)^{\lfloor\frac{k-1}{d}\rfloor}\binom{\frac{n}{d}-1}{\lfloor\frac{k-1}{d}\rfloor}\right)\\ &= \frac{(-1)^k k!}{n}\mathlarger{\sum}_{d\, \mid \, n}(-1)^{\lfloor\frac{k}{d}\rfloor}c_{d}(b)\binom{\frac{n}{d}-1}{\lfloor\frac{k}{d}\rfloor}\\ &+k\frac{(-1)^{k-1} (k-1)!}{n}\mathlarger{\sum}_{d\, \mid \, n}(-1)^{\lfloor\frac{k-1}{d}\rfloor}c_{d}(b)\binom{\frac{n}{d}-1}{\lfloor\frac{k-1}{d}\rfloor}. \end{align*} Note that in the fourth equality above we have used the fact that $\lfloor\frac{k}{d}\rfloor=\lfloor\frac{k-1}{d}\rfloor+1$ if $d \mid k$, and $\lfloor\frac{k}{d}\rfloor=\lfloor\frac{k-1}{d}\rfloor$ if $d\nmid k$. Now, recalling (\ref{relation bet N and N>0}) we obtain the desired result. \end{proof} We believe that Theorem~\ref{main thm dist pos ai=1} is also a strong tool and might lead to interesting applications. Denote by $VT_b^{1,k}(n)$ the set of codewords in the Varshamov--Tenengolts code $VT_b(n)$ with Hamming weight $k$. Theorem~\ref{main thm dist pos ai=1} immediately gives an explicit formula for the number of such codewords. This result is useful in the study of a class of binary codes that are immune to single repetitions \cite{DOAN}. \begin{corollary}\label{VT exa k1s} The number $|VT_b^{1,k}(n)|$ of codewords in the Varshamov--Tenengolts code $VT_b(n)$ with Hamming weight $k$ is \begin{align} \label{VT exa k1s: for} |VT_b^{1,k}(n)|=\frac{(-1)^k}{n+1}\mathlarger{\sum}_{d\, \mid \, n+1}(-1)^{\lfloor\frac{k}{d}\rfloor}c_{d}(b)\binom{\frac{n+1}{d}-1}{\lfloor\frac{k}{d}\rfloor}. \end{align} \end{corollary} \begin{proof} Let $\langle y_1,\ldots,y_n \rangle$ be a codeword in $VT_b(n)$ with Hamming weight $k$, that is, with exactly $k$ $1$'s. Denote by $x_j$ the position of the $j$th one. Note that $1\leq j \leq k$ and $1 \leq x_1 < x_2 < \cdots < x_k \leq n$. Now, we have $$ \sum_{i=1}^{n}iy_i \equiv b \pmod{n+1} \Longleftrightarrow x_1+\cdots +x_k\equiv b \pmod{n+1}. $$ Therefore, finding the number of codewords in $VT_b(n)$ with Hamming weight $k$ boils down to finding the number of solutions $\langle x_1,\ldots,x_k \rangle \in \mathbb{Z}_{n+1}^k$ of the linear congruence $x_1+\cdots +x_k\equiv b \pmod{n+1}$, with all $x_j$ positive and distinct modulo $n+1$, and with disregarding the order of the coordinates. The result now follows by a direct application of Theorem~\ref{main thm dist pos ai=1}. \end{proof} \begin{rema} There is an earlier interesting result of Dolecek and Anantharam \cite{DOAN} which gives the formula (\ref{VT exa k1s: for}) in a special case where the Hamming weight is dependent on the modulus, but here we give a more general treatment where the Hamming weight is \textit{arbitrary}. Of course, the expression (3.7) in their paper is exactly the same as our formula (\ref{main thm dist ai=1: for}), so it is an interesting problem to prove a 1-1 correspondence between these two results. \end{rema} \section{More connections}\label{Sec_4} Interestingly, some special cases of the functions $P_n(k,b)$, $N_n(k,b)$, $T_n(b)$, and $T'_n(b)$ that we studied in this paper have appeared in a wide range of combinatorial problems, sometimes in seemingly unrelated contexts. Here we briefly mention some of these connections. It would be interesting to prove 1-1 correspondences between these interpretations. \bigskip \textbf{Ordered partitions acted upon by cyclic permutations.} Consider the set of all ordered partitions of a positive integer $n$ into $k$ parts acted upon by the cyclic permutation $(1 2 \ldots k)$. Razen, Seberry, and Wehrhahn \cite{RSW} obtained explicit formulas for the cardinality of the resulting family of orbits and for the number of orbits in this family having exactly $k$ elements. These formulas coincide with the expressions for $P_n(k,0)$ and $P_n(k,1)$, respectively, when $n$ or $k$ is odd (see Corollary~\ref{special cases: b=0,1}). Razen et al. \cite{RSW} also discussed an application in coding theory in finding the complete weight enumerator of a code generated by a circulant matrix. \bigskip \textbf{Permutations with given cycle structure and descent set.} Gessel and Reutenauer \cite{GERE} counted permutations in the symmetric group $S_n$ with a given cycle structure and descent set. One of their results gives an explicit formula for the number of $n$-cycles with descent set $\lbrace k \rbrace$, which coincides with the expression for $P_n(k,1)$ when $n$ or $k$ is odd. \bigskip \textbf{Fixed-density necklaces and Lyndon words.} If $n$ or $k$ is odd then the expressions for $P_n(k,0)$ and $P_n(k,1)$ give, respectively, the number of fixed-density binary necklaces and fixed-density binary Lyndon words of length $n$ and density $k$, as described by Gilbert and Riordan \cite{GIRI}, and Ruskey and Sawada \cite{RUSA}. \bigskip \textbf{Necklace polynomial.} The function $T_n(b)$ is closely related to the polynomial $$ M(q, n)= \frac{1}{n}\sum_{d\, \mid \, n}\mu(d)q^{\frac{n}{d}}, $$ which is called the \textit{necklace polynomial} of degree $n$ (it is easy to see that $M(q, n)$ is integer-valued for all $q \in \mathbb{Z}$). In fact, if $n$ is odd then $M(2, n)=T_n(1)$. The necklace polynomials turn up in various contexts in combinatorics and algebra. \bigskip \textbf{Quasi-necklace polynomial.} The function $T'_n(b)$ is also closely related to the polynomial $$ M'(q, n)= \frac{1}{2n}\sum_{d\, \mid \, n}\mu(d)q^{\frac{n}{d}}, $$ that we call the \textit{quasi-necklace polynomial} of degree $n$. In fact, if $n$ is odd then $M'(2, n)=T'_n(1)$. The quasi-necklace polynomials also turn up in various contexts in combinatorics. For example, they appear as: \begin{itemize} \item the number of transitive unimodal cyclic permutations obtained by Weiss and Rogers \cite{WERO} (motivated by problems related to the structure of the set of periodic orbits of one-dimensional dynamical systems) using methods related to the work of Milnor and Thurston \cite{MITH}. See also \cite{THIB} which gives a generating function for the number of unimodal permutations with a given cycle structure; \item the number of periodic patterns of the tent map \cite{AREL}. \end{itemize} \section*{Acknowledgements} The authors would like to thank the anonymous referees for a careful reading of the paper and helpful suggestions. During the preparation of this work the first author was supported by a Fellowship from the University of Victoria (UVic Fellowship).
{'timestamp': '2020-10-13T02:27:23', 'yymm': '2010', 'arxiv_id': '2010.05415', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05415'}
arxiv
\section{Introduction} Recently, graph data are utilized in more and more application and research domains. Graph neural networks (GNN) that can learn a distributed representation for a graph or a node in a graph are widely applied to a variety of areas for graph data analysis, such as social network analysis \cite{hamilton2017inductive,ying2018graph}, molecular structure inference \cite{duvenaud2015convolutional,gilmer2017neural}, text mining \cite{yao2019graph,peng2018large}, clinical decision making \cite{li2018classifying,mao2019medgcn} and image processing \cite{mao2019imagegcn,garcia2017few}, etc. GNN recursively updates the representation of a node in a graph by aggregating the feature vectors of its neighbors and itself \cite{hamilton2017inductive,morris2019weisfeiler,xu2019powerful}. The graph-level representation can then be obtained through aggregating the final representations of all the nodes in the graph. The generated representations can feed into a prediction model for different learning tasks, such as node classification and graph classification, and the whole model can be trained in an end-to-end fashion. In GNN, the aggregation rule plays a vital role in learning informative representations for the nodes and the entire graph. There are many GNN variants with different aggregation rules proposed to achieve good performances in different tasks, e.g., graph convolutional networks (GCN) \cite{kipf2017semi} and GraphSAGE \cite{hamilton2017inductive} for node-level aggregation and deep graph convolutional neural network (DGCNN) \cite{zhang2018end} and capsule neural network (CapsNet) \cite{xinyi2019capsule} for graph-level aggregation. However, most of the existing GNN aggregation rules are designed based on a fixed non-injective pooling function, e.g., max pooling and mean pooling. The fixed non-injective pooling usually loses some information and may generate the same embedding for different nodes or graphs. For example, for the graph with attributed nodes in Figure \ref{fig:illustration}(a), mean pooling or sum aggregation on the neighborhoods generates the same neighborhood representation for all the nodes (Figure \ref{fig:illustration}(d)), thus cannot capture any meaningful structure information. Xu et al. \cite{xu2019powerful} showed that a powerful GNN can at most achieve the discriminative power as Weisfeiler-Lehman graph isomorphism test (WL test) which can discriminate a broad class graphs \cite{weisfeiler1968reduction}, and proposed the powerful graph isomorphism network (GIN). However, the theoretical framework of GIN is under the assumption that the input feature space is countable, which makes GIN less expressive when applied to graphs with continuous attributes, i.e., attributed graphs. \begin{figure*} \centering \includegraphics[width=.8\linewidth]{fig_ExpGNN.pdf} \caption{An overview of our framework on an exemplar attributed graph in one iteration. (a) Original graph with attributed nodes; (b) Graph nodes are represented by the corresponding attribute and neighborhood set through WL test; (c) The node vector representations after an injective set function on neighborhood sets, here the set function is $f(X)=\sum_{x \in X}(1,x, x^2, x^3, x^4)$; (d) A non-injective alternative of our injective set function in other GNNs, the node representations after mean pooling or sum aggregation of neighborhood sets. After aggregation, the node information remain unchanged, node B and D still have the same representation despite their different neighborhoods.} \label{fig:illustration} \end{figure*} Here, we present a theoretical framework that can guide us to design highly expressive GNNs for general graphs with continuous attributes. Our framework is illustrated in Figure \ref{fig:illustration}, first, each node with attribute in a graph (Figure \ref{fig:illustration}(a)) is converted to a tuple representation containing its attribute and a set of its neighborhood attributes through one WL test iteration (Figure \ref{fig:illustration}(b)), then we design a continuous injective set function to map each neighborhood to a vector (Figure \ref{fig:illustration}(c)). After certain learnable transformations, the graph with node embeddings can go the next iteration. After \textit{k} iterations, a node representation can capture the structural information and attribute information within the node’s \textit{k}-hop neighborhood. Due to the continuous injective set mapping, equivalent nodes in the graph have the same representation and vice versa. Our code is available at \url{ https://github.com/mocherson/Exp_GNN}. Our main contributions are summarized as follows. (1) We present a theoretical framework to guide the design of highly expressive GNNs for general attributed graphs. (2) Using the framework, we develop two variants of ExpGNN with a customized continuous injective set function and a learned continuous set function, respectively. (3) We validate our models on multiple benchmark datasets including simple graphs and attributed graphs for graph classification, the experimental results demonstrate that our models can achieve state-of-the-art performances on most of the benchmarks. \section{Preliminaries} A graph $G$ is denoted as $(V,E)$, where $V$ is the node set (assume size $n$) corresponding to a node feature matrix $X\in \mathbb{R}^{n\times d}$, and $E$ is the set of edges corresponding an adjacency matrix $A\in\{0,1\}^{n\times n}$. We focus on node features in this paper, and leave edge features for future work. \textbf{Graph neural networks.} GNNs update a node representation by aggregating the node's neighborhood and then combine the neighborhood representation and the node's current representation. Formally, the propagation rule of a GNN layer can be represented as \begin{equation}\label{eq:combine} H^{(k+1)}(v) = f_{C}^{(k)} \left(H^{(k)}(v) , f_{A}^{(k)}\left( \left\{H^{(k)}(w) | w\in \mathcal{N}(v) \right\}\right) \right) \end{equation} where $H^{(k)}(v)$ is the representation vector of node $v$ in the $k$th layer, and $H^{(0)}(v)$ is initialized with $X(v)$, the original attributes of node $v$. $\mathcal{N}(v)$ is the neighborhood of $v$. $f_{A}^{(k)}(\cdot)$ AGGREGATEs over a neighborhood and $f_{C}^{(k)}(\cdot)$ COMBINEs the node's current representation and its neighborhood’s representation in the $k$th layer. For node embedding, the node representation of the final layer $H^{(K)}(v)$ (suppose a total of $K$ layers) is considered as an informative representation that could be used for node classification. For graph or subgraph embedding, another READOUT function $f_{R}(\cdot)$ is employed to obtain the graph-level representation $h_G$ by aggregating the final representations of nodes in the graph or subgraph $G$, i.e., \begin{equation}\label{eq:readout} H_G = f_{R} \left( \left\{H^{(K)}(v) | v\in G \right\}) \right) \end{equation} $f_{A}(\cdot)$, $f_{C}(\cdot)$ and $f_{R}(\cdot)$ are all crucial for the expressive capability of a GNN. $f_{A}(\cdot)$ and $f_{R}(\cdot)$ are set functions that maps a set to a vector, they can be simple summations or sophisticated graph-level pooling functions \cite{ying2018hierarchical,zhang2018end}. $f_{C}(\cdot)$ operates on two vectors, it can be usually modeled by a multi-layer perceptron (MLP) or linear function on the concatenated vector. \textbf{The expressive capability of GNN.} Lemma 2 and Theorem 3 in Xu et al.'s work \cite{xu2019powerful} describe the relation between GNNs and WL test in expressive capability for graphs. We outline them as follows, refer to \cite{xu2019powerful} for the proofs. \begin{lemma} If the WL test decides two graphs $G_1$ and $G_2$ are isomorphic, any GNNs defined by Eq. \ref{eq:combine} and \ref{eq:readout} will map $G_1$ and $G_2$ to the same embedding. \end{lemma} \begin{theorem} \label{th:gnnpower} If WL test decides two graphs $G_1$ and $G_2$ are not isomorphic, a GNN with sufficiently many GNN layers defined by Eq. \ref{eq:combine} and \ref{eq:readout} can also map $G_1$ and $G_2$ to different embeddings if the functions $f_{A}(\cdot)$, $f_{C}(\cdot)$ and $f_{R}(\cdot)$ are all injective. \end{theorem} The above Lemma and Theorem can guide us to design a GNN that has the discriminative power equal to WL test. The key is to design injective functions for $f_{A}(\cdot)$, $f_{C}(\cdot)$ and $f_{R}(\cdot)$. An injective function for $f_{C}(\cdot)$ that operates on two vectors can be easily obtained by concatenating the two vectors. But designing an injective function for $f_{A}(\cdot)$ or $f_{R}(\cdot)$ that operates on a set is not trivial, because a set can have variable number of elements, and the operation on the set elements must be permutation-invariant. Moreover, the continuity of these functions are all crucial to the model expressive capability, which is not considered in \cite{xu2019powerful}. In the following, we will discuss how to design the continuous injective aggregation function on a set and further expressive GNNs. \section{Methods} \subsection{Set representation} A set function is a function defined in a domain that is a collection of sets. In a finite graph, the neighborhood of each node is considered as a finite set. Thus, in this paper, we only consider set functions of finite sets. A continuous set function is of real importance in practice \cite{wagstaff2019limitations}. Generally, in a continuous function, sufficiently small changes in the input result in arbitrarily small changes in the output at every point in the domain. The continuity of a function ensures that the change in output is very slight if the input is altered slightly by any reason such as truncating to machine precision. In this paper, we talk about the ordinary continuity where the continuity of function $f(\mathbf{x})$ at point $\mathbf{c}$ is defined by the limitation as $\lim_{\mathbf{x}\rightarrow \mathbf{c}} f(\mathbf{x}) = f(\mathbf{c})$ For $M\in \mathbb{N}$, a set function $f(X)$ defined in domain $\mathcal{X}=\{X | X\subset \mathbb{R}^d, |X|\leq M\}$ can be represented as a sequence of permutation-invariant functions $f_i$ for different set sizes, i.e., \begin{equation}\label{eq:setfunction} f(X)=f_i(x_1,\cdots,x_i) \quad if \quad |X|=i\leq M, x_1,\cdots,x_i \in X \end{equation} \begin{definition}[Continuous set function] For $M \in \mathbb{N}$ and a set function $f(X)$ defined in domain $\mathcal{X}_M=\{X \mid X \subset \mathbb{R}^d,|X| \le M\}$, $f(X)$ can be represented as Eq. \ref{eq:setfunction}, if $f_i(x_1,\cdots,x_i)$ is continuous in the Euclidean space for every $i\leq M$, we call $f(X)$ a continuous set function. \end{definition} Obviously, a continuous set function can also have the property that sufficiently small changes in the input (a sufficiently small change will not change the set size) result in arbitrarily small changes in the output. Thus by a continuous set function, graphs with very similar structures and attributes could be mapped to similar embeddings. The following theorem provides a way to construct continuous injective set functions in uncountable space by sum aggregation after a certain transformation. \begin{theorem} \label{th:injective} Assume $\mathcal{X}$ is a set of finite subsets of $\mathbb{R}^d$, i.e., for $M\in \mathbb{N}$ and $\mathcal{X}=\{X|X\subset \mathbb{R}^d, |X|\leq M \}$, there exists an infinite number of continuous functions $\Phi : \mathbb{R}^d\rightarrow \mathbb{R}^{D}$ such that the set function $f:\mathcal{X}\rightarrow \mathbb{R}^{D}$, $f(X)=\sum_{\mathbf{x}\in X} \Phi(\mathbf{x})$ is continuous and injective. \end{theorem} We prove Theorem \ref{th:injective} in the supplementary material, the proof contains three steps: 1. Constructing a satisfying function in one dimensional cases ($d=1$); 2. Constructing a satisfying function in multi-dimensional cases($d>1$) based on the results in step 1; 3. The satisfying function can be used to generate infinite many other satisfying functions. In our proof, we find a $\Phi(\mathbf{x})$ defined in Eq. \ref{eq:phidd} ($\mathbf{x}[i]$ is the $i$th component of vector $\mathbf{x}$) that can make $f(X)=\sum_{\mathbf{x}\in X} \Phi(\mathbf{x})$ continuous and injective if the first entries of all vectors in $X$ are distinct. \begin{equation}\label{eq:phidd} \Phi_{M}(\mathbf{x})= \\ \left[ \begin{matrix} 1, & \mathbf{x}[1], & \mathbf{x}[1]^2, & \cdots, & \mathbf{x}[1]^{(M-1)}, & \mathbf{x}[1]^{M}, \\ \mathbf{x}[2], & \mathbf{x}[1]\mathbf{x}[2], & \mathbf{x}[1]^2\mathbf{x}[2], & \cdots, & \mathbf{x}[1]^{M-1}\mathbf{x}[2], \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ \mathbf{x}[d], & \mathbf{x}[1]\mathbf{x}[d], & \mathbf{x}[1]^2\mathbf{x}[d], & \cdots, & \mathbf{x}[1]^{M-1}\mathbf{x}[d] \end{matrix} \right] \end{equation} In the proof, we also provide a way to construct such a function $\Phi(\mathbf{x})$ by defining a continuous injective function $g:\mathbb{R}^d\rightarrow \mathbb{R}^d$, then $\Phi(g(\mathbf{x}))$ can also satisfy the condition if we have a function $\Phi(\mathbf{x})$ satisfying the condition. We call $\Phi(\mathbf{x})$ the \textbf{transformation function}. \begin{lemma} \label{lm:limitation} Let $M\in \mathbb{N}$ and $\mathcal{X}=\{X | X \subset \mathbb{R}^d, |X|=M \}$, then for any continuous function $\Phi : \mathbb{R^d}\rightarrow \mathbb{R}^{N}$, if $N < dM$, the set function $f:\mathcal{X}\rightarrow \mathbb{R}^{N}$ $f(X)=\sum_{\mathbf{x}\in X} \Phi(\mathbf{x})$ is not injective. \end{lemma} We prove Lemma \ref{lm:limitation} in the appendix. Lemma \ref{lm:limitation} tells that if we want to construct a continuous injective set function for sets with $M$ $d$-dimensional vectors by sum aggregation with continuous transformation $\Phi(\mathbf{x})$, $\Phi(\mathbf{x})$ must have at least $dM$ dimensions. We are restricting $\Phi$ as a continuous function so that it can be modeled by a neural network, because a neural network can approximate any continuous functions rather than any functions by the universal approximation theorem \cite{cybenko1989approximation}. \subsection{Expressive graph representation} Since Theorem \ref{th:injective} tells that a set can be uniquely represented by a sum aggregation of its elements through a transformation function, we can use the unique set representation to model neighborhood of each node in a graph, and thus improve the expressiveness of graph representation. From Theorem \ref{th:gnnpower}, to design an expressive GNN, we need to design injective functions for $f_{A}(\cdot)$, $f_{C}(\cdot)$ and $f_{R}(\cdot)$. Since $f_{C}(\cdot)$ is easy to get continuous and injective, and $f_{A}(\cdot)$ and $f_{R}(\cdot)$ both operate on a set of vectors in $R^d$, thus, we need Theorem \ref{th:injective} to guide us to construct a continuous and injective set function for $f_{A}(\cdot)$ and $f_{R}(\cdot)$ by sum aggregation after a certain continuous transformation. \textbf{COMBINE function.} According to Lemma \ref{lm:limitation}, for a set of $M$ $d$-dimensional embeddings, the transformation function must be at lease $dM$-dimensional to construct a continuous injective set function with sum aggregation, thus, without dimension reduction in $f_{C}(\cdot)$, we get a $(dM+d)$-dimensional embedding after one layer. Nevertheless, in a specific learning task, not all dimensions are related to the learning task, we could design learnable neural networks to adaptively reduce the output dimension for each layer. We could use learnable MLPs with a lower output dimension to model $f_{C}(\cdot)$ as Eq. \ref{eq:MLPcombine}, where $[\mathbf{x_1},\mathbf{x_2}]$ is to concatenate vectors $\mathbf{x_1}$ and $\mathbf{x_2}$. \begin{equation}\label{eq:MLPcombine} f^{(k)}_{C}(\mathbf{x_1},\mathbf{x_2}) = MLP^{(k)}\left(\left[\mathbf{x_1},\mathbf{x_2}\right]\right) \end{equation} Note that MLP maping high-dimensional vectors to low-dimensional vectors must not be continuous and injective if all dimensions in the high-dimensional vectors are independent. Here, MLP is used for task-driven feature reduction. \textbf{AGGREGATE function.} $f_{A}(\cdot)$ operates on a set of node embeddings in the neighborhood of a node. We have two choice of the transformation function of $f_{A}(\cdot)$, i.e., \textit{fixed transformation} and \textit{learnable transformation}. \textit{Fixed transformation.} In the proof of Theorem \ref{th:injective}, we find the function $\Phi_{M}(\mathbf{x})$ defined in Eq. \ref{eq:phidd} can be used as a continuous transformation function to make the sum aggregation continuous and injective in most cases. For $f_{A}(\cdot)$, let $M_n$ be the max neighborhood size for all nodes in all the graphs. Usually, $M_n$ is not very large, we can set the transformation function as $\Phi_{M_n}(\mathbf{x})$ for each layer $k$ to maintain the expressive capability. Then $f_{A}(\cdot)$ for layer $k$ can be represented as \begin{equation}\label{eq:poweragg} f_{A}^{(k)} \left( \left\{H^{(k)}(w) | w\in N(v) \right\} \right) = \sum_{w\in \mathcal{N}(v)}{\Phi_{M_n} \left(H^{(k)}(w) \right)} \end{equation} We are aware of that $f_{A}^{(k)}(\cdot)$ in Eq. \ref{eq:poweragg} are not totally injective if the first entry of elements of $\mathcal{N}(v)$ are not all distinct. We think $f_{A}^{(k)}(\cdot)$ can capture much more information than many other known aggregation methods. Combining Eqs. \ref{eq:combine}, \ref{eq:MLPcombine} and \ref{eq:poweragg}, we get the propagation rule as \begin{equation}\label{eq:powerGNN} H^{(k+1)}(v) = MLP^{(k)} \left( \left[H^{(k)}(v), \sum_{w\in \mathcal{N}(v)}{\Phi_{M_n} \left(H^{(k)}(w)\right)}\right] \right) \end{equation} Though the function $\Phi_{M}(\mathbf{x})$ defined in Eq. \ref{eq:phidd} can make the sum aggregation continuous and injective, it may result in numerical stability since the item $\mathbf{x}[1]^M$ will make the number become very large or very close to 0 if $M$ is very large. To address this issue, we use a continuous and injective function $g(\mathbf{x})$ to normalize the power, since in the proof of Theorem \ref{th:injective} we know $\Phi_{M}(g(\mathbf{x}))$ is also a qualified transformation function to make the sum aggregation continuous and injective, if $g(\mathbf{x})$ is continuous and injective. In this paper, we set \begin{equation}\label{eq:gx} \begin{aligned} & g(\mathbf{x})[1]= \begin{cases} \mathbf{x}[1]^{1/M}, & \mathbf{x}[1]\ge 0 \\ -(-\mathbf{x}[1])^{1/M}, & \mathbf{x}[1]<0 \\ \end{cases} \\ & g(\mathbf{x})[2:d]= \mathbf{x}[2:d] \end{aligned} \end{equation} \textit{Learnable transformation.} Due to the continuity of the transformation function, we can also set a learnable MLP to approach the transformation function for $f_{A}(\cdot)$ by the universal approximation theorem \cite{cybenko1989approximation}, then we get the propagation rule as \begin{equation}\label{eq:MLPagg} H^{(k+1)}(v)= MLP_{c}^{(k)} \left( \left[H^{(k)}(v), \sum_{w\in \mathcal{N}(v)}{MLP_{t}^{(k)}\left(H^{(k)}(w)\right)}\right] \right) \end{equation} where $MLP_{t}^{(k)}$ and $MLP_{c}^{(k)}$ serve as the transformation function and the combine function for the $k$th layer, respectively. By this way, we get the all the node embeddings for all graphs. For node classification task, the final layer output node embedding can be input to an learnable MLP classifier to get the probability for each class. For graph or subgraph classification, we need another aggregation function $f_{R}(\cdot)$ to aggregate all the node embeddings in a graph. \textbf{READOUT function.} $f_{R}(\cdot)$ operates on a set of all node embeddings in a graph. Let $M_G$ be the max node number of all the graphs, for $d$-dimensional node embeddings, the continuous transformation function must be at least $dM$ dimensions for injective continuous $f_{R}(\cdot)$, thus generate a $(dm)$-dimensional graph-level embedding. For large graphs with many nodes, the output dimension will be very high. To avoid high-dimensional embeddings, we also use a learnable MLP as the transformation function to reduce the output dimension. \begin{equation}\label{eq:readoutdecom} H_G = f_{R} \left( \left\{H^{(K)}(v) | v\in G \right\} \right) = \sum_{v\in G}{MLP_G \left(H^{(K)}(v)\right)} \end{equation} For graph classification, the output graph-level embedding are input to an MLP classifier with $n_C$ outputs corresponding to the probabilities of the $n_C$ classes. Also, MLP can represent the composition of functions, in our implementation, we merge the classifier MLP and MLP$_G$ into only one MLP as GIN did in \cite{xu2019powerful}. We only use the final GNN layer outputs for classification rather than concatenating all layers' outputs to construct a longer vector representation for classification as GIN did, because we think the final layer outputs contain all information from middle layers and are expressive enough for graph classification. In addition, this can reduce the input dimension of the final classifier, resulting in a simpler classifier than GIN, especially in case of many layers. \section{Related Work} \textbf{General graph neural networks.} Many GNN variants with different aggregation rules are proposed in the literature to achieve good performances in different tasks. In \cite{xu2019powerful}, GIN has been proposed with the propagation rule as \begin{equation}\label{eq:gin} H^{(k+1)}(v) = MLP^{(k)}\left(\left(1+\epsilon^{(k)} \right)\cdot H^{(k)}(v) + \sum_{u\in N(u)}{H^{(k)}(u)} \right) \end{equation} GIN is expected to be highly expressive for simple graphs where node attributes can be one-hot encoders on which sum aggregation is injective. However, GIN cannot be directly extended to attributed graphs with the same expressive capability, because the sum aggregation is no longer injective in uncountable cases. GCN is another GNN variant with simple element-wise mean pooling in a node's neighborhood including the node itself \cite{kipf2017semi}. Hamilton et al. \cite{hamilton2017inductive} tested 3 aggregators in GraphSAGE, including mean aggregator, LSTM aggregator and max pooling aggregator, they found no significant performance difference exists between the LSTM aggregators and pool aggregators, but GraphSAGE-LSTM is significantly slower than GraphSAGE-pool. Mean aggregation and max pooling are permutation invariant on sets, but the operation is not injective, which may result in the same embedding for different inputs. LSTM aggregation could have large expressive capacity, but it is not permutation invariant, this may render equivalent nodes or isomorphic graphs to have different embeddings. \textbf{Graph kernels for graph classification.} Graph kernels is an established and widely-used technique for solving classification tasks on graphs \cite{shervashidze2011weisfeiler,shervashidze2009efficient,yanardag2015deep}. One of the dominating paradigms in the design of graph kernels is representation and comparison of local structure by neighborhood aggregation. The well know WL subtree kernel inspired the GNN for neighborhood aggregation. Though most of the graph kernels are for simple graph classification, more and more research began to study graph kernels for attributed graphs \cite{morris2016faster,feragen2013scalable,orsini2015graph,neumann2016propagation}. Graph kernel-based method can measure the similarity between two graphs, but usually cannot generate a distributed representation for a graph. \section{Experiments} For ExpGNN, we evaluate the expressive capability on the training data and evaluate the generalization ability on the test data. The evaluations are based on two graph classification tasks, simple graph classification and attributed graph classification. \begin{table*}[t] \scriptsize \centering \caption{Accuracy for simple graph classification in test set (\%). Top 3 performances on each dataset are bolded.} \begin{tabular}{l|c|c|c|c|c|c|c|c} \toprule & MUTAG & PTC & NCI1 & PROTEINS & COLLAB & IMDB-B & IMDB-M & RDT-B \\ \midrule ExpGNN-fixed & \textbf{90.5 $\pm$ 6.1} & 65.6 $\pm$ 7.8 & \textbf{82.9 $\pm$ 2.5} & \textbf{77.2 $\pm$5.6} & -- & -- & -- & -- \\ ExpGNN-MLP & \textbf{91.1 $\pm$ 7.9} & \textbf{66.5 $\pm$ 7.6} & \textbf{82.9 $\pm$ 1.3} & 76.1 $\pm$ 5.2 & -- & -- & -- & -- \\ ExpGNN-FI-fixed & 90.0 $\pm$ 6.9 & \textbf{68.5 $\pm$ 8.5} & 82.3 $\pm$ 2.6 & \textbf{77.0 $\pm$ 6.0} & -- & 73.5 $\pm$ 4.3 & 48.9 $\pm$ 3.3 & -- \\ ExpGNN-FI-MLP & 90.0 $\pm$ 6.9 & 64.1$\pm$ 4.1 & \textbf{83.3 $\pm$ 1.7} & 76.3$\pm$ 5.1 & 78.4$\pm$ 1.0 & 73.3 $\pm$ 3.7 & 49.9 $\pm$ 2.8 & \textbf{91.2 $\pm$4.2} \\ \midrule GIN-final & 89.4 $\pm$ 5.8 & 63.5 $\pm$ 8.6 & 82.7 $\pm$ 2.0 & 76.2 $\pm$ 4.9 & 75.8 $\pm$ 1.8 & 72.9 $\pm$ 5.3 & 48.9 $\pm$ 4.9 & \textbf{91.6 $\pm$ 3.0} \\ GIN \cite{xu2019powerful} & 89.4 $\pm$ 5.6 & 64.6 $\pm$ 7.0 & 82.7 $\pm$ 1.6 & 76.2 $\pm$ 2.8 & \textbf{80.2 $\pm$ 1.9} & \textbf{75.1 $\pm$ 5.1} & \textbf{52.3 $\pm$ 2.8} & \textbf{92.4 $\pm$ 2.5} \\ GCN \cite{kipf2017semi} & 85.6 $\pm$ 5.8 & 64.2 $\pm$ 4.3 & 80.2 $\pm$ 2.0 & 76.0 $\pm$ 3.2 & 79.0 $\pm$ 1.8 & 74.0 $\pm$ 3.4 & \textbf{51.9 $\pm$ 3.8} & 50.0 $\pm$ 0.0 \\ GraphSAGE \cite{hamilton2017inductive} & 85.1 $\pm$ 7.6 & 63.9 $\pm$ 7.7 & 77.7 $\pm$ 1.5 & 75.9 $\pm$ 3.2 & -- & 72.3 $\pm$ 5.3 & 50.9 $\pm$ 2.2 & -- \\ PSCN \cite{niepert2016learning} & \textbf{92.6 $\pm$ 4.2} & 60.0$\pm$ 4.8 & 78.6 $\pm$ 1.9 & 75.9 $\pm$ 2.8 & 72.6 $\pm$ 2.2 & 71.0 $\pm$ 2.2 & 45.2$\pm$ 2.8 & 86.3 $\pm$ 1.6 \\ DCNN \cite{atwood2016diffusion} & 67.0 & 56.6 & 62.6 & 61.3 & 52.1 & 49.1 & 33.5 & -- \\ DGCNN \cite{zhang2018end} & 85.8 $\pm$ 1.7 & 58.6 $\pm$ 2.5 & 74.4 $\pm$ 0.5 & 75.5 $\pm$ 0.9 & 73.8 $\pm$ 0.5 & 70.0 $\pm$ 0.9 & 47.8 $\pm$ 0.9 & -- \\ CapsGNN \cite{xinyi2019capsule} & 86.7 $\pm$ 6.9 & - & 78.4 $\pm$ 1.6 & 76.3 $\pm$ 3.6 & \textbf{79.6 $\pm$ 0.9} & 73.1 $\pm$ 4.8 & 50.3 $\pm$ 2.7 & -- \\ GCAPS-CNN \cite{verma2018graph} & -- & \textbf{66.0 $\pm$ 5.9} & 82.7 $\pm$ 2.4 & \textbf{76.4 $\pm$ 4.2} & 77.7 $\pm$ 2.5 & 71.7 $\pm$ 3.4 & 48.5 $\pm$ 4.1 & 87.6 $\pm$ 2.5 \\ IEGN \cite{Maron2019InvariantAE} & 84.6 $\pm$ 10 & 59.5 $\pm$ 7.3 & 73.7 $\pm$ 2.6 & 75.2 $\pm$ 4.3 & 77.9 $\pm$ 1.7 & 71.3 $\pm$ 4.5 & 48.6 $\pm$ 3.9 & -- \\ HO-GNN \cite{morris2019weisfeiler} & 86.1 & 60.9 & 76.2 & 75.9 & -- & \textbf{74.2} & 49.5 & --\\ FGSD \cite{verma2017hunt} & 92.1 & 62.8 & {79.8} & {73.4} & \textbf{80.0} & {73.6} & {52.4} & 86.5 \\ AWE \cite{ivanov2018anonymous} & 87.9 $\pm$ 9.8 & -- & -- & -- & 73.9 $\pm$ 1.9 & \textbf{74.5 $\pm$ 5.9} & \textbf{51.5} $\pm$ 3.6 & 87.9 $\pm$ 2.5 \\ Graph2vec \cite{narayanan2017graph2vec} & 83.2 $\pm$ 9.3 & 60.2 $\pm$ 6.9 & 73.2 $\pm$ 1.8 & 73.3 $\pm$ 2.1 & -- & -- & -- &-- \\ \midrule WL subtree \cite{shervashidze2011weisfeiler} & 90.4 $\pm$ 5.7 & 59.9 $\pm$ 4.3 & \textbf{86.0 $\pm$ 1.8} & 75.0 $\pm$ 3.1 & 78.9 $\pm$ 1.9 & 73.8 $\pm$ 3.9 & 50.9 $\pm$ 3.8 & 81.0 $\pm$ 3.1 \\ GK \cite{shervashidze2009efficient} & 81.6 $\pm$ 2.1 & 57.3 $\pm$ 1.4 & 62.5 $\pm$ 0.3 & 71.7 $\pm$ 0.6 & 72.8 $\pm$ 0.3 & 65.9 $\pm$ 1.0 & 43.9 $\pm$ 0.4 & 77.3 $\pm$ 0.2 \\ DGK \cite{yanardag2015deep} & 87.4 $\pm$ 2.7 & 60.1 $\pm$ 2.6 & 80.3 $\pm$ 0.5 & 75.7 $\pm$ 0.5 & 73.1 $\pm$ 0.3 & 67.0 $\pm$ 0.6 & 44.6 $\pm$ 0.5 & 78.0 $\pm$ 0.4 \\ \bottomrule \end{tabular}% \label{tab:simplegraph}% \end{table*}% \begin{figure}[t] \centering \subfloat[MUTAG]{\includegraphics[width=.25\linewidth,page=1]{figures/acc_MUTAG.pdf}} \subfloat[PTC]{\includegraphics[width=.25\linewidth,page=1]{figures/acc_PTC.pdf}} \subfloat[PROTEINS-att]{\includegraphics[width=.25\linewidth,page=1]{figures/acc_PROTEINS_att.pdf}} \subfloat[FRANKENSTEIN]{\includegraphics[width=.25\linewidth,page=1]{figures/acc_FRANKENSTEIN.pdf}} \caption{The accuracy curves on training set and test set in the training process.} \label{fig:traincurve} \end{figure} \begin{table*}[t] \scriptsize \centering \caption{Accuracy for attributed graph classification in test set (\%). Top 3 performances on each dataset are bolded.} \begin{tabular}{l|c|c|c|c|c} \toprule & ENZYMES & FRANKENSTEIN & PROTEINS-att & SYNTHETICnew & Synthie \\ \midrule ExpGNN-fixed & 58.0 $\pm$ 5.6 & 71.5 $\pm$ 2.7 & \textbf{77.3 $\pm$ 3.2} & 89.7 $\pm$ 7.1 & 93.7 $\pm$ 3.7 \\ ExpGNN-MLP & \textbf{71.3 $\pm$ 4.3} & \textbf{71.8 $\pm$ 2.7} & 76.1 $\pm$ 3.6 & \textbf{98.0 $\pm$ 2.7} & \textbf{99.8 $\pm$ 0.8} \\ \midrule GIN-final & 69.3 $\pm$ 5.3 & 68.5 $\pm$ 1.5 & 76.4 $\pm$ 3.0 & 79.7 $\pm$ 6.9 & 90.0 $\pm$ 4.4\\ HGK-SP \cite{morris2016faster} & \textbf{71.30 $\pm$ 0.86} & 70.06 $\pm$ 0.32 & \textbf{77.47 $\pm$ 0.43} & \textbf{96.46 $\pm$ 0.61} & 94.34 $\pm$0.54 \\ HGK-WL \cite{morris2016faster} & 67.63 $\pm$ 0.95 & \textbf{73.62 $\pm$ 0.38} & 76.70 $\pm$ 0.41 & \textbf{98.84 $\pm$ 0.29} & \textbf{96.75 $\pm$ 0.51} \\ GHK \cite{feragen2013scalable} & 68.80 $\pm$ 0.96 & 68.48 $\pm$ 0.26 & 72.26 $\pm$ 0.34 & 85.10 $\pm$ 1.04 & 73.18 $\pm$ 0.77 \\ GIK \cite{orsini2015graph} & \textbf{71.70 $\pm$ 0.79} & \textbf{76.31 $\pm$ 0.33} & \textbf{76.88 $\pm$ 0.47} & 83.07 $\pm$ 1.10 & \textbf{95.75 $\pm$ 0.50} \\ P2K \cite{neumann2016propagation} & 69.22 $\pm$ 0.34 & -- & 73.45 $\pm$ 0.48 & 91.70 $\pm$ 0.86 & 50.15 $\pm$ 1.92 \\ \bottomrule \end{tabular}% \label{tab:resatt}% \end{table*}% \begin{figure*}[t] \centering \subfloat[ExpGNN-MLP]{\includegraphics[width=.25\textwidth,page=1]{figures/emb_MLP_TSNE_ep300_SYNTHETICnew.pdf}} \subfloat[ExpGNN-fixed]{\includegraphics[width=.25\textwidth,page=1]{figures/emb_power_TSNE_ep300_SYNTHETICnew.pdf}} \subfloat[GIN-final]{\includegraphics[width=.25\textwidth,page=1]{figures/emb_identical_TSNE_ep300_SYNTHETICnew.pdf}} \caption{t-SNE visualization of the output embeddings on training data of SYNTHETICnew dataset.} \label{fig:tsnevisual} \end{figure*} \subsection{Graph classification} \textbf{Dataset.} We use 8 simple graph benchmarks and 5 attributed graph benchmarks for graph classification, the 8 simple graph datasets contain 4 bioinformatics datasets (MUTAG, PTC, NCI1, PROTEINS) and 4 social network datasets (COLLAB, IMDB-BINARY, IMDB-MULTI, and REDDIT-BINARY) \cite{yanardag2015deep}, these datasets have no continuous node attributes input to the model, for bioinformatics datasets, the categorical node labels are encoded as one-hot input features; for social network datasets, because nodes have no given features, we initialize all node features to 1. The 5 attributed graph datasets contain 3 bioinformatics datasets (ENZYMES, FRANKENSTEIN, PROTEINS-att) and 2 synthetic datasets (SYNTHETICNEW, Synthie) where the continuous attributes are concatenated with one-hot node label for each node to serve as the input to the models. All the datasets are available from \cite{KKMMN2016}. More dataset information can be found in the supplementary material. \textbf{Settings.} We implement 4 ExpGNN variants: (1) ExpGNN-fixed, the transformation function in all layers are set as Eq. \ref{eq:phidd}; (2) ExpGNN-MLP, the transformation function in all layers are set as a learnable MLP. (3) ExpGNN-FI-fixed and (4) ExpGNN-FI-MLP, because for a simple graph with one-hot node features, the summation without transformation or with identical transformation is injective, thus we set First layer Identical transformation function in ExpGNN-FI-fixed and ExpGNN-FI-MLP and only for simple graph classification. We also implement GIN with the output of the final layer as node embeddings to sum to graph embedding, GIN-final. For social network datasets, because the input nodes' features are all the same, any transformation function will generate the same node vector for all nodes, no transformation function is needed in the first layer, only FI is implemented. For COLLAB and REDDITBINARY, the max neighborhood size is too large, we do not implement fixed transformation function. All the 4 ExpGNN variants and GIN-final have 5 GNN layers, all MLPs in ExpGNN have 2 layers. Batch normalization \cite{ioffe2015batch} is applied in every hidden layer (including GNN layer and MLP layer) followed by a ReLU activation function. We use the Adam optimizer \cite{kingma2014adam} with initial learning rate tuned in $\{0.01, 0.001\}$ and decay the learning rate by 0.5 every 50 epochs. The batch size is 32, no dropout layer applied. The number of hidden units is tuned in $\{16,32,64\}$. Following the settings in \cite{xu2019powerful,yanardag2015deep,niepert2016learning}, we perform 10-fold cross-validation on each dataset, and report the average and standard deviation of validation accuracies across the 10 folds within the cross-validation to evaluate the generalization ability. All models are trained 300 epochs, a single epoch with the best cross-validation accuracy averaged over the 10 folds is selected. To evaluation the expressive capability, we also record the average training accuracy across the 10 folds of ExpGNNs and GIN-final in each epoch. \textbf{Baselines.} For expressive capability, we compare ExpGNN with GIN-final on the training set. For generalization ability in simple graph classification, besides GIN, we also compare ExpGNN with a number of state-of-the-art models, including deep learning-based methods and graph kernels. The deep learning-based methods include GCN \cite{kipf2017semi}, GraphSAGE \cite{hamilton2017inductive}, PATCHY-SAN (PSCN) \cite{niepert2016learning}, Diffusion convolutional neural networks (DCNN) \cite{atwood2016diffusion}, Deep Graph CNN (DGCNN) \cite{zhang2018end}, Capsule Graph Neural Network (CapsGNN) \cite{xinyi2019capsule}, Graph capsule CNN (GCAPS-CNN) \cite{verma2018graph}, Invariant and equivariant graph networks (IEGN) \cite{Maron2019InvariantAE}, Higher-order Graph Neural Networks (HO-GNN) \cite{morris2019weisfeiler}, family of graph spectral distances (FGSD) \cite{verma2017hunt}, Anonymous Walk Embeddings (AWE) \cite{ivanov2018anonymous} and Graph2vec \cite{narayanan2017graph2vec}. The graph kernel methods include WL subtree kernel \cite{shervashidze2011weisfeiler}, graphlet count kernel (GK) \cite{shervashidze2009efficient} and Deep Graph Kernel (DGK) \cite{yanardag2015deep}. Although deep learning methods can naturally handle attributed graphs, few results of attributed graph classification with deep learning methods are available in the literature. For generalization ability in attributed graph classification, we are only aware of graph kernel related baselines, including hash graph kernels with shortest path (HSK-SP) \cite{morris2016faster}, hash graph kernels with WL subtree (HSK-WL) \cite{morris2016faster}, GraphHopper kernel (GHK) \cite{feragen2013scalable}, graph invariant kernel (GIK) \cite{orsini2015graph} and propagation kernel for continuous attributes (P2K) \cite{neumann2016propagation}. We also compared ExpGNN with our implemented GIN-final for attributed graph classification. \textbf{Results.} Figure \ref{fig:traincurve} illustrates accuracies in training and test sets in the training process on 4 datasets for ExpGNN and GIN-final with their respective best settings. More results on other datasets can be found in the supplementary material. We can see that ExpGNN-MLP for different datasets are able to fit the training sets perfectly and are better than GIN-final and ExpGNN-fixed. For MUTAG and PTC datasets, GIN in \cite{xu2019powerful} can fit the training set, while GIN-final cannot, since GIN concatenates all the middle layer outputs as the graph embedding, it may be the reason that the final layer outputs of GIN may lose some information from middle layers. From the test accuracy curves in Figure \ref{fig:traincurve}, we can also find that ExpGNN can generalize better than GIN-final on these datasets, except ExpGNN-MLP on dataset PROTEINS-att. As for the generalization ability, Table \ref{tab:simplegraph} lists the classification accuracies for simple graph classification, Table \ref{tab:resatt} lists the results for attributed graph classification, comparing with other state-of-the-art methods. We highlight the top 3 accuracies for each dataset in boldface. From Table \ref{tab:simplegraph}, for simple graph classification on all bioinformatics datasets, at least 2 ExpGNN variants can achieve top 3 in these 21 models. From Table \ref{tab:resatt}, for all the attributed graph datasets, ExpGNN can achieve top 3 in these 8 models, especially, ExpGNN-MLP places first on Synthie dataset. Comparing ExpGNN and GIN-final, ExpGNN can consistently outperform GIN-final except for ExpGNN-fixed on ENZYMES dataset and ExpGNN-MLP on PROTEINS-att. \subsection{Expressive capability analysis} The expressive capability describes how a model can distinguish different samples. Generally, a high expressive model will map different samples to different embeddings and similar samples to similar embeddings. For classification problem, an expressive model should make samples in the same class compact together and samples in different classes highly discriminative. Here, we fetch the output embeddings of GNN before feeding to the classifier, and visualize them to see if GNN can discriminate samples from different classes. Figure \ref{fig:tsnevisual} shows the t-SNE visualization \cite{maaten2008visualizing} of output embeddings of different GNN models on training data of SYNTHETICnew dataset. The final layer GNN output embedding is also visualized with PCA and two random dims in the supplementary material. We can see that the output embeddings of ExpGNN-MLP are highly discriminative, which demonstrates the expressive capability of ExpGNN-MLP. \section{Conclusion} In this paper, we present a theoretical framework to design highly expressive GNNs for general graphs. Based on the framework, we propose two expressive GNN variants with fixed transformation function and learnable transformation function, respectively. Moreover, the proposed expressive GNN can naturally learn expressive representations for graphs with continuous node attributes. We validate the proposed GNN for graph classification on multiple benchmark datasets including simple graph and attributed graph. The experimental results demonstrate that our model achieves state-of-the-art performances on most of the benchmarks. \bibliographystyle{plain} \section{Proofs} \begin{theorem} \label{th:injective} Assume $\mathcal{X}$ is a set of finite subsets of $\mathbb{R}^d$, i.e., for $M\in \mathbb{N}$ and $\mathcal{X}=\{X|X\subset \mathbb{R}^d, |X|\leq M \}$, there exists an infinite number of continuous functions $\Phi : \mathbb{R}^d\rightarrow \mathbb{R}^{D}$ such that the set function $f:\mathcal{X}\rightarrow \mathbb{R}^{D}$, $f(X)=\sum_{\mathbf{x}\in X} \Phi(\mathbf{x})$ is continuous and injective. \end{theorem} \begin{proof} We prove the theorem by three steps, 1. constructing a satisfying function $\Phi(x)$ in one dimensional cases ($d=1$); 2. constructing a satisfying function $\Phi(\mathbf{x})$ in multi-dimensional cases ($d>1$); 3. The number of the satisfying functions is infinite. \noindent\textbf{1. One dimensional cases ($d=1$):} In one dimensional case, the theorem can be easily proved by extending the following lemma from \cite{zaheer2017deep}. \begin{lemma*} Let $\mathcal{X}=\{(x_1,\cdots,x_M)\in [0,1]^M: x_1\leq x_2 \leq \cdots \leq x_M\}$. The sum-of-power mapping $E: \mathcal{X}\rightarrow \mathbb{R}^{M+1}$ defined by the coordinate functions \begin{equation} E(X)=\left [E_0(X),E_1(X),\cdots,E_M(X) \right]=\left[\sum_{x\in X}{1},\sum_{x\in X}{x},\cdots, \sum_{x\in X}{x^M} \right] \end{equation} is injective. \end{lemma*} In \cite{zaheer2017deep}, this lemma is proved based on the famous Newton-Girard formulae, where the domain $\mathcal{X}$ can be extended to $\mathcal{X}=\{X|X\subset \mathbb{R}, |X|\leq M, M\in \mathbb{N}\}$ with the same proof process. Because $E_0(X)=\sum_{x\in X} {1}=|X|$ is the number of elements in $X$, $E_0(X_1)=E_0(X_2)$ implies equal set size between the two sets, it can be easily extended to $\mathcal{X}=\{X|X\subset \mathbb{R}, |X|\leq M, M\in \mathbb{N}\}$. Since $E(X)=\left[\sum_{x\in X}{1},\sum_{x\in X}{x},\cdots, \sum_{x\in X}{x^M} \right] = \sum_{x\in X}{[1,x,\cdots,x^M]}$. Let $\Phi(x)=[1,x,\cdots,x^M]$, obviously $\Phi(x)$ is continuous, thus, we get one $\Phi(X)$ such that $f(X)=\sum_{x\in X} \Phi(x)$ is injective and continuous. \noindent\textbf{2. Multi-dimensional cases ($d>1$):} Consider the following function $\Phi:\mathbb{R}^d\rightarrow \mathbb{R}^{(dm+1)}$, \begin{equation}\label{eq:phi} \Phi(\mathbf{x})=\left[ \begin{aligned} 1, & \mathbf{x}[1], & \mathbf{x}[1]^2, & \cdots, & \mathbf{x}[1]^{(M-1)}, & \mathbf{x}[1]^{M}, \\ \mathbf{x}[2], & \mathbf{x}[1]\mathbf{x}[2], & \mathbf{x}[1]^2\mathbf{x}[2], & \cdots, & \mathbf{x}[1]^{M-1}\mathbf{x}[2], \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ \mathbf{x}[d], & \mathbf{x}[1]\mathbf{x}[d], & \mathbf{x}[1]^2\mathbf{x}[d], & \cdots, & \mathbf{x}[1]^{M-1}\mathbf{x}[d] \end{aligned} \right] \end{equation} where $\mathbf{x}[i]$ is the $i$th entry of vector $\mathbf{x}$. For a ($dm+1$)-dimensional vector $V$ from the image domain of $\mathcal{X}$ through $f(X)=\sum_{\mathbf{x}\in X} \Phi(\mathbf{x})$, we will identify the number of the preimages of $V$. Let $X$ is a preimage of $V$, we have the following equation which is exactly a equation group with $dM+1$ equations. \begin{equation}\label{eq:sumphi} V= \left[ \begin{matrix} \sum_{\mathbf{x} \in X}1, & \sum_{\mathbf{x} \in X}\mathbf{x}[1], & \sum_{\mathbf{x} \in X}\mathbf{x}[1]^2, & \cdots, & \sum_{\mathbf{x} \in X}\mathbf{x}[1]^{(M-1)}, & \sum_{\mathbf{x} \in X}\mathbf{x}[1]^{M}, \\ \sum_{\mathbf{x} \in X}\mathbf{x}[2], & \sum_{\mathbf{x} \in X}\mathbf{x}[1]\mathbf{x}[2], & \sum_{\mathbf{x} \in X}\mathbf{x}[1]^2\mathbf{x}[2], & \cdots, & \sum_{\mathbf{x} \in X}\mathbf{x}[1]^{M-1}\mathbf{x}[2], \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ \sum_{\mathbf{x} \in X}\mathbf{x}[d], & \sum_{\mathbf{x} \in X}\mathbf{x}[1]\mathbf{x}[d], & \sum_{\mathbf{x} \in X}\mathbf{x}[1]^2\mathbf{x}[d], & \cdots, & \sum_{\mathbf{x} \in X}\mathbf{x}[1]^{M-1}\mathbf{x}[d] \end{matrix} \right] \end{equation} Note that the first row of Eq. \ref{eq:sumphi} is exactly the sum-of-power mapping we considered in one dimensional cases, thus we can identify a unique set of the first entry of elements in $X$, and the number of elements in $X$ is also determined. Let $X$ have $M$ elements and $X=\{\mathbf{x_1},\mathbf{x_2},\cdots,\mathbf{x_M}\}$, the set $\{\mathbf{x_1}[1],\mathbf{x_2}[1],\cdots,\mathbf{x_M}[1]\}$ is uniquely defined. Consider the second row of Eq. \ref{eq:sumphi}, we can rewrite the equations in the second row as linear matrix equation as Eq. \ref{eq:eqvdmd} \begin{equation}\label{eq:eqvdmd} \left[ \begin{matrix} 1 & 1 & \cdots & 1 \\ \mathbf{x_1}[1] & \mathbf{x_2}[1] & \cdots & \mathbf{x_M}[1] \\ \mathbf{x_1}[1]^2 & \mathbf{x_2}[1]^2 & \cdots & \mathbf{x_M}[1]^2 \\ \vdots & \vdots & \ddots & \vdots \\ \mathbf{x_1}[1]^{(M-1)} & \mathbf{x_2}[1]^{(M-1)} & \cdots & \mathbf{x_M}[1]^{(M-1)} \\ \end{matrix} \right] \times \left[ \begin{matrix} \mathbf{x_1}[2] \\ \mathbf{x_2}[2] \\ \vdots \\ \mathbf{x_M}[2] \\ \end{matrix} \right] = V[2,:]^T \end{equation} Note that the coefficient matrix in left side of Eq. \ref{eq:eqvdmd} is a Vandermonde matrix, if the $\mathbf{x_1}[1],\cdots, \mathbf{x_M}[1]$ are all distinct, the coefficient matrix is invertible \cite{macon1958inverses}, Eq. \ref{eq:eqvdmd} has a unique solution for $\mathbf{x_1}[2],\cdots, \mathbf{x_M}[2]$ corresponding to $\mathbf{x_1}[1],\cdots, \mathbf{x_M}[1]$. Similarly, by the $i$th ($2<i<d$) row of Eq. \ref{eq:sumphi}, $\mathbf{x_1}[i],\cdots, \mathbf{x_M}[i]$ can be uniquely identified. In the other case, if the $\mathbf{x_1}[1],\cdots, \mathbf{x_M}[1]$ that solved from the first row of Eq. \ref{eq:sumphi} are not all distinct, Eq. \ref{eq:eqvdmd} has infinitely many solutions. $\Phi(\mathbf{x})$ defined by Eq. \ref{eq:phi} is not sufficient to make $f(X)=\sum_{\mathbf{x}\in X} \Phi(\mathbf{x})$ injective. We need some more dimensions appended in $\Phi(\mathbf{x})$. Let $\mathbf{x_1}[1]= \mathbf{x_2}[1] = \cdots =\mathbf{x_k}[1]$, then by combining the items, Eq. \ref{eq:eqvdmd} is shrinked to \begin{equation}\label{eq:shrinkvdmd} \left[ \begin{matrix} 1 & 1 & \cdots & 1 \\ \mathbf{x_k}[1] & \mathbf{x_{k+1}}[1] & \cdots & \mathbf{x_M}[1] \\ \mathbf{x_k}[1]^2 & \mathbf{x_{k+1}}[1]^2 & \cdots & \mathbf{x_M}[1]^2 \\ \vdots & \vdots & \ddots & \vdots \\ \mathbf{x_k}[1]^{(M-1)} & \mathbf{x_{k+1}}[1]^{(M-1)} & \cdots & \mathbf{x_M}[1]^{(M-1)} \\ \end{matrix} \right] \times \left[ \begin{matrix} \sum_{i=1\cdots k}\mathbf{x_i}[2] \\ \mathbf{x_{k+1}}[2] \\ \vdots \\ \mathbf{x_M}[2] \\ \end{matrix} \right] = V[2,:]^T \end{equation} By solving Eq. \ref{eq:shrinkvdmd}, we have a unique sum $\sum_{i=1\cdots k}\mathbf{x_i}[2]$. To identify a unique set of $\{\mathbf{x_1}[2], \mathbf{x_2}[2], \cdots, \mathbf{x_k}[2]\}$, we can define a unique $\sum_{i=1\cdots k}\mathbf{x_i}[2]^2, \sum_{i=1\cdots k}\mathbf{x_i}[2]^3, \cdots, \sum_{i=1\cdots k}\mathbf{x_i}[2]^k$, we can add items $\mathbf{x}[2]^2, \mathbf{x}[1]\mathbf{x}[2]^2, \mathbf{x}[1]^2\mathbf{x}[2]^2, \cdots, \mathbf{x}[1]^{M-1}\mathbf{x}[2]^2$ to $\Phi(\mathbf{x})$ to uniquely identify $\sum_{i=1\cdots k}\mathbf{x_i}[2]^2$. Similarly, add items $\mathbf{x}[2]^k, \mathbf{x}[1]\mathbf{x}[2]^k, \mathbf{x}[1]^2\mathbf{x}[2]^k, \cdots, \mathbf{x}[1]^{M-1}\mathbf{x}[2]^k$ to $\Phi(\mathbf{x})$ to uniquely identify $\sum_{i=1\cdots k}\mathbf{x_i}[2]^k$. Thus all $\mathbf{x_i}[2]$ are identified. After the set $\{\mathbf{x_1}[2],\mathbf{x_2}[2],\cdots,\mathbf{x_M}[2]\}$ is uniquely defined, by adding $\mathbf{x}[2]^i\mathbf{x}[j] (i=0,\cdots M-1, j=3,\cdots d)$ to $\Phi(\mathbf{x})$, we can use $\mathbf{x_i}[2]$ to construct a Vandermonde matrix to solve $\mathbf{x_i}[3], \cdots, \mathbf{x_i}[d], (i=1,\cdots,M)$. If $\mathbf{x_i}[1:2]$ are not all distinct, we can identify $\mathbf{x_i}[3]$ similarly by adding $\mathbf{x}[1]^i\mathbf{x}[3]^j$ to $\Phi(\mathbf{x})$. By this way, the set $X$ can be uniquely identified. In our construction of $\Phi(\mathbf{x})$, all the functions are continuous, thus, there exists a continuous function $\Phi(\mathbf{x})$ such that $f(X)=\sum_{\mathbf{x}\in X} \Phi(\mathbf{x})$ is injective and continuous. \noindent\textbf{3. The number of the satisfying function is infinity:} To prove the number of this kind functions is infinity, we construct a continuous injective function $g:\mathbb{R^d}\rightarrow \mathbb{R^d}$, we will show that if we have a $\phi(\mathbf{x})$ satisfying the condition $f(X)=\sum_{\mathbf{x}\in X}{\phi(\mathbf{x})}$ is continuous and injective, then $\phi(g(\mathbf{x}))$ also satisfy the condition $f(X)=\sum_{\mathbf{x}\in X}{\phi(g(\mathbf{x}))}$ is continuous and injective. We define a function $h:\mathcal{X}\rightarrow \mathcal{X}$, $h(X)=\{g(\mathbf{x})| \mathbf{x}\in X\}$, since $g(\mathbf{x})$ is injective, $h(X)$ is also injective. If we have a function $\phi(\mathbf{x})$ such that $f(X)=\sum_{\mathbf{x}\in X} \phi(\mathbf{x})$ is injective, $f(h(X))$ is injective. \begin{equation} f(h(X))= \sum_{\mathbf{x}\in h(X)}{\phi(\mathbf{x})}=\sum_{\mathbf{x}\in\{g(\mathbf{x})|\mathbf{x}\in X\}} {\phi(\mathbf{x})} =\sum_{\mathbf{x}\in X} {\phi(g(\mathbf{x}))} \end{equation} Because $\phi(\mathbf{x})$ and $g(\mathbf{x})$ are both continuous, $\phi(g(\mathbf{x}))$ is continuous, thus we find another function $\phi(g(\mathbf{x}))$ such that $\sum_{\mathbf{x}\in X} {\phi(g(\mathbf{x}))}$ is injective. Because we can have an infinite number of such continuous injective functions $g:\mathbb{R}^d\rightarrow \mathbb{R}^d$ (e.g., $g(\mathbf{x})=k\mathbf{x}, k\in \mathbb{R}$), we have a infinite number of such functions $\Phi(\mathbf{x})=\phi(g(\mathbf{x}))$ such that $f(X)=\sum_{\mathbf{x}\in X} \Phi(\mathbf{x})$ is injective. \end{proof} \begin{lemma} \label{lm:limitation} Let $M\in \mathbb{N}$ and $\mathcal{X}=\{X | X \subset \mathbb{R}^d, |X|=M \}$, then for any continuous function $\Phi : \mathbb{R^d}\rightarrow \mathbb{R}^{N}$, if $N < dM$, the set function $f:\mathcal{X}\rightarrow \mathbb{R}^{N}$ $f(X)=\sum_{\mathbf{x}\in X} \Phi(\mathbf{x})$ is not injective. \end{lemma} \begin{proof} Suppose $f(X)$ is injective. Because $\Phi(\mathbf{x})$ is continuous, $f(X)$ is a finite sum of continuous function, it is also continuous, thus, $f(X)$ is continuous and injective. All sets in $\mathcal{X}$ have $M$ elements from $\mathbb{R}^d$. In one dimensional cases ($d=1$), $\mathcal{X}$ has a bijection to $\mathcal{S}=\{X=(x_1,\cdots,x_M)| X\in \mathbb{R}^M, x_1\leq x_2\leq\cdots\leq x_M\}$. In multi-dimensional cases ($d>1$), we can construct a bijection from $\mathcal{X}$ to $\mathcal{S}=\{X=(\mathbf{x_1},\cdots,\mathbf{x_M})| X\in \mathbb{R}^{dM}, \mathbf{x_1}[1]\leq \mathbf{x_2}[1]\leq\cdots\leq \mathbf{x_M}[1], \text{if } \mathbf{x_i}[1:k]=\mathbf{x_{i+1}}[1:k], \mathbf{x_i}[k+1]\leq\mathbf{x_{i+1}}[k+1], i=1,\cdots M-1, k=1,\cdots,d-1\}$. For $X \in \mathcal{X}$, let $X=\{\mathbf{x_1},\cdots,\mathbf{x_M}\}$, we can sort elements in $X$ by the first entry, for the elements whose first entries are equal, sort them by the second entry, so repeatedly in this way, we get a final ordered sequence of the vectors, which is unique in $\mathcal{S}$. Note that $\mathcal{S}$ is a convex open subset of $\mathbb{R}^{dM}$, and is therefore homeomorphic to $\mathbb{R}^{dM}$. Since $N<dM$, no continuous injection exists from $\mathbb{R}^{dM}$ to $\mathbb{R}^N$. Thus no continuous injective function exist from $\mathcal{X}$ to $\mathbb{R}^N$. Hence we have reached a contradiction. \end{proof} \section{Dataset Details} Table \ref{tab:dataset} is the dataset information. All datasets are available from \cite{KKMMN2016}. \begin{table*}[ht] \small \centering \caption{Dataset information. \#G=number of graphs. \#C=number of classes. AvgN=average number of nodes in one graph. AvgE=average number of edges in one graph. Dim=node attribute dimension. MaxNeighb is the max 1-hop neighbors in all the nodes. } \begin{tabular}{l|c|c|c|c|c|c|c|l} \toprule & \#G & \#C & AvgN & AvgE & MaxNeighb & Dim & Type & Source \\ \midrule MUTAG &188 & 2 &17.93& 19.79 & 4 & -- & bioinformatics & \cite{debnath1991structure, kriege2012subgraph}\\ PTC &344 &2 &14.29& 14.69 & 4 & -- & bioinformatics & \cite{helma2001predictive, kriege2012subgraph}\\ NCI1 &4110& 2 &29.87& 32.30 & 4 & -- & bioinformatics & \cite{wale2008comparison, shervashidze2011weisfeiler}\\ PROTEINS &1113& 2 &39.06& 72.82 & 25 & -- & bioinformatics & \cite{borgwardt2005protein, dobson2003distinguishing}\\ COLLAB &5000& 3 &74.49& 2457.78 & 491 & -- & social networks & \cite{yanardag2015deep}\\ IMDB-B & 1000& 2 &19.77& 96.53 & 135 &-- & social networks & \cite{yanardag2015deep}\\ IMDB-M & 1500& 3 &13.00& 65.94 & 88 & -- & social networks & \cite{yanardag2015deep}\\ RDT-B & 2000 & 2 &429.63& 497.75 & 3062 & -- & social networks & \cite{yanardag2015deep}\\ \midrule ENZYMES & 600& 6 &32.63& 62.14& 9 & 18 & bioinformatics & \cite{borgwardt2005protein, schomburg2004brenda}\\ FRANKENSTEIN & 4337& 2& 16.90& 17.88& 4 & 780 & bioinformatics & \cite{orsini2015graph}\\ PROTEINS-att &1113& 2 &39.06& 72.82 & 25 & 1 & bioinformatics & \cite{borgwardt2005protein, dobson2003distinguishing}\\ SYNTHETICnew & 300 &2& 100.00& 196.25 & 9 & 1 & synthetic & \cite{feragen2013scalable}\\ Synthie &400& 4 &95.00& 172.93 & 20 & 15 & synthetic & \cite{morris2016faster}\\ \bottomrule \end{tabular}% \label{tab:dataset}% \end{table*}% \section{Results} The accuracy curves on training set and test set in the training process for different datasets are shown in Figure \ref{fig:traincurve}. \begin{figure}[h] \centering \subfloat[PROTEINS]{\includegraphics[width=.33\textwidth,page=1]{figures/acc_PROTEINS.pdf}} \subfloat[IMDBBINARY]{\includegraphics[width=.33\textwidth,page=1]{figures/acc_IMDBBINARY.pdf}} \subfloat[IMDBMULTI]{\includegraphics[width=.33\textwidth,page=1]{figures/acc_IMDBMULTI.pdf}} \subfloat[ENZYMES]{\includegraphics[width=.33\textwidth,page=1]{figures/acc_ENZYMES.pdf}} \subfloat[SYNTHETICnew]{\includegraphics[width=.33\textwidth,page=1]{figures/acc_SYNTHETICnew.pdf}} \subfloat[Synthie]{\includegraphics[width=.33\textwidth,page=1]{figures/acc_Synthie.pdf}} \caption{The accuracy curves on training set and test set in the training process.} \label{fig:traincurve} \end{figure} The final layer GNN output embedding in SYNTHETICnew dataset is visualized with PCA (Figure \ref{fig:pcavisual}) and two random dims (Figure \ref{fig:randvisual}). \begin{figure}[h] \centering \subfloat[ExpGNN-MLP]{\includegraphics[width=.33\textwidth,page=1]{figures/emb_MLP_PCA_ep300_SYNTHETICnew.pdf}} \subfloat[ExpGNN-power]{\includegraphics[width=.33\textwidth,page=1]{figures/emb_power_PCA_ep300_SYNTHETICnew.pdf}} \subfloat[GIN-final]{\includegraphics[width=.33\textwidth,page=1]{figures/emb_identical_PCA_ep300_SYNTHETICnew.pdf}} \caption{PCA visualization of the output embeddings on training data of Synthie dataset.} \label{fig:pcavisual} \end{figure} \begin{figure}[h] \centering \subfloat[ExpGNN-MLP]{\includegraphics[width=.33\textwidth,page=1]{figures/emb_MLP_rand2_ep300_SYNTHETICnew.pdf}} \subfloat[ExpGNN-power]{\includegraphics[width=.33\textwidth,page=1]{figures/emb_power_rand2_ep300_SYNTHETICnew.pdf}} \subfloat[GIN-final]{\includegraphics[width=.33\textwidth,page=1]{figures/emb_identical_rand2_ep300_SYNTHETICnew.pdf}} \caption{visualization of the output embeddings with 2 random dimensions on training data of Synthie dataset.} \label{fig:randvisual} \end{figure} \bibliographystyle{plain}
{'timestamp': '2020-10-13T02:27:50', 'yymm': '2010', 'arxiv_id': '2010.05427', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05427'}
arxiv
\section{Identifying Negations} \label{s:identifying_negs} In order to identify negations in English sentences (in source sentences when the translation direction is English to foreign, otherwise in reference translations and system outputs), we develop a negation cue detector that consists of a two-layer Bidirectional Long Short-Term Memory network with a Conditional Random Field layer on top (BiLSTM-CRF). This architecture (Figure \ref{fig:nn_architecture}) is similar to the one proposed by \newcite{reimers2017optimal}. We train and evaluate the model with CD-SCO, a corpus of Conan Doyle stories with negation annotations~\cite{morante-blanco-2012-sem}. CD-SCO includes common negation cues (\eg{}, never, no, n't), as well as prefixal (\eg{}, impossible, unbelievable) and suffixal negation (\eg{}, motionless). We map each token in the input sentence to its 300-dimensional pre-trained GloVe embedding \cite{pennington2014glove}. In addition, we extract token-level universal POS tags using spaCy \cite{honnibal2017spacy} and leverage another embedding (300-dimensional) to encode them. Embedding weights for universal POS are learned from scratch as part of the training of the network. We concatenate the word and POS embeddings, and feed them to the BILSTM-CRF architecture (size of cell state: 200 units). The representations learnt by the 2-layer BiLSTM are fed to a fully connected layer with ReLU activation function \cite{nair2010rectified}. Finally, the CRF layer yields the final output. We use the following labels to indicate whether a token is a negation cue: S\_C (single-token negation cue, \eg{}, never, not), P\_C (prefixal negation, \eg{}, inconsistent), SF\_C (suffixal negation, \eg{}, emotionless), and N\_C (not a cue). \begin{figure} \centering \input{figs/appendix/nn} \caption{The BiLSTM-CRF model architecture to identify negation cues. The input is a sentence, where each token is the actual word and its universal POS tag. The model outputs a sequence of labels indication of negation presence. The example input sentence is ``Holmes/NOUN would/VERB not/ADV listen/VERB to/ADP such/ADJ fancies/NOUN ,/PUNCT and/CCONJ I/PRON am/VERB his/DET agent/NOUN." } \label{fig:nn_architecture} \end{figure} \noindent \textbf{Training details.} We merge the train and development instances from CD-SCO, and use 85\% of the result as training and the remaining 15\% as development. We evaluate our cue detector with the original test split from CD-SCO. We use the stochastic gradient descent algorithm with \mbox{RMSProp} optimizer \citep{tieleman2012lecture} for tuning weights. We set the batch size to 32, and the dropout and recurrent dropout are set to 30\% for the LSTM layers. We stop the training process after the accuracy in the development split does not increase for 20 epochs, and the final model is the one which yields the highest accuracy in the development accuracy during the training process (not necessarily the model from the last epoch). Evaluating with the test set yields the following results: 92.75 Precision, 92.05. Recall, and 92.40 F1. While not perfect, the output of the cue detector is reliable, and an automatic detector is the only way to count negations in large corpora. The code is available at \url{https://github.com/mosharafhossain/negation-cue}. Note that our cue detector model has nearly 4.3 million parameters and takes 30 minutes on average to train on a CPU machine (Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz) with 64 GB of RAM. \section{Impact of Sentence Length} \label{s:length_factor} We present results on the sentence length bucket analysis (discussed in Section~\ref{sec:quant}) in Table \ref{t:eval_bucket_1} (sentences that fall within a standard deviation of the mean sentence length), Table \ref{t:eval_bucket_3} (sentences shorter than one standard deviation of the mean), and Table \ref{t:eval_bucket_2} (sentences longer than one standard deviation of the mean). \begin{table}[ht!] \small \centering \input{tables/appendix/eval_bucket_1} \caption{Evaluation of the best WMT18 and WMT19 submissions (same format as Table~\ref{t:best_all}) using only the sentences that fall within a standard deviation of the mean sentence length $[\mu\pm\sigma]$ for each dataset. } \label{t:eval_bucket_1} \vspace{-1em} \end{table} \begin{table}[ht!] \small \centering \input{tables/appendix/eval_bucket_3} \caption{Evaluation of the best WMT18 and WMT19 submissions (same format as Table~\ref{t:best_all}) using only the sentences shorter than one standard deviation of the average $(0,\mu-\sigma)$ for each dataset. } \label{t:eval_bucket_3} \vspace{-1em} \end{table} \begin{table}[ht!] \small \centering \input{tables/appendix/eval_bucket_2} \caption{Evaluation of the best WMT18 and WMT19 submissions (same format as Table~\ref{t:best_all}) using only the sentences longer than one standard deviation of the average $(\mu+\sigma,+\infty)$ for each dataset. } \label{t:eval_bucket_2} \vspace{-1em} \end{table} \section{Ranking of Submissions} \label{s:ranking_of_systems} In Section~\ref{sec:quant}, we show the ranking of systems obtained with all sentences, sentences with negation, and sentences without negation translating from Russian to English. In this section, we show the rankings of a few other language directions (Estonian to English in Table \ref{t:ranking_et_en}, Chinese to English in Table \ref{t:ranking_zh_en}, Lithuanian to English in Table \ref{t:ranking_lt_en}, Gujarati to English in Table \ref{t:ranking_gu_en} and English to Turkish in Table \ref{t:ranking_en_tr}). We observe again many changes in the rankings calculated with sentences containing negation. \begin{table*}[] \small \centering \input{tables/appendix/ranking_et_en} \caption{Rankings of all submissions translating from Estonian to English using all sentences (official WMT 2018 ranking), sentences with negation, and sentences without negation. tilde-comb refers to tilde-c-nmt-comb. } \label{t:ranking_et_en} \end{table*} \begin{table*}[] \small \centering \input{tables/appendix/ranking_zh_en} \caption{Rankings of all submissions translating from Chinese to English using all sentences (official WMT 2018 ranking), sentences with negation, and sentences without negation. Tencent-ens refers to the Tencent-ensemble-system. } \label{t:ranking_zh_en} \end{table*} \begin{table*}[] \small \centering \input{tables/appendix/ranking_lt_en_wmt19} \caption{Rankings of all submissions translating from Lithuanian to English using all sentences (official WMT 2019 ranking), sentences with negation, and sentences without negation. GTCOM and tilde-nc refer to the systems GTCOM-Primary and tilde-nc-nmt, respectively. } \label{t:ranking_lt_en} \end{table*} \begin{table*}[] \small \centering \input{tables/appendix/ranking_gu_en} \caption{Rankings of all submissions translating from Gujarati to English using all sentences (official WMT 2019 ranking), sentences with negation, and sentences without negation. CUNI-T2T, aylien-mt, and GTCOM refer to the systems CUNI-T2T-transfer-guen, aylien-mt-gu-en-multilingual, and GTCOM-Primary, respectively } \label{t:ranking_gu_en} \end{table*} \begin{table*}[] \small \centering \input{tables/appendix/ranking_en_tr} \caption{Rankings of all submissions translating from English to Turkish using all sentences (official WMT 2018 ranking), sentences with negation, and sentences without negation. alibaba5732 and alibaba5744 refer to the systems alibaba-ensemble-model.5732 and alibaba-ensemble-model.5744, respectively. } \label{t:ranking_en_tr} \end{table*} \section{Z-score vs. Metrics: WMT19} \label{s:metrics_app} \begin{table*}[ht!] \small \centering \input{tables/appendix/da_bleu_meteor} \caption{ Comparison of WMT19 rankings (Kendall's $\tau$) using several metrics, and sentences with and without negation. We compare the official scoring (normalized direct assessments, Z-score) and three automated metrics: BLEU, chrF++ and METEOR. All $\tau$ coefficients are statistically significant ($p<0.05$) (null hypothesis: there is no association between the Z-score and the automatic metric). The differences in the rankings obtained with the Z-score and the three metrics are more substantial when negation is present (lower $\tau$ coefficients). } \label{t:da_bleu_meteor} \vspace{-1em} \end{table*} In Section~\ref{sec:quant}, we discuss correlations between Z-scores and three widely-used automated metrics for assessing the quality of machine translation outputs using the data from WMT18. Table \ref{t:da_bleu_meteor} shows the same analysis using the data from WMT19. The conclusions are the same. \section{Related Work}\label{sec:background} \an{I don't like related work sections, and I prefer to include the necessary references throughout the text. That said, if you'd like to have one, I won't object :) How about a negation 101 section? -- For a standard related work section, though, I'd put this section before the conclusion, to not tire the reader and break the flow of the paper.} \ap{yep, fine with me. I like the idea of Negation 101!} \section{Conclusions}\label{sec:concl} We show, through both quantitative and qualitative analysis, that negation remains problematic for modern NMT systems. Though negation is ubiquitous and universal in its semantic effect, its realization varies tremendously from language to language. Typological similarity with respect to negation seems to correspond to better translation of negation, at least for the language pairs we investigate. Looking forward, we propose to harness linguistic insights about particular languages to better translate negation, and to devise fine-grained evaluation metrics to capture the adequacy of negation-involving translations. \section*{Acknowledgements} The authors are grateful to the anonymous reviewers for their constructive and thorough comments. We also thank Graham Neubig for initial discussions and feedback on the initial stages of the paper. This material is based in part upon work supported by the National Science Foundation under Grant No.~1845757. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of the NSF. \section{Introduction}\label{sec:intro} Machine translation (MT) has come a long way, steadily improving the quality of automatic systems, relying mostly on the advent of neural techniques~\cite{goldberg2017neural} and availability of large data collections. As neural MT (NMT) systems start to become ubiquitous, however, one should take note of whether the improvements, as measured by evaluation campaigns such as WMT~\cite[\textit{et alia}]{ws-2017-machine,ws-2018-machine-translation-shared,ws-2019-machine-translation} or IWSLT shared tasks~\cite[\textit{et alia}]{cettolo2017overview,niehues2018iwslt} or other established benchmarks, do in fact mean better quality, especially with regards to the semantic adequacy of translations. We focus specifically on negation, a single yet quite complex phenomenon, which can severely impact the semantic content of an utterance. As NMT systems increasingly improve, to the point of claiming human parity in some high-resource language pairs and in-domain settings \cite{hassan2018achieving},\footnote{We direct the reader to \cite{laubli-etal-2018-machine} and \cite{toral-etal-2018-attaining} for further examination of such claims.} fine-grained semantic differences become increasingly important. Negation in particular, with its property of logical reversal, has the potential to cause loss of (or mis-)information if mistranslated. Other linguistic phenomena and analysis axes have gathered significant attention in NMT evaluation studies, including anaphora resolution~\cite{hardmeier2014translating,voita-etal-2018-context} and pronoun translation~\cite{guillou-hardmeier-2016-protest}, modality~\cite{baker2012modality}, ellipsis and deixis~\cite{voita-etal-2019-good}, word sense disambiguation~\cite{tang-etal-2018-analysis}, and morphological competence~\cite{burlot-yvon-2017-evaluating}. Nevertheless, the last comprehensive study of the effect of negation in MT pertains to older, phrase-based models~\cite{fancellu-webber-2015-translating-negation}. In this work, we set out to study the effect of negation in modern NMT systems. Specifically, we explore: \begin{compactenum} \item Whether negation affects the quality of the produced translations~(it does); \item Whether the typically-used evaluation datasets include a significant amount of negated examples~(they don't); \item Whether different systems quantifiably handle negation differently across different settings~(they do); and \item Whether there is a linguistics-grounded explanation of our findings~(there is). \end{compactenum} Our conclusion is that indeed negation still poses an issue for NMT systems in several language pairs, an issue which should be tackled in future NMT systems development. Negation should be taken into consideration especially when deploying real-world systems which might produce incredibly fluent but inadequate output~\cite{martindale-etal-2019-identifying}. \section{So what's going wrong?}\label{sec:ling} \begin{table*}[t] \small \centering \input{tables/neg_errors} \caption{(a) Typological properties related to negation (left), and (b) Error analysis of negation-containing test set sentences (right) for five non-English WMT languages. With the exception of Finnish, languages more similar to English with respect to negation show fewer negation-related errors in translation. We discuss Finnish below.}\label{tab:negErrors} \vspace{-1em} \end{table*} We have shown that translations with negation receive lower scores on average than translations without negation, for most languages. We have also shown that this is true regardless of a system's overall performance. To better understand \emph{why} negation is challenging for NMT systems, we look into the properties of negation in individual languages, as well as the particular errors made by the systems. For this analysis, we restrict ourselves to 5 language pairs, mostly selecting languages with substantial negation-related performance differences for one or more of the quantitative analyses (Turkish, Lithuanian, Russian, and Finnish). We also consider German, as English-German/German-English is one of the most commonly used translation benchmarks. \subsection{Typological perspective on negation} The World Atlas of Linguistic Structures \cite[WALS][]{wals} is a typological database of the world's languages. The core of WALS is a partially-filled grid of typological features vs. languages. For example, WALS identifies 5 broad categories of features related to the realization of negation. The left side of table~\ref{tab:negErrors} shows the relevant feature values for our languages.\footnote{We leave out prohibitives~\cite{wals-71}, as this construction is infrequent and does not affect our analysis.} \textbf{(i.) Clausal: Form of simple clausal negation.} This feature captures the morphological form of clausal negation for declarative sentences \cite{wals-112} and has three possible values. \textbf{Particle} languages use a negation word (e.g. \emph{not} in EN or \emph{nicht} in DE), \textbf{Affix} languages use a negative affix (e.g. the prefix \emph{ne-} in LT), and \textbf{Aux} languages use a negative auxiliary verb. Aux languages are the rarest; only 47 out of 1157 languages with a value for this property in WALS use a negative auxiliary verb. Finnish is one of these. In FI the negative verb (underlined) inflects to agree with the subject, as for example: \emph{Linja-auton kuljettajaa \underline{ei} epäillä rikoksesta}, ``The bus driver is not suspected of a crime.'' This means that clausal negation in Finnish declarative sentences is always expressed with the same verb, and the form of the verb relies only on the person and number of the subject; other aspects of the sentence do not change the form of the verb. \textbf{(ii.) PredNeg: Presence of predicate negation with negative indefinites.} In some languages, negative indefinite pronouns (e.g. \emph{nothing, nowhere}) require an additional particle negating the predicate \cite{wals-115}. Russian is an example of a language with the predicate negation requirement: \emph{\foreignlanguage{russian}{Сергей Сироткин: Я \underline{ничего не} мог сделать [...] }}, ``Sergey Sirotkin: There was nothing I could do [...].'' \foreignlanguage{russian}{ничего} translates as \emph{nothing} in English, and \foreignlanguage{russian}{не} is the predicate negation particle. Most varieties of English do not use a predicate negation particle, though some do, leading to a value of `No/Mixed' for this feature in WALS. Because our systems all translate from and into a mainstream variety of English, we use `No' for this analysis. \textbf{(iii.) Symm: Symmetricity of negation.} \citet{wals-113} characterizes languages as symmetric or asymmetric with respect to simple clausal negation. In symmetric languages (e.g. DE and RU), negated clauses are the same as their non-negated counterparts, with the exception of the negation word. In asymmetric languages (e.g. Finnish), presence of the negation word triggers other grammatical changes in the sentence. For FI, the negative auxiliary is inflected and the main verb changes to an uninflected form. Some languages (like English) show both behaviors depending on context. \textbf{(iv.) Order: Order of negation cues and other constituents.} Various aspects of the ordering of negation cues in the clause are addressed in two sections of WALS \cite{wals-143,wals-144}. Here we look only at the relative ordering of the negation cue and the verb. NegV (negation cue before the verb), the ordering seen in EN, RU, and FI, is the most common (525/1325 languages sampled). LT also shows NegV ordering, with the difference that the negation cue is an affix rather than a particle (indicated by square brackets and hyphen: [Neg-V]). TR shows the opposite ordering, and German allows both NegV and VNeg. \paragraph{Similarity to English.} For this analysis, we assign each language a score for its similarity to English with respect to typological properties of negation, based on WALS data. English is the comparison language because it is the common language in all translation directions. For each of the four WALS properties, a language scores one point for a feature with the same value as English, and a half point for a partial match. For example, Russian gets a half-point for the Symm feature. \subsection{Are errors due to negation?} In a next step, we look closely at negation-containing sentences to determine how often systems get the negation wrong. For these five language pairs, we extract all test-set sentences with negation cues detected in the reference translations; the number of sentences per language pair is shown in Table~\ref{tab:negErrors}. After sorting sentences according to Z-score, we compare reference translation and system output and annotate (Yes/No) whether the system gets negation wrong, compared to the reference. In contrast to \citet{fancellu-webber-2015-translating-negation}, who do fine-grained annotation of translation errors related to negation (focusing on deletion/insertion/substitution of cues, focus, and scope), we ask a broader question designed to capture semantic adequacy focused on handling of negation. We only choose \textbf{Yes} if the system output shows a glaring error in meaning \textit{related to negation} (see Section~\ref{sec:negation} for discussion of some typical error types). The percentage of sentences that contain negation with negation-related errors (Table~\ref{tab:negErrors}, right side) ranges from only 2.7\% in Finnish up to more than 17\% in Turkish. The core finding from this analysis is that (except for Finnish) \textbf{the languages with the fewest negation-related errors are most similar to English with respect to the typology of negation.} Turkish differs from English on three of four WALS features. In addition, clausal negation in Turkish occurs through a negative affix attached to the verb root. The complexity of Turkish verbal morphology means that: a) the negative morpheme undergoes changes in form depending on its context; and b) the negative morpheme is tucked away in the interior of the verb word, between the stem and both tense-aspect-mood markers and person agreement morphology \cite{emeksiz2010negation}. In \emph{Ben seni unut\underline{-ma}-di-m,} (``I have not forgotten you'') \cite{emeksiz2010negation}, the negative morpheme appears as \emph{-ma}. Affixal clausal negation is not unusual from a typological perspective, but the morphological richness of Turkish makes it particularly difficult to recognize negated clauses. Lithuanian, Russian, and German each differ from English in their values for 1-2 features. Interestingly, these languages occupy a sort of middle ground for the percentage of negation errors seen. Finnish seems to be a special case. Though it differs from English on 2-3 feature values (2.5 in our scoring system), we see a very low proportion of negation-related errors in system output translations. We attribute this to the negative auxiliary, a way of expressing negation that is easy to identify, even for non-speakers of the language (and presumably also for NMT systems). 175 out of 185 source sentences contain at least one easily-identifiable negation cue: a conjugated form of the negative auxiliary, prefixal negation on adjectives, a negative conjunction ($\sim$ EN \emph{lest, neither}), or a negative preposition ($\sim$ EN \emph{without}). We hypothesize that the clarity and detectibility of source-side negation cues improve the quality of NMT systems when translating negation. \paragraph{Other observations.} In addition to the main finding above, we notice that, for some languages, certain negation cues are either more or less likely to appear in sentences with negation errors. For example, in German, negation errors are most likely when the cue is \emph{nicht}-V (negation particle modifying the verb); this is also the most frequent cue overall. Of 46 source sentences containing the negative indefinite article \emph{kein}, only one triggers a negation error. We have performed this analysis only for languages where we can reliably (manually) identify negation cues on the source side; we hope to extend to more languages in the future. Figurative expressions, identified either on the source side or judging by the reference translation, often contain negation errors. We also see recurring problems with the interaction of negation and the translation of certain temporal expressions, and occasional problems with negation errors in the reference translations~\cite{freitag2020bleu}. Encouragingly, errors of outright contradiction between the reference translation and system output are rare. \section{Negation 101}\label{sec:negation} Negation at its most straightforward---simple negation of declarative sentences---involves reversing the truth value of a sentence. \emph{Skies are blue}, for example, becomes \emph{Skies are not blue}. \textbf{Clausal negation} of an existing utterance, defined roughly as negation of the entire clause rather than a subpart, produces a second utterance whose meaning contradicts that of the first.\footnote{See \citet{penka2015negation} and \citet{horn2010expression}, among others, for more on the semantics, syntax, and interpretation of negation.} Without stipulations about special contexts (e.g. referring to \emph{skies} in two different places), it is not possible for both utterances to be true. \textbf{Constituent negation} involves negation of a non-clausal constituent, such as \emph{happy} in \emph{The universe is not happy with us}. Finally, \textbf{lexical negation} refers to two different phenomena. The first are words formed by adding negative affixes, such as \emph{non-starter} or \emph{unhappy}. The second are words with no negative affixes whose meanings nonetheless convey negation, such as the verb \emph{lack} in \emph{This engine lacks power}. Negation is a core property of human language; every language provides mechanisms for expressing negation, and, cross-linguistically, there are a small number of strategies used for its expression \cite{dahl1979typology,miestamo2007negation,horn2010expression}. Following \citet{wals-112}, languages may use three different mechanisms for clausal negation: a) \textbf{negative particles} (e.g. English \emph{not} or German \emph{nicht}); b) \textbf{negative morphemes or affixes} (e.g. Lithuanian \emph{ne-}); and/or c) \textbf{negative auxiliary verbs}, (e.g. Finnish \emph{ei}), a strategy in which (generally) inflection moves from the main verb to the auxiliary verb. Depending on the language, constituent and lexical negation may be coded using the same mechanisms as clausal negation, or with entirely different mechanisms. Negative pronouns (e.g. English \emph{nothing} or \emph{nowhere}), negative adverbials (\emph{never}), and negative polarity items (\emph{any}) add additional complexity to the expression of negation. Even within negation, cross-linguistic variability is immense, ranging from different linguistic strategies, to different structural relationships between linguistic elements, even to differences in interpretation. \citet{szabolcsi2004conjunction} show that the interpretation of conjunction, disjunction, and negation can differ cross-linguistically. In English ``not X and Y'' can be interpreted as either $\neg X\wedge\neg Y$ (``neither X nor Y'') or $\neg X \vee \neg Y$ (``not X or not Y'') while in Hungarian (and Russian, Italian, etc.) only the first interpretation is allowed. Such differences are potential error sources for translating negation. \paragraph{Negation-related translation errors.} Here we show examples of different types of errors that NMT systems make when translating negation. \textbf{1. Negation Omission}: The system output completely omits the translation of the negation cue. The following reference translation from the Turkish-English WMT18 shared task reads: ``[...] Don't run for public office, if you can't take heat from voters.'' The best performing system, though, outputs ``[...] if you can't take criticism from voters, you're a candidate for state duty,'' contradicting the reference translation.\footnote{The source sentence in Turkish is: ``Eğer seçmenlerin eleştirilerini kaldıramıyorsan devlet görevine aday olma.''} \textbf{2. Negation Reversal}: The semantic meaning is reversed, so that the sentence ends up meaning the opposite of the intended meaning, often in fine-grained ways. Consider the following reference translation from WMT19 Lithuanian-English: ``The family lawyer of the deceased biker also asks for reversal of the verdict of not guilty.'' Here the ``verdict of not guilty'' entails that there was no conviction. The output of the translation system, however, implies there was a conviction to be reversed: ``The family lawyer of the dead rider also asks for the conviction to be lifted.''\footnote{The Lithuanian source is: ``Panaikinti išteisinam\k{a}j\k{i} nuosprend\k{i} prašo ir žuvusio motociklininko šeimos advokatė.''} \textbf{3. Incorrect Negation Scope:} The system output makes errors in argument mapping, such that the wrong constituent is negated. Here we look at an example from Finnish-English WMT18. Differences between the reference translation (``The reason is not the Last Judgment'') and the best performing system output (``The last judgment is not the reason'') lead to differences in interpretation.\footnote{Finnish source sentence: ``Viimeinen tuomio ei ole syy.''} \textbf{4. Mistranslation of Negated Object:} When the negated element in the sentence is wrongly translated, meaning is disturbed. This example comes from WMT18 German-English. The reference translation begins ``No exchange of personal data occurred [...],'' and the system output for the best system begins ``There was no exchange of personnel [...].''\footnote{The source sentence in German is: ``Zu einem Personalienaustausch kam es aber nicht, da der 75-Jährige die Dame auf dem Parkplatz nicht mehr finden konnte.''} Aside from the mistranslated object noun phrase, the meaning is intact. \noindent These error types vary in their severity, but each has the potential to completely change the meaning conveyed by the translation. \section{Quantitative Analysis}\label{sec:quant} We conduct a thorough quantitative analysis of the WMT18 and WMT19 submissions around six questions investigating the role of negation in MT. \begin{table}[ht!] \small \centering \input{tables/best_all} \caption{Evaluation of the best WMT18 and WMT19 submissions (normalized direct assessments, Z) for each language direction using all sentences, sentences with negation (w/ neg.), and sentences without negation (w/o neg.). Translating sentences with negation obtains worse results in many languages (e.g., Turkish, Russian, Estonian, Lithuanian, Gujarati). } \label{t:best_all} \vspace{-1em} \end{table} \paragraph{Q0: Is Negation Present in Evaluation Datasets?} We found that 9.6--20\% of source sentences contain negation depending on the target language. These percentages are lower than what we observe in online reviews~(23--29\%), books~(29\%) and conversation transcripts~(27--30\%) \cite{hossain-etal-2020-analysis}, and are also lower than previous reports \cite{morante-sporleder-2012-modality}. \paragraph{Q1: Is Translating Sentences with and without Negation Equally Hard?} Table \ref{t:best_all} shows the Z-scores obtained by the best submission in each translation direction using all sentences, sentences with negation, and sentences without negation. Many language pairs obtain substantially worse Z-scores for sentences containing negation: Turkish, Russian, and Estonian in WMT18 (20.0--68.9\% lower), and Lithuanian, Gujarati, and Russian in WMT19 (21.2--60.3\% lower). When both translation directions are available for a language pair (WMT18), translating negation into English from these languages consistently receives lower scores than translating from English. Interestingly, sentences with negation receive better Z-scores in Finnish, Chinese, and Kazakh (4.6--45.8\% higher). Finally, only two languages show opposite trends translating from and into English negations: German and Czech, although the differences in Z-scores are smaller (-3.4--11.7\%). Naturally, other factors beyond the presence of negation can affect the results. Since sentence length tends to negatively correlate with translation quality, the length difference between sentences with and without negation could be an important factor. Sentences with negation are on average longer than sentences without negation,\footnote{This is expected if one considers the additional tokens required, such as the negation cue, or other potential syntactic changes (e.g. adding an auxiliary verb).} but we do not consider the differences (typically within 2-6 words) to be significant. Nevertheless, we replicated our analysis from Table~\ref{t:best_all} using only the sentences that fall within a standard deviation of the mean sentence length $[\mu\pm\sigma]$ for each dataset. The results, shown in Table~\ref{t:eval_bucket_1} in the Appendix, do not differ significantly from our Table~\ref{t:best_all} analysis. We identify one major inconsistency, in the case of English-Finnish translation direction; we attribute it to issues in identifying negation in that dataset, and we leave further analysis as future work. In any case, performing the same analysis on sentences that fall outside that bucket (that is, sentences shorter or longer than one standard deviation of the average $(0,\mu-\sigma)$ and $(\mu+\sigma,+\infty)$, respectively, available in Tables~\ref{t:eval_bucket_3} and~\ref{t:eval_bucket_2} in the Appendix) does not yield conclusive results. We attribute this to the fact that these buckets include fewer data samples and too many outliers (of very easy or very hard sentences). In any case, the consistency of the results in the ``average'' case leads us to conclude: a) that \textbf{negation affects Z-scores in all language pairs and directions}, and b) \textbf{that translating from or into English sentences containing negation in most language directions is harder than sentences without negation.} \begin{table}[t] \small \centering \input{tables/ranking_all} \caption{Comparison of rankings (Kendall's $\tau$) of all submissions to WMT18 and WMT19 using (a) all sentences and those with negation (w/ neg.), (b) all sentences and those without negation (w/o neg.), and (c) sentences with and without negation (w/ v. w/o). The numbers between parentheses indicate the number of sentences with human scores for the best system. All $\tau$ coefficients are statistically significant ($p < 0.05$) except those that are underlined (null hypothesis: there is no association between the rankings). We note, however, that the $\tau$ coefficients are substantially lower in most language directions when negation is present. } \label{t:ranking_all} \end{table} \begin{table*}[ht!] \small \centering \input{tables/ranking_one_pair} \caption{Rankings of all submissions translating from Russian to English using all sentences (official WMT ranking), sentences with negation, and sentences without negation. FB-FAIR, afrl, and afrl-sys refer to Facebook-FAIR, afrl-ruen-syscomb, and afrl-syscomb19. We use \up{k} (\down{k}) to indicate the gains (losses) in absolute ranking with respect to the ranking obtained with all sentences. For example, in WMT19, MSRA.SCA is 7 positions lower in the ranking obtained with sentences with negation (from 6th to 13th), and online.A is 6 positions higher (from 9th to 3rd). As the $\tau$ coefficients indicate (Table \ref{t:ranking_all}), there are barely any changes in the ranking obtained with sentences without negation, but many changes in the ranking obtained with sentences with negation. } \label{t:ranking_one_pair} \end{table*} \paragraph{Q2: Does Negation Affect Rankings?} Just because the best system in each language direction obtains better or worse Z-scores (Q1), it is not necessarily the case that \emph{all} systems do better or worse. In order to check if rankings are affected, we calculate the correlation between rankings obtained with Z-scores and (a)~sentences with negation and (b)~sentences without negation (outlined in Table~\ref{t:ranking_all}). We use Kendall's $\tau$ coefficient \cite{kendall1938new}, which only considers the ranking---not the differences in Z-scores. $\tau$ coefficients range from~-1 to~1 (absolute negative and positive correlation), and $\tau=0$ indicates no correlation at all. We observe that the Z-score rankings for all sentences and sentences without negation are very close in all language directions: $\tau\!\in\!(0.8, 1.0)$, and all but two (\mbox{tr$\rightarrow$en} and \mbox{lt$\rightarrow$en}) are above~$0.9$. The rankings obtained based on sentences with negation, on the other hand, show lower $\tau$ correlations, except language pairs involving German and Czech. Except those involving German and Chinese, all language pairs have at least one translation direction with $\tau\!\le\!0.85$. We also observe that the rankings change much more (lower $\tau$ coefficients) translating from Chinese, Estonian, and Russian into English sentences containing negation than translating from English sentences containing negation into those languages. It is worth noting that the relative drop in Z-score of the best system when negation is present (\%$\Delta$, Table \ref{t:best_all}) is not a good predictor of ranking changes. For example, all submissions translating from English to Russian obtain proportionally worse Z-scores when negation is present in the source text, thus the ranking barely changes ($\tau\!=\!0.944$) despite $\%\Delta\!=\!-30.4$. On the other hand, we observe many ranking changes translating from Chinese to English ($\tau\!=\!0.495$) and vice versa ($\tau\!=\!0.758$), despite $\%\Delta$ of only~15.7 and~4.6. In Table \ref{t:ranking_one_pair}, we show the ranking of submissions translating from Russian to English obtained with all sentences (official WMT ranking), and the rankings obtained with sentences containing and not containing negation. The ranking changes in WMT18 (\up{} and \down{} arrows) illustrate the $\tau$ correlation coefficients obtained with sentences with negation (many changes, $\tau\!=\!0.575$) and without negation (few changes, $\tau\!=\!0.912$). The supplementary materials contain similar tables for selected language pairs in WMT18 and WMT 19. We conclude that \textbf{rankings based on sentences containing negation are substantially different for most translation directions. Thus, different systems behave differently translating from and into English sentences containing negation.} \begin{figure}[t] \centering \includegraphics[width=.9\columnwidth]{figs/corr_scores_rela} \vspace{-1em} \caption{Correlation between the Z-score with all sentences and the \textit{relative} drop for the sentences with negation (best system per language pair). } \label{f:all_diff} \vspace{-1em} \end{figure} \paragraph{Q3: Is Translating Negation Harder with Harder Language Pairs and Directions?} Not all translation directions are equally easy to model, as evidenced by the wide variance of direct assessment scores in the WMT competitions (Table~\ref{t:best_all}). Figure~\ref{f:all_diff} shows that there is is a weak positive correlation between the \emph{relative} differences in Z-score with negation and the overall Z-score. There are however many exceptions/outliers, e.g., translations from Finnish or Russian into English receive roughly the same Z-scores, but negation is much harder from Russian than from Finnish. We conclude that \textbf{the difficulty of translating between two languages is only a weak indicator of how difficult it is to translate negation, most notable with overall Z-scores below 0.3.} \paragraph{Q4: Is Translating Negation between Similar Languages Easier?} Intuition may lead us to believe that it is easier to translate negation between similar languages. We show the correlation between language similarity and relative differences in Z-scores with and without negation in Figure~\ref{f:similarity_diff}. To calculate similarity between two languages, we follow \newcite{zhang-toral-2019-effect} and \newcite{berzak2017predicting}. Briefly, we obtain feature vectors for each language from lang2vec~\cite{Littel-et-al:2017}, and define the similarity between two languages as the cosine similarity between their feature vectors. More specifically, we concatenate 103 morphosyntactic features and 87 language family features (only those relevant to the languages we work with) from the URIEL typological database. We conclude that \textbf{similarity between languages is only a weak indicator of how difficult it is to translate negation}. We revisit this question in Section~\ref{sec:ling} with an in-depth linguistic discussion. \begin{figure}[t] \centering \includegraphics[width=.9\columnwidth]{figs/corr_sim_scores_rela} \vspace{-1em} \caption{Correlation between the language similarity and the \textit{relative} drop for the sentences with negation. \iffalse \caption{Correlation between the \textit{relative} difference in Z-scores between sentences with and without negation.} \fi \label{f:similarity_diff} \vspace{-1em} \end{figure} \begin{table*}[ht!] \small \centering \input{tables/da_bleu_meteor_wmt18} \caption{ Comparison of WMT18 rankings (Kendall's $\tau$) using several metrics, and sentences with and without negation. We compare the official scoring (normalized direct assessments, Z-score) and three automated metrics: BLEU, chrF++ and METEOR. We provide the same analysis for WMT19 in the supplementary materials. All $\tau$ coefficients are statistically significant ($p<0.05$) except those that are underlined (null hypothesis: there is no association between the Z-score and the automatic metric). The differences in the rankings obtained with the Z-score and the three metrics are more substantial when negation is present (lower $\tau$ coefficients). } \label{t:da_bleu_meteor_wmt18} \end{table*} \paragraph{Q5: Are Automatic Metrics Worse with Negation?} Machine translation evaluation is an active field of research, and new automatic metrics are proposed yearly \cite[\textit{et alia}]{fomicheva2019taking}. The ideal metric would correlate perfectly with human judgments, and increased correlation is often a justification for new metrics \cite{lavie-agarwal-2007-meteor}. We investigate whether three popular metrics (BLEU, chrF++ and METEOR) are equally suitable when applied to sentences with and without negation. Note that the smallest change when negation is present (e.g., dropping \emph{never} or \emph{n't}) is likely to result in a (very) bad translation. Table~\ref{t:da_bleu_meteor_wmt18} shows the correlations (Kendall's $\tau$) between the rankings on WMT 18, obtained with the Z-scores and the three metrics using (a)~sentences with negation, and (b)~sentences without negation When negation is present, the three metrics obtain worse correlation coefficients or just slightly better (within 5\%). This is true with all translation directions except those involving Finnish or Turkish. The drops in correlation coefficients are substantial with the three metrics in many translation directions, e.g., from Russian, Chinese or Gujarati into English. While there is no winner across all language directions (e.g., chrF++ is better with Russian, and METEOR with Czech), the correlation coefficients show, unsurprisingly, that BLEU is the least suited to evaluate translation quality when negation is present. We conclude that \textbf{automatic metrics are bad estimators of machine translation quality when negation is present, and that chrF++ and METEOR are better suited than BLEU.} \section{Experimental Setup}\label{sec:setup} We follow the setup of the Conference on Machine Translation~(WMT), in particular, the 2018 and 2019 Shared Tasks~\cite{bojar-etal-2018-findings,barrault-etal-2019-findings}. We compare reference and system translations using normalized direct assessments. Direct assessments are scores from 0 to 100 provided by researchers or crowd workers. In order to account for the hundreds of human annotators with potentially different criteria, raw direct assessments are normalized using the mean and standard deviation of each annotator. The normalized direct assessment is the average of the sentence-level direct assessments. We refer to normalized direct assessment with Z-score or simply~Z. Z-scores are the official ranking criterion in WMT competitions, and are preferred to automated metrics to assess the quality of MT. Nevertheless, most of the MT community still relies on automated metrics for development and system comparisons. Thus, we also work with three automated metrics, in particular BLEU~\cite{post-2018-call}, chrF++~\cite{popovic-2017-chrf}, and METEOR~\cite{denkowski-lavie-2011-meteor}. In the remainder of the paper we present two complementary analyses. First, we investigate the role of negation in machine translation with an emphasis on numeric evaluation (Section~\ref{sec:quant}). Second, we investigate from a linguistic perspective what makes translating negation difficult (Section~\ref{sec:ling}). \noindent \textbf{Datasets.} We work with all submissions to the news translation tasks in the WMT18 and WMT19 competitions. Table~\ref{t:ranking_all} shows the language directions in each competition along with the number of sentences with Z-scores in the corresponding test set. Specifically, we investigate systems for both translation directions between English and Russian (\textsc{ru}), Estonian (\textsc{et}), German (\textsc{de}), Turkish (\textsc{tr}), Finnish (\textsc{fi}), Czech (\textsc{cs}), and Chinese (\textsc{zh}). We also use Lithuanian (\textsc{lt}), Gujarati (\textsc{gu}), and Kazakh (\textsc{kk}) to English systems from WMT 19. \noindent \textbf{Negation Detection.} Due to the lack of reliable negation detection systems in most languages, our study is limited to focusing on cases where negation is present in English. This creates slightly different settings for translation into and out of English, hence we distinguish them in our analyses and presentation of the results. For translation out of English, we detect negation cues in the source sentence. For translation into English, we detect negation cues in the reference translations. In order to detect negation automatically, we train a negation cue detector for English using a Bi-LSTM neural network with a CRF layer, as described in~\cite{hossain-etal-2020-predicting}. Trained and evaluated with a publicly available corpus~\cite{morante-blanco-2012-sem}, it obtains 0.92 F1. The cue detector recognizes single-token cues (\emph{not}, \emph{n't}, \emph{never}, \emph{no}, \emph{nothing}, \emph{nobody}, etc.) as well as affixal cues (\emph{im}possible, \emph{dis}agree, fear\emph{less}, etc.). The supplemental materials provide details about the architecture and input representation of the cue detector. \paragraph{Important note.} We make the strong assumption in our analyses that presence of a negation cue in the English reference translation indicates presence of negation in the source sentence. We acknowledge that investigating the role of negation in machine translation by only looking at English negations likely misses valid insights. For example, a Spanish sentence containing negation (e.g., \emph{``El ladrón no estaba preocupado hasta que vino la policía''}) can be translated into English either with negation (\textit{``The thief was not worried until the police arrived''}), or without negation (\emph{``The thief only worried when the police arrived''}). We reserve for future work a more thorough analysis of correspondences between negation in source sentences and negation in English reference translations.
{'timestamp': '2020-10-13T02:28:00', 'yymm': '2010', 'arxiv_id': '2010.05432', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05432'}
arxiv
\subsection{View-based positional distribution common knowledge}\label{sec:appendix_know} In this appendix, we share the formulation of view-based common knowledge inspired from the paper \cite{DeWitt2018}. All vehicles have a circular field of view with a fixed radius(set based on communication range). Then, common knowledge $\mathcal{I}^{\mathcal{G}}$ between groups of $\mathcal{G}$ of agents arises through entity-based field-of-view common knowledge\cite{DeWitt2018}. The state $s$ is composed of a number of entities $e\in \varepsilon$ with state features $s^e$ i.e. $s = \{s^e | e \in \varepsilon\}$. In this work, all entities are agents $a \in \mathcal{A} \equiv \varepsilon$ and $s^a$ is the position of vehicles i.e. $s^a = (x^a, y^a)$. The observation $z^a$ contains the subset of state features $s^e$ from all the entities $e$ that $a$ can see. Whether $a$ can see $e$ is determined by the binary mask $\mu^a(s^a, s^e)\in \{\bot, \top\}$. In our scenario, binary mask checks whether the distance between $s^a, s^e$ is lower than the observation radius $R$. Also, $\mu^a$ and $R$ are the same for all agents. The set of all entities the agent $a$ can see is therefore $\mathcal{M}^a := \{e | \mu^a(s^a, s^e)\} \subseteq \varepsilon$. The agent's observation is specified by the deterministic observation function $o(s,a)$ such that $z^a = o(s,a)=\{s^e | e \in \mathcal{M}^a\} \in \mathcal{Z}$. Then, each agent receives $z^a$ e.g. positions of the observed vehicles to create \textit{view-based positional distribution} vector such that $v^a = g(z^a, B, R)$. In our scenario, agents are homogeneous i.e. the function $g$, binary mask $\mu^a$ and variables $B, R$ are the same for all agents. Furthermore, our aim is to learn cooperative behavior in centralized training e.g. far vehicles should learn to select the same action/resource. Thus, the model can learn the common knowledge function $\mathcal{I}^{\mathcal{G}}$. Then, the commonly known trajectory $\tau_t^G$; \begin{equation} \tau_t^{\mathcal{G}} := \mathcal{I}^{\mathcal{G}}(\tau_t^a) = \mathcal{I}^{\mathcal{G}}(\tau_t^{\overline{a}}) , \forall a, \overline{a} \in \mathcal{G}. \end{equation} From the observation trajectory, $\tau_t^a = (v_1^a, ..., v_t^a)$ of any agent $a \in \mathcal{G}$. The commonly known position distribution $v_k^{\mathcal{G}} = \{g(z_k^{\mathcal{G}}, B, R) |z_k^{\mathcal{G}}\in \mathcal{Z}, B\in \mathbb{Z}^+, R\in \mathbb{Z}^+\}$ with $z_k^{\mathcal{G}} = \{s_k^e | e\in \mathcal{I}^{\mathcal{G}} \}$. The commonly known trajectory \begin{equation} \begin{split} \tau_t^{\mathcal{G}} = (v_1^{\mathcal{G}},\mathbf{u}_1^{\mathcal{G}},..., v_t^{\mathcal{G}},\mathbf{u}_t^{\mathcal{G}} ) \\ \mathbf{u}_t^{\mathcal{G}} := (u_t^{a},..., u_t^{a}), a \in \mathcal{G} \\ \text{with policy } \pi^{\mathcal{G}}(u_t^{a}|\tau_{t}^{\mathcal{G}},\tau_t^a ).\\ \end{split} \label{eq:commonknowledge} \end{equation} Each agent can deduce the commonly known positional distribution vector from its view-based positional distribution and individual action for each agent can be obtained by condition on commonly known positional distribution and view-based position distribution Equation \ref{eq:commonknowledge}. Simply, if all agents in the system can see each other, then an agent can estimate the observations of the others from its own observation and selects an action by estimating the actions of others to maximize the system objective. Each agent view is the group's joint view, joint actions are generated based on this joint view. Each agent performs its part from the joint action which is determined by the view of the agent. In this work, actions of the agent do not change \textit{directly} the construction of common knowledge. Unless all use the same resource persistently for transmission, then agents can not receive the messages of others due to half-duplexity constraint. Then, agents remove the positions of other agents from their neighboring table if they can not receive any update for the last $m$ transmissions from other agents. Thus, the action of agent $a_t^{i}$ has only a long term effect on common knowledge. In this work, common knowledge mainly depends on the system dynamics i.e. mobility of vehicles. This can simplify the problem since learning system dynamics(LSTM helps for mobility prediction) easier than developing common knowledge. Otherwise, we would need to know the actions of other agents in order to take an individual action based on local observation or we would need to take joint actions as in \cite{DeWitt2018}. Then, we might say that relying on common knowledge which is deducted by the information that is \textit{not} directly affected by the actions of the agents, can improve cooperative behaviour and allow the model to develop individual actions instead of joint actions based on local observations. \subsection{Neighbor Table Updates} \label{app:neigh} Each vehicle holds a neighboring table which includes the positions of the other vehicles on the road and piggybacks the neighboring table together with the CAM messages so that every vehicle on the road knows the positions of the other vehicles. We adopt a similar mechanism to keep the neighboring table updated as a destination-sequenced-distance vector(DSDV) routing scheme which is based on the Bellman-Ford algorithm \cite{10.1145/190314.190336}. Each entry in the neighbor table contains a sequence number along with vehicle id and positions, which is updated(increased by "1") by the vehicle of the entry for every transmitted CAM message. When a vehicle receives a CAM message from the other vehicles, it checks every entry in the neighbor table of the transmitter in the CAM message. If the sequence number in an entry of the transmitter neighbor table is higher than the sequence number of the same entry(indicates the same vehicles), the receiver updates the positions of the vehicle in the entry with the positions received by transmitter neighbor table. Additionally, each entry in the table includes a \textit{last update} counter which expresses the time between the updates of this entry. When a vehicle piggybacks its neighbor table together with a CAM message, it increases the \textit{last update} counter in all the entries except its own entry. When a vehicle receives a neighbor table of the transmitter which has a higher sequence number for the same entry, it reset the \textit{last update} counter to zero. If the \textit{last update} counter is higher than a threshold which can be adjusted based on mobility e.g. 2 seconds, then we omit this entry when extracting positional distribution from the table assuming that the receiver vehicle is no longer in the coverage of the transmitter vehicle. Note that, we apply such a mechanism so that all vehicles on the road can know the updated positions of the other vehicles. We refer to the paper \cite{10.1145/190314.190336} for readers to get more intuitions about the mechanism. \section{Conclusion and Future Work} \label{sec:conc} In this work, we proposed a novel algorithm, distributed resource allocation with multi-agent DRL (DIRAL) for out of coverage vehicular communications. The algorithm proposes a novel solution to the congestion problem that can rise naturally due to the uncontrolled mobility of the vehicles. We show that our proposal improves the PRR in a congested scenario by up to $20\% $. This algorithm enables V2X to be used more reliably for out of coverage scenarios. The practicality of our results are demonstrated by training in a simple Python based simulator and deploying on a more elaborate C++ based system simulator (RealNeS). The results presented herein are limited to vehicles moving in single direction. However, the case of vehicles moving in different directions can be handled by means of separate resource pools for different directions and applying DIRAL within the resource pools. A solution with resource pools is left for future work. \section{Further Discussions} \label{sec:discussions} \subsection{Random velocity} In all of the experiments, the positional distribution of the vehicles on the road is finite and expected. After the training, the model can generate one joint action for each positional distribution and each vehicle can apply its part of the action based on their view-based positional observation. We tested the model with the toy example also under random velocities. At the end of the episode, each vehicle either accelerate(+0.1) or decelerate(-0.1) i.e. $\min(0.8 m/step, vel_t^i \pm \delta), \max(1.4 m/step, vel_t^i \pm \delta)$. Note that the periodicity of the CAM message is $100ms$ which leads to the variation of the velocity between $28.8kmph - 50.4kmph$ and every 2.5 seconds it either increase or decrease $3.6kmph$. The result in Figure \ref{fig:random_toy} shows that the algorithm can not reach the optimal policy but vehicles can still learn a sub-optimal policy(2 vehicles use separate resources, 2 same resources). However, the results can be improved further by integrating velocity as a part of the state feature $v_t^i \in s_t^i$. We leave this case as a part of the future work. \subsection{Impact of LSTM layer} We also analyzed the impact of the LSTM input layer on learning performance. Hence, the first LSTM layer is replaced by feedforward neural networks(FNN) as vanilla DQN. Scenario 6 i.e. 20 vehicles, 20 resources is exploited for comparing the performance of these two settings. The results in Figure \ref{fig:dqnvsdrqn} show that LSTM input layer enables learning whereas vanilla DQN with FNN as first later is now able to learn at all. LSTM layer captures the previous $m$ observations e.g. in our case $m=6$ instead of learning only from the last observation. \subsection{Granularity of observations} The performance of the proposed approach under different granularity i.e. $B$ differs is also examined. We observed that the optimal bin size $B$ is correlated with the number of vehicles in a scenario. Training performance of toy example and scenario 6 under various $B$ value is depicted in Figure \ref{fig:train_per_bin}. In general, the variance of the learning curve diminishes with increasing granularity. \begin{figure*} \begin{subfigure}{.49\textwidth} \centering \includegraphics[width=0.8\linewidth]{infocom2021_TVT/figures/results/paper_random_velocity_toy_example_b20.pdf} \caption{Toy example under random velocity} \label{fig:random_toy} \end{subfigure} \begin{subfigure}{.49\textwidth} \centering \includegraphics[width=0.8\linewidth]{infocom2021_TVT/figures/results/final_20ue_20r_500m_35kmph_dqn_vs_drqn.pdf} \caption{Scenario 6, Vanilla DQN vs DQN with LSTM} \label{fig:dqn_vs_drqn} \end{subfigure} \newline \begin{subfigure}{.49\textwidth} \centering \includegraphics[width=0.8\linewidth]{infocom2021_TVT/figures/results/final_4ue_3r_toy_o_index_bin_sizes.pdf} \caption{Scenario 1} \label{fig:sub-first} \end{subfigure} \begin{subfigure}{.49\textwidth} \centering \includegraphics[width=0.8\linewidth]{infocom2021_TVT/figures/results/final_20ue_20r_500m_35kmph_bin_size.pdf} \caption{Scenario 6} \label{fig:sub-second} \end{subfigure} \caption{Training performance of different scenarios} \label{fig:fig:train_per_further} \end{figure*} \subsection{Networked agents} Our work can also be considered as a part of the networked agents in multi-agent deep reinforcement learning system in which agents exchange messages through a communication channel in order to maximize system objective. Communication in multi-agent reinforcement learning is a new emerging trend for cooperative and competitive settings \cite{DBLP:journals/corr/FoersterAFW16a, DBLP:journals/corr/abs-1802-08757, DBLP:journals/corr/abs-1902-01554}. In our system, each agent shares its neighboring positional table with the other agents to keep updated position information of each vehicle in the system. This positional information is later used to construct state of the agent. Note that, sharing positional information with other agents does not create extra burden on radio resources since we share the messages together with the CAM messages. Also, our work aligns with the latest 5G V2X standards, sharing information with other vehicles to assist their resource selection is also part of the 5G-V2X i.e.mode 2(b) standard \cite{R11809867}. \section{Evaluation} \label{sec:evaluation} We first evaluate the performance of the proposed approach in a light-weighted test simulator for faster analysis of various experiments. Once the proper architecture is determined in the test simulator, it is deployed and tested in the 5G real-time network simulator (RealNeS)\footnote{http://nomor.de/services/simulation/system-level-simulation/} for evaluation of packet reception ratio. We consider a simple channel model in the test simulator such that if there is more than one vehicle that exploits the same resource block within the range of receivers, receivers decode the packets of the closer vehicle. However, the simulation granularity in RealNeS allows us to compute effective SINRs in the equivalent complex baseband (ECB) taking into account, fast and slow fading, precoding and receive filtering techniques. Table~\ref{tab:parameters} summarizes training and network settings. We evaluated the performance of the DIRAL in the scenarios as shown in Table~\ref{tab:scenarios} for different configurations in terms of number of vehicles and available resources. \begin{table}[htbp] \caption{Training and network parameter settings} \begin{center} \resizebox{0.5\textwidth}{!}{ \begin{tabular}{|c|c|c|c|} \hline \multicolumn{2}{|c|}{\textbf{Training}}&\multicolumn{2}{|c|}{\textbf{Network}} \\ \cline{1-4} \textbf{Name} & \textbf{Value}& \textbf{Name}& \textbf{Value} \\ \hline Time-steps & 250000 & Access scheme & OFDMA \\ \hline Experience-replay & 1024 & Carrier frequency & 5.9GHz \\ \hline Step size(for LSTM) & 6 & System bandwidth & 10MHz \\ \hline Batch size(Training) & 512 & Subcarrier spacing & 30kHz \\ \hline Learning rate & 0.0001 & PRBs & 24 \\ \hline Discount factor $\gamma$ & 0.7 & Number of antennas & 4 \\ \hline Hidden layers & 256 neurons & Transmit power & 23.0dBm\\ \hline Optimizer & ADAM & TFC index & 4(QPSK) \\ \hline Activation function & ReLU & CAM message size & 300bytes \\ \hline $\epsilon$-decay & 0.999 & Periodicity & 100ms \\ \hline \end{tabular}} \label{tab:parameters} \end{center} \end{table} \vspace{-0.65cm} \begin{table}[htbp] \caption{Evaluation scenarios} \begin{center} \resizebox{0.5\textwidth}{!}{ \begin{tabular}{|c|c|c|c|c|c|} \hline \textbf{No} & \textbf{Vehicles} & \textbf{Resources} & \textbf{Highway} & \textbf{Velocity(kmph)} & \textbf{Mobility} \\ \hline 1 & 4 & 3 & 100m & \{18,36,45,54\} & Wrap-around \\ \hline 2 & 6 & 5 & 250m & $\sim$35 & SUMO$^{\mathrm{1}}$ \\ \hline 3 & 8 & 10 & 500m & $\sim$35 & SUMO \\ \hline 4 & 10 & 10 & 500m & $\sim$35 & SUMO \\ \hline 5 & 12 & 10 & 500m & $\sim$35 & SUMO \\ \hline \multicolumn{4}{l}{$^{\mathrm{1}}$https://sumo.dlr.de/docs/.} \vspace{-0.5cm} \end{tabular}} \label{tab:scenarios} \end{center} \end{table} \vspace{-0.2cm} \subsection{Training Performance} We started the evaluations with a toy example as depicted in Figure~\ref{fig:exp_dist}, where we have $N=4$ vehicles and $K=3$ resources at each time-step. The parameter to adjust the granularity of observations i.e. $B$ is set to $40$ in this toy example and $R$ value is selected proportional to the length of the highway e.g. $R=100$. Each vehicle moves in the same direction with a unique velocity. We used the reward function in Equation \ref{eq:reward_design} with a slight modification for the scenarios $1$ and $2$. We gave neutral reward for the farthest vehicles that use the same resources to observe the desired behavior better. So, at each time-step the maximum reward of the system is 2 for the scenario $1$. The length of the each episode is 25 time-steps and we trained the model after each episode. The convergence of this approach is illustrated in Figure \ref{fig:sub-firstt}. The proposed approach reaches the optimal policy for the considered scenario. We increased the granularity of observations to $B=100$ for large scenarios e.g. $3$, $4$, and $5$ to capture the mobility pattern of all the vehicles. Although higher $B$ increases the state space, DQN with LSTM architecture is able to find good estimates of Q-values. The model can differentiate the positions of vehicles better with increasing granularity of observations. We use the reward in Equation \ref{eq:reward_design} with $r_{reuse}=250m$ to motivate far vehicles to use the same resources. Note that, the proposed reward works also with large number of vehicles. As seen in \ref{fig:sub-third}, DIRAL is able to evolve more smoothly. This is mainly caused by the fact that we have a relatively simpler mobility model for the scenario $4$. We mainly aimed at proving convergence with the test simulator and due to space limitations we do not share all the training performances. \begin{figure} \centering \begin{subfigure}{.23\textwidth} \centering \includegraphics[width=\linewidth]{figures/results/last4_rewards_config_toy_4ue_3r_tests_db_r2_b40_mg_o_.pdf} \caption{Scenario 1: 4 vehicles, 3 resources} \label{fig:sub-firstt} \end{subfigure} \begin{subfigure}{.23\textwidth} \centering \includegraphics[width=\linewidth]{figures/results/last4_rewards_config_realness_12ue_10r_tests_db_r2_.pdf} \caption{Scenario 4: 12 vehicles, 10 resources} \label{fig:sub-third} \end{subfigure} \vspace{-0.1cm} \caption{Training performance of congested scenarios} \vspace{-0.5cm} \label{fig:train_per} \end{figure} \subsection{RealNeS Analysis} The trained policies for the scenarios $2$, $3$, $4$, and $5$ in the test simulator are deployed to real time network simulator, and the performance of DIRAL is compared with random scheduling and SPS. SPS algorithm consists of \textit{sensing}, \textit{selection}, and \textit{reselection}. With \textit{sensing}, each vehicle monitors Received Signal Strength Indicator (RSSI) of shared resources for the last 1000 slots. For \textit{selection}, resources with expected RSSI lower than a threshold form a resource pool and a resource is selected randomly from the shared pool. If the size of the resource pool is smaller than 20\% of all shared resources, then the threshold is increased by 3dB, and the \textit{selection} procedure is repeated. After the \textit{selection} process, a vehicle exploits the same resource for the subsequent $\sim[5, 15]$ transmissions that is set by the reselection counter. The reselection counter is decreased by one after every transmission and when it reaches zero, the vehicle continues to use the same resource with the probability of 0.8 or selects a new resource. In random scheduling, each vehicle randomly selects one resource among the shared resources in every transmission. We compare the performance of DIRAL for both congested and non-congested case. The measurements for evaluation are taken every 100 transmissions over 1000 seconds. The PRR values are illustrated with boxplots in Figure \ref{fig:10r_conf} for scenarios $3$, $4$ and $5$. This indicates that for a congested scenario DIRAL outperforms both SPS and random scheduling in terms of PRR. SPS algorithm is able to perform as well as DIRAL only when the number of resources higher than the number of vehicles. PRR as a function of the distance between transmitter and receiver is depicted in Figure~\ref{fig:sub-third_prr} for scenario 2. The system achieves very high PRR values for near vehicles compared to SPS and random while sacrificing communication with far vehicles by exploiting the same resources. \begin{figure} \centering \begin{subfigure}{.49\textwidth} \includegraphics[width=1.1\linewidth]{figures/results/last_prr_all_v6.pdf} \caption{PRR of various vehicles with 10 resources.} \label{fig:10r_conf} \end{subfigure} \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=\linewidth]{figures/results/last4_6ue_5r_250m_35kmph_prr_v3.pdf} \caption{Scenario 2} \label{fig:sub-third_prr} \end{subfigure} \caption{RealNeS analysis} \label{fig:eval_per} \end{figure}% \section{Introduction} Vehicle-to-vehicle (V2V) Communication is a vital technology for automotive industry to reduce the accident risk and to provide safer driving experience. Vehicles periodically broadcast Cooperative Awareness Messages (CAMs) which contain the position, velocity, direction of the vehicles along with emergency vehicle and collision risk warnings~\cite{Communications2018}. The 3rd Generation Partnership Project (3GPP) has standardized the message exchange among the vehicles (V2V), and among vehicles and pedestrian (V2P), infrastructure (V2I) and network (V2N) in release~14 \cite{3gpp:36.300}, known as Long-Term-Evolution Vehicle-to-Everything (LTE-V2X). Within 3GPP, the evolution of V2X communication is continuing in the scope of New Radio (NR), a technology for the 5th generation of cellular networks. The allocation of V2V resources in cellular, i.e., time and frequency can be either controlled by the cellular network structure or performed autonomously by the individual vehicles. Since the existence of base stations cannot always be guaranteed, distributed resource allocation (DRA) methods are required. 3GPP has standardized a DRA method that relies on UEs to independently perform sensing and resource selection based on the principle of semi-persistent scheduling (SPS). Based on these two principles vehicles in mutual vicinity are likely to choose the same resources and interfere with each other for a number of subsequent transmissions~\cite{nomor_sps}, resulting in repeated undecoded CAMs sent by these vehicles. Especially, for congested scenarios, it becomes more challenging for the SPS algorithm. Our goal is to overcome the drawback of the SPS approach by deriving a DRA that builds on principles otherwise used by centralized resource allocation methodology, namely knowledge of the spatial distribution of vehicles. Achieving the globally optimal solution in DRA is a combinatorial optimization problem and mathematically intractable as the network size increases~\cite{4155374}. Therefore, as a strong heuristic, we adopt the multi-agent deep reinforcement learning (MADRL) approach, i.e., each vehicle is a learning unit. MADRL has been recently exploited in various modern network problems such as power allocation; IoT, UAV, and V2X for spectrum access, data rate selection, transmit power control, etc., c.f. \cite{Nasir,8807386,DBLP:journals/corr/abs-1905-02910}. In~\cite{DBLP:journals/corr/abs-1905-02910}, the authors propose MADRL to maximize the delivery rate of V2V messages for in-coverage scenario. They train multiple independent deep Q-networks (DQN) for each V2V link. As the increase in number of vehicles increases the number of V2V links combinatorically, this method does not scale computationally \cite{Gupta}. We group V2V decisions of each vehicle as a single decision for each vehicle overcoming this scaling problem. Furthermore, we train only one model which is shared by the vehicles such that the vehicles can also learn from the experiences of the other vehicles. \section{Multi-agent DRL Algorithm} \label{sec:model} In this section we describe the solution we propose to the problem~\eqref{eq:ma_reward} that is the DIstributed Resource Allocation with multi-agent deep reinforcement Learning (DIRAL) algorithm. The novelty of this paper lies in the unique state representation to tackle the \textit{non-stationarity} in multi-agent learning system to perform distributed resource allocation. Each vehicle observes the positions of the other vehicles on the road from its own perspective and creates view-based positional distribution vector as shown in Figure \ref{fig:exp_dist} for vehicle A and C. In this work, \textit{field-of-view common knowledge} \cite{DeWitt2018} arises through view-based positional distribution based observations since vehicles can deduce the observation of other vehicles from their own observation. For example, in Figure \ref{fig:exp_dist}, vehicle A can infer the observation of C from its own observations so that it can allocate a reasonable resource for transmission of CAM by anticipating the resource selection of vehicle C. Cooperative nature of the objective i.e. vehicles need to cooperate for resource allocation to maximize the equation~\eqref{eq:ma_reward}, and centralized training enables vehicles to develop fully decentralized policies under common knowledge \cite{DeWitt2018}. Figure \ref{fig:diral} depicts the general structure of DIRAL. We focus on centralized training, decentralized execution framework which is commonly used in many MADRL system \cite{Naparstek2017}. In the centralized training part, we can access the actions of the vehicles to determine the reward for each agent. Once the training part is done, agents exploit the trained policy to take a decision based on only their local observations. Centralized training also facilitates \textit{parameter sharing} approach, such that the parameters of DQN are shared with all the agents. Note that, our current settings allow sharing parameters since agents are homogeneous \cite{Gupta}, i.e. share the same reward utility, state and action space. \textit{Parameter sharing} reduces the number of parameters that must be trained significantly thus training is computationally favourable and scalable. We deploy further improvements in order to stabilize the learning and improve the policy. Thus, we adopt double DQN, an enhanced version of DQN with target and evaluation networks to solve the overestimation problem of DQN \cite{DBLP:journals/corr/HasseltGS15}. Evaluation network is used both for action selection and policy evaluation. Target network is exploited to calculate the Q values of the next action i.e. $a\prime$ for computing the loss and is updated with the parameters of evaluation networks periodically. Furthermore, we store the experiences of each agent i.e. $e_t^i = (s_t^i, a_t^i, r_t^i, s_{t+1}^i)$ in the experience replay memory to be exploited for training as depicted in Fig. \ref{fig:diral}. The correlations among experiences can be removed via sampling randomly from the replay memory $(s, a, r, s') \sim U(D)$ during training and the changes in the data distribution smoothing over \cite{mnih2015humanlevel}. We shortened the size of the experience replay and keep a FIFO buffer with a size proportional to the number of agents to avoid non-stationarity introduced in training with large experience replay buffer \cite{leibo2017multiagent}. As a part of the deep neural network architecture of DQN, we use long-term short memory (LSTM) networks as a first layer to predict the mobility pattern of the vehicles based on positional distribution. LSTM layer sustains an internal state and combines the observations over time. We approximate $Q(s_t, a_t, h_{t-1}; \theta)$ with recurrent neural networks where $h_{t-1}$ is the hidden state of the agent at the previous step. The hidden state $h_t = LSTM(s_t, h_{t-1}) = LSTM(s_{t-(L-1)},...,o_t)$ with $L$ as the number of observations. LSTM network is followed by a fully connected feed-forward network layer to compute the values of each action. Note that, although we train only one DQN, the agents still act dissimilar, because each agent evolves its own hidden state due to different observations which enable agents to behave distinctly although they share the same DQN \cite{DBLP:journals/corr/FoersterAFW16a}. \begin{figure} \centering \includegraphics[width=\textwidth/2]{figures/diral_arc.pdf} \caption{Illustration of DIRAL.} \label{fig:diral} \end{figure} \subsection{State and Action Space} The state vector $s_t^i$ at time $t$ for the vehicle $i$ is composed of the previous action that agent $i$ took $a_{t-1}^i$ and the vector represents the positional distribution of other vehicles from the perspective of the vehicle $v_t^i$, that is the output of function $f(p_t^i, B, R)$. View-based positional distribution (VPD) function $f(p_t^i, B, R)$ exploits the positions of the other vehicles from the neighbor table $p_t^i$ of the agent $i$ at the time $t$, an integer $B \in \mathbb{Z}^+ $ which determines the granularity of the view-based observation vector and an integer $R \in \mathbb{Z}^+ $ which indicates the observation radius of the agent $i$. The Figure \ref{fig:exp_dist} illustrates the positional distribution of the vehicles $p_t^i$ at the top and the related output of $f(p_t^i, B, R)$ for vehicles A and C at the bottom. The parameters are set as $B=10$ and $R=100m$. The effect of setting these parameters is discussed in Sec.~\eqref{sec:evaluation} with the convergence versus complexity trade-off. The current neighboring table is piggybacked to the CAM messages as such every vehicle shares their position information. In this work, the agent uses all the available frequency chunks with transmissions so that 1 slot and 1 subchannel represent one resource block. The action space becomes $\mathcal{A}:= \{a | a = k,\,\, k\in \mathcal{K}\}$. \subsection{Reward Design} We consider the performance of the proposed approach both in congestion and non-congestion case. In particular, we encourage each vehicle to select a different resource but for congestion case we motivate far vehicles to use the same resource. The reward of each agent is calculated as follows; \begin{equation}\label{eq:reward_design} r_t^i(a_t^i|s_t^i) = \begin{cases} 1, & N_t^c = 1 \\ \begin{rcases} 0 & \text{if $dist(\pmb{c}) > r_{reuse}$} \\ -N_t^c & \text{else,} \\ \end{rcases} & \text{$N_t^c = 2$} \\ -N_t^c , & N_t^c > 2 \end{cases} \end{equation} where the vector $\pmb{c} $ is the interfering agents at the same resource i.e. $\pmb{c} = [i, k,...,l]$ with $\pmb{c} \subset N$ and $N_t^c = |\pmb{c}| $ is the total number of collided vehicles. The average of the sum rewards at the time $t$ is added to the reward of the individual vehicles to intensify cooperative behaviour $ r_t^i(a_t^i|s_t^i) = r_t^i(a_t^i|s_t^i) + \frac{\sum_{j=1}^{N}r_t^j(a_t^j|s_t^j)}{N}$. Note that, we do not need additional feedback channels to inform whether a transmitted packet is successfully decoded or not to compute the reward. We train the model based on only the positional distribution and resource allocation of the vehicles. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{figures/example_dist_v2.pdf} \caption{Example of the output of $f(p_t^i, B, R)$ with $B=10$ and $R=100m$} \label{fig:exp_dist} \end{figure} \section{Scenario} \label{sec:network_model} \subsection{System Model} We consider a wireless vehicle communication network consisting of a set of vehicles $ \mathcal{N} = \{1, 2, ..., N\}$. Vehicles are mobile along a road and their distance to each vehicle is changing dynamically. None of the vehicles are connected to a base-station. Each vehicle has a half-duplex radio, thus only when they are not transmitting, they can receive. For transmission, vehicles autonomously select a resource from a set of available resources $ \mathcal{K} = \{1, 2, ..., K\}$. For simplification of our system model and to avoid in-band emission (IBE) caused by the simultaneous transmission on adjoining frequencies which degrades system performance in V2X \cite{Bazzi2019}, resources are separated only over time into slots. We consider a time-slotted system in which all vehicles are scheduled simultaneously at the time $t$ for the allocation of resources in $\mathcal{K}$. In this work, we strive to maintain high reliability of periodic broadcast V2V messages i.e. CAMs, in other words, each vehicle is trying to maximize the number of neighbors that decodes its packet. Thus, we use a reliability metric, the packet reception ratio (PRR) from 3GPP \cite{3gpp:36.885} as a key performance indicator. PRR is defined as the ratio of the successful receptions among the total number of neighbors $N_t^i$ of the transmitter vehicle $i$ at time $t$. Whether a vehicle has successfully received a CAM at a resource depends on if the vehicles in vicinity have selected that resource for transmission. Thus, the selection of resources can be used to model PRR. Each vehicle $i \in \mathcal{N}$ selects an action $a_t^i = k$ which indicates selection of the resource $k\in \mathcal{K}$ at time $t$. The actions selected by all the vehicles at time $t$ is $ \mathbf{a_t} = (a_t^1, a_t^2, ..., a_t^N)$. For the statement of the problem and the design of the reward we assume a simplified channel model that only reflects path loss, but neglects fast and slow fading. Interference modeling is limited to transmissions from other vehicles. Note that, if more than one vehicle transmit at the same resource, a receiver only selects the one with the highest SINR for decoding. Based on this, each vehicle $i$ calculates $\text{PRR}_t^i(\mathbf{a_t})$ as the ratio of the neighbors that correctly decoded its packet at time $t$ given the actions of all vehicles $\mathbf{a_t}$, at time $t$: \vspace{-0.1cm} \begin{equation} \begin{split} \text{PRR}_t^i(\mathbf{a_t}) = \frac{1}{N_t^i} \sum_{j=1}^{N_t^i} 1 \{ P_{err}(\gamma_t^{i,j})\leq X \sim U([0,1])\}, \end{split} \vspace{-0.7cm} \end{equation} \vspace{-0.1cm} where $N_t^i$ denotes the number of the vehicles neighbors of the vehicle $i$ at the time $t$, and $\gamma_t^{i,j}$ is the signal-to-interference-plus-noise ratio (SINR) at vehicle $j \in \mathcal{N}_t^i=\{1,\cdots,{N}_t^i \}$ of the packet of vehicle $i$, \vspace{-0.2cm} \begin{align} \gamma_t^{i,j} = \frac{P {\lvert H_t^{i,j}\rvert}^2}{\sigma^2 + \sum_{k \in N_t^c(\mathbf{a_t})\setminus \{ i \}} P {\lvert H_t^{k,j} \lvert}^2}. \nonumber \vspace{-0.3cm} \end{align} $P_{err}(\gamma_t^{i,j})$ function calculates the block error rate for the given SINR based on the fixed modulation and coding scheme(MCS). If $P_{err}(\gamma_t^{i,j})$ equal or less than a random number between $0$ and $1$, the packet will be decoded successfully $P$ is the transmit power that is fixed for all vehicles, $\sigma^2$ is the power of additive white Gaussian noise, $\mathcal{N}_t^c(\mathbf{a_t})$ is the set of interfering packets determined by the actions at the time $t$, $H_t^{i,j}$ and $H_t^{k,j}$ are the channel gain between the transmitter $i$ and receiver $j$ and between the transmitter $k$ and receiver $j$ respectively. \subsection{Problem Definition} Vehicles aim to maximize the number of neighbours that receive their CAM messages measured by $\text{PRR}$. Given the definition of $\text{PRR}$, we formulate an optimization problem to select the policy $\pi$ that sets the actions of the vehicles $\mathbf{a_t^\pi}$ and maximize the $\text{PRR}$, \begin{maxi}|1| {\mathbf{\pi}}{\sum_{i=1}^{N} \text{PRR}_t^i(\mathbf{a_t^\pi})} {}{} \addConstraint{a_t^i \in \{1, 2, ..., K\}.} \label{eq:prr_sum} \end{maxi} For the non-congested case, i.e., $N \leq K $, \eqref{eq:prr_sum} can be satisfied easily if all the vehicles choose separate resources, i.e, $a_t^i~\neq~a_t^l \,\,\forall \,\,i,l \,\,\text{with}$ $i\neq l$. However, with the congestion case, i.e., $N > K$, a policy has to be used to dynamically adjust the actions as the vehicle channel gains and the number of neighbors vary due to the mobility of vehicles. The policy that would maximize the average PRR for all vehicles is called the optimal policy $\pi^*$. Obtaining the optimal policy $\pi^*$ is challenging for distributed scenario as there is no central scheduler that takes into account the channel gains and locations of each vehicle with respect to each other. In centralized solution, the base station coordinates transmission of vehicles, adopts spatial reuse of resources to maintain reliable communications, i.e. high PRR. Specifically, base station allocates the same resources to the vehicles if the distance between them is higher than a minimum reuse distance $r_{reuse}$ \cite{8275637}. However, we consider the case where the vehicles are located outside of the coverage of a base station. Thus, each vehicle selects an action based only on local observations autonomously. Due to the dynamic multi-dimensional nature of the problem, we formulate it as a multi-agent deep reinforcement learning problem such that far vehicles ($>r_{reuse}$) are motivated to choose the same resources whereas near vehicles use separate resources. Simply, we investigate the concept of centralized scheduling in a distributed fashion to maximize the overall packet reception ratio. \subsection{Deep Reinforcement Learning Background} Reinforcement learning is a machine learning technique where an algorithm, considered as an agent, learns based on its interactions with the environment. Let $\mathcal{S}$ and $\mathcal{A}$ be the state and action space respectively. In a single-agent, fully-observable, RL setting \cite{Sutton1998}, an agent observes the current state $s_t$ in state space $\mathcal{S}$ at each discrete time step $t$, and chooses an action $a_t$ in action space $\mathcal{A}$ based on a policy $\pi$. Then, it observes a reward signal $r_t$, and transitions to a new state $s_{t+1}$. The goal of the agent is to maximize accumulated discounted reward $G_t:= r_t + \gamma r_{t+1} + \gamma^2 r_{t+2} ... = r_t + \gamma G_{t+1}$, where $\gamma \in [0,1]$ is a discount factor which determines the influence of future rewards on the optimal decisions. A policy $\pi$ defines the behaviour of an agent and is the probability of an action given a state, i.e., $\pi(a|s) = \mathbb{P}[a_t = a | s_t = s] $ with $\sum_{a \in \mathcal{A}}\pi(a|s) = 1$. Then following policy $\pi$, the expected total reward starting from the state $s$, taking action $a$ can be calculated via the action-value function $Q^{\pi}(s,a) = \mathop{\mathbb{E}_{\pi}}[G_t|s_t = s, a_t = a]$. The optimal action-value function, denoted as $Q^{*}(s,a)$ is the maximum action-value function over all policies, i.e. $Q^{*}(s,a) = \max_{\pi} Q^{\pi}(s,a)$. Once the optimal action-value function is obtained, the optimal policy $\pi^{*}(s,a)$ can be extracted by acting greedy at each state i.e. $ \underset{a \in A}{\arg\max}\,\, Q^{*}(s,a)$. One of the most famous algorithm to compute the optimal action-value function is Q-learning \cite{q_learning}, which iteratively approximates the Q-function using the Bellman equation, \vspace{-0.2cm} \begin{equation} \label{eq:q_learning} Q(s,a) = Q(s,a) + \alpha \big[ r + \gamma \max_{a'}Q(s',a') - Q(s,a)\big]. \vspace{-0.2cm} \end{equation} When state and action space is large, deep neural networks (DNN) are used to approximate the Q function. This technique is known as Deep Q Networks (DQN) where the Q-function can be represented as $Q(s,a;\theta)$ where $\theta$ denotes the trainable weights of the network. In order to find $Q(s,a;\theta)$, the least squares loss $L(\theta)$ is defined; \vspace{-0.1cm} \begin{equation} \label{eq:loss} L(\theta) = \big[(r + \gamma \max_{a'} Q(s',a'; \theta)) - Q(s,a; \theta) \big]^2. \vspace{-0.1cm} \end{equation} The gradient descent is applied with respect to $\theta$ in order to minimize the loss in (\ref{eq:loss}). \subsection{Multi-agent DRL Formulation} We consider a multi-agent system where each reinforcement learning agent, vehicle, learn simultaneously which resources to select for its transmission. At each time-step $t$, each agent $i\,\,\in\,\,\mathcal{N}$ observes a state $s_t^i$ locally, selects an action $a_t^i$ from its policy $\pi^i(a_t^i |s_t^i)$ and receives a reward $r_t^i$ from the environment. The sum of discounted rewards for the agent $i$ for episodes of length $H$ is $G_t^i = \sum_{l=0}^{H} \gamma^l r_{t+l}^i$. Each vehicle $i$ aims to find a policy $\pi^i$ to maximize its expected accumulated discounted reward. Note that, the reward of a vehicle $i$ depends not only on the policy $\pi^i$ but also on the policy of the other vehicles. The set of policy of all agents except the agent $i$ is denoted by $\pmb{\pi}^{-i}= \{\pi^{j}\}_{j\neq i}$. We use the shorthand notation $\mathbf{-i}= \mathcal{N} \setminus {i} $ for the set of opponents of agent $i$. Then, the objective of each vehicle $i$ is; \vspace{-0.22cm} \begin{equation} \label{eq:ma_reward} \max_{\pi^i} \mathbb{E}\big[G_t^i (\pi^i, \pmb{\pi}^{-i})\big], \vspace{-0.1cm} \end{equation} where $\mathbb{E}\big[G_t^i (\pi^i, \pmb{\pi}^{-i})\big]$ indicates the expected accumulated reward when the agent $i$ follows the policy $\pi^i$ and the opponents perform $\pmb{\pi}^{-i}$. In short, the agents need to learn a cooperative behaviour in a distributed fashion in order to maximize their objective. Solving \eqref{eq:ma_reward} is challenging since multiple agents learn concurrently makes the environment \textit{non-stationary} from the perspective of each agent and breaks the stationarity assumption which is required for convergence of single-agent DRL algorithms \cite{zhang2019multiagent}. One way to deal with \textit{non-stationary} behaviour in multi-agent systems is to anticipate the actions of the other agents through recursive reasoning \cite{hern2017survey}. A particular case where the agents possess knowledge after infinitive reasoning steps is known as \textit{common knowledge} \cite{10.2307/2958591}. An event, say $\mathrm{e}$, is common knowledge "if and only if everyone knows $\mathrm{e}$, and everyone knows that everyone knows $\mathrm{e}$, and everyone knows that everyone knows that everyone knows $\mathrm{e}$, and so on \textit{ad infinitum}" \cite{Gmytrasiewicz}.
{'timestamp': '2020-10-13T02:24:02', 'yymm': '2010', 'arxiv_id': '2010.05290', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05290'}
arxiv
\section{Introduction} \blfootnote{ % % % % \hspace{-0.65cm} This work is licensed under a Creative Commons Attribution 4.0 International Licence. Licence details: \url{http://creativecommons.org/licenses/by/4.0/}. % } Translation into languages with grammatical gender involves correctly inferring the grammatical gender of all entities in a sentence. In some languages this grammatical gender is dependent on the social gender of human referents. For example, in the Spanish translation of the sentence `This is the doctor', `the doctor' would be either `el médico', masculine, or `la médica', feminine. Since the noun refers to a person the grammatical gender inflection should be correct for a given referent. In practice many NMT models struggle at generating such inflections correctly \cite{sun-etal-2019-mitigating}, often instead defaulting to gender-based social stereotypes \cite{prates2019assessing} or masculine language \cite{hovy-etal-2020-sound}. For example, an NMT model might always translate `This is the doctor' into a sentence with a masculine inflected noun: `Este es el médico'. Such behaviour can be viewed as translations exhibiting gender bias. By `bias' we follow the definition from \newcite{friedmanbias1996} of behaviour which `systematically and unfairly discriminate[s] against certain individuals or groups of individuals in favor of others.' Specifically, translation performance favors referents fitting into groups corresponding to social stereotypes, such as male doctors. Such systems propagate the representational harm of erasure to referents -- for example, a non-male doctor would be incorrectly gendered by the above example translation. Systems may also cause allocational harms if the incorrect translations are used as inputs to other systems \cite{crawford2017trouble}. System users also experience representational harms via the reinforcement of stereotypes associating occupations with a particular gender \cite{abbasi2019fairness}. Even if they are not the referent, the user may not wish for their words to be translated in such a way that they appear to endorse social stereotypes. Users will also experience a lower quality of service in receiving grammatically incorrect translations. A common approach to this broad problem in NMT is the use of gender features, implicit or explicit. The gender of one or more words in a test sentence is determined from external context \cite{vanmassenhove-etal-2018-getting,basta-etal-2020-towards} or by reliance on `gender signals' from words in the source sentence such as gendered pronouns. That information can then be used when translating. Such approaches combine two distinct tasks: identifying the gender inflection feature, and then applying it to translate words in the source sentence. These feature-based approaches make the unstated assumption that if we \emph{could} correctly identify that, e.g., the doctor in the above example should be female, we could inflect entities in the sentence correctly, reducing the effect of gender bias. Our contribution is an exploration of this assumption. We propose a scheme for incorporating an explicit gender inflection tag into NMT, particularly for translating coreference sentences \emph{where the reference gender label is known}. Experimenting with translation from English to Spanish and English to German, we find that simple existing approaches overgeneralize from a gender signal, incorrectly using the same inflection for every entity in the sentence. We show that a tagged-coreference adaptation approach is effective for combatting this behaviour. Although we only work with English source sentences to extend prior work, we note that our approach can be extended to source languages without inherent gender signals like gendered pronouns, unlike approaches that rely on those signals. Intuitively, if gender tagging does not perform well when it can use the label determined by human coreference resolution, it will be even less useful when a gender label must be automatically inferred. Conversely, gender tagging that is effective in this scenario may be beneficial when the user can specify the gendered language to use for the referent, such as Google Translate's translation inflection selection \cite{johnson2018providing}, or for translations where the grammatical gender to use for all human referents is known. We also find that our approach works well with RoBERTa-based gender tagging for English test sentences. Existing work in NMT gender bias has focused on the translation of sentences based on binary gender signals, such as exclusively male or female personal pronouns. This excludes and erases those who do not use binary gendered language, including but not limited to non-binary individuals \cite{zimman2017transgender,cao-daume-iii-2020-toward}. As part of this work we therefore explore applying tagging to indicate gender-neutral referents, and produce a WinoMT set to assess translation of coreference sentences with gender-neutral entities. \subsection{Related work} Variations on a gender tag or signal for machine translation have been proposed in several forms. \newcite{vanmassenhove-etal-2018-getting} incorporate a `speaker gender' tag into training data, allowing gender to be conveyed at the sentence level. However, this does not allow more fine-grained control, for example if there is more than one referent in a sentence. Similar approaches from \newcite{voita-etal-2018-context} and \newcite{basta-etal-2020-towards} infer and use gender information from discourse context. \newcite{moryossef-etal-2019-filling} also incorporate a single explicit gender feature for each sentence at inference. \newcite{miculicich-werlen-popescu-belis-2017-using} integrate coreference links into machine translation reranking to improve pronoun translation with cross-sentence context. \newcite{stanovsky-etal-2019-evaluating} propose NMT gender bias reduction by `mixing signals' with the addition of pro-stereotypical adjectives. Also related to our work is the very recent approach of \newcite{bergmanis2020mitigating}, who train their NMT models from scratch with all source language words annotated with target language grammatical gender. In \newcite{saunders-byrne-2020-reducing} we treat gender bias as a domain adaptation problem by adapting to a small set of synthetic sentences with equal numbers of entities using masculine and feminine inflections. We also interpret this as a gender `tagging' approach, since the gendered terms in the synthetic dataset give a strong signal to the model. In this work we extend the synthetic datasets from this work to explore this effect further. Other approaches to reducing gender bias effects involve adjusting the word embeddings either directly \cite{escude-font-costa-jussa-2019-equalizing} or by training with counterfactual data augmentation \cite{zhao-etal-2018-gender,zmigrod-etal-2019-counterfactual}. We view these approaches as orthogonal to our proposed scheme: they have similar goals but do not directly control inference-time gender inflection at the word or sentence level. \section{Assessing and controlling gender inflection} We wish to investigate whether a system can translate into inflected languages correctly correctly given the reference gender label of a certain word. Our proposed approach involves fine-tuning a model on a very small, easily-constructed synthetic set of sentences which have gender tags. At test time we assign the reference gender label to the words whose gender inflection we wish to control. \subsection{Gender bias assessment} WinoMT \cite{stanovsky-etal-2019-evaluating} is a test set for assessing the presence of gender bias in translation from English to several gender-inflected languages. Each of 3888 test sentence contains two human entities, one of which is coreferent with a pronoun. 1826 of these sentences have male primary entities, 1822 female and 240 neutral. The first test sentence in WinoMT is: \emph{The developer argued with the designer because she did not like the design.} The gender label for this sentence is `female' and the primary entity label is `the developer'. The same sentence with a gender tag would be: \emph{The developer \texttt{$<$F$>$} argued with the designer because she did not like the design.} We only tag the primary entity in test sentences. During evaluation WinoMT extracts the hypothesis translation for `the developer' by automatic word alignment and assesses its gender inflection in the target language. The main objective is high overall accuracy -- the percentage of correctly inflected primary entities. We note a comment by \newcite{rudinger-etal-2018-gender}, who develop a portion of the English WinoMT source sentences, that such schemas `may demonstrate the presence of gender bias in a system, but not prove its absence.' In fact high WinoMT accuracy can be achieved by using the labeled inflection for \emph{both} entities in a WinoMT test sentence, even though only one is specified by the sentence. We therefore produce\footnote{Our new adaptation and evaluation sets can be found at \url{https://github.com/DCSaunders/tagged-gender-coref}} a test set for the WinoMT framework to track the gender inflection of the secondary entity in each original WinoMT sentence (e.g. `the designer' in the above example). We measure second-entity inflection correspondence with the gender label, which we refer to as \textbf{L2}. High L2 suggests that `the designer' would also have feminine inflection in a translation of the above example, despite not being coreferent with the pronoun. We are particularly interested in cases where L2 increases over a baseline, or high $\mathbf{\Delta}$\textbf{L2}. Many factors may contribute to a baseline system's L2, but we are specifically interested in whether \emph{adding} gender features affects only the words they are intended to affect. High $\Delta$L2 indicates a system learning to over-generalize from available gender features. We consider this as erasing the secondary referents, and therefore as undesirable behaviour. \subsection{Adaptation to gender-feature datasets} \begin{table*}[ht] \centering \small \begin{tabular}{|p{0.7cm}|p{4.3cm}|p{4.2cm}|p{4.5cm}|} \hline \textbf{Name} & \textbf{English source} & \textbf{German target} & \textbf{Spanish target}\\ \hline \multirow{3}{*}{\textbf{S\&B}} & the trainer finished his work& der Trainer beendete seine Arbeit & el entrenador terminó su trabajo \\ &the trainer finished her work& die Trainerin beendete ihre Arbeit & la entrenadora terminó su trabajo \\ & the trainer finished their work & \texttt{DEF} Trainer\texttt{W\_END} beendete \texttt{PRP} Arbeit & \texttt{DEF} entrenador\texttt{W\_END} terminó su trabajo \\ \hline \textbf{V1} & the trainer \texttt{$<$M$>$} finished his work & der Trainer beendete seine Arbeit & el entrenador terminó su trabajo\\ \hline \textbf{V2} & the trainer \texttt{$<$F$>$} finished the work & die Trainerin beendete die Arbeit & la entrenadora terminó el trabajo \\ \hline \textbf{V3} & the trainer \texttt{$<$N$>$} and the choreographer \texttt{$<$M$>$} finished the work & \texttt{DEF} Trainer\texttt{W\_END} und der Choreograf beendeten die Arbeit & \texttt{DEF} entrenador\texttt{W\_END} y el coreógrafo terminaron el trabajo\\ \hline \textbf{V4} & the trainer \texttt{$<$F$>$}, the choreographer \texttt{$<$N$>$} & die Trainerin, \texttt{DEF} Choreograf\texttt{W\_END}& la entrenadora, \texttt{DEF} coreógraf\texttt{W\_END}\\ \hline \end{tabular} \caption{Examples of the tagging schemes explored in this paper. Adjective-based sentences (e.g. `the tall woman finished her work') are never tagged. For neutral target sentences, we define synthetic placeholder articles \texttt{DEF} and noun inflections \texttt{W\_END}, as well as a placeholder possessive pronoun for German \texttt{PRP}} \label{tab:examples} \end{table*} \label{sec:tags} In \newcite{saunders-byrne-2020-reducing} we propose reducing gender bias effects quickly by model adaptation to sets of 388 simple synthetic sentences with equal numbers of male and female entities. A gendered-alternative-lattice rescoring scheme avoids catastrophic forgetting. The sentences follow a template: \begin{center}\textit{The [entity] finished [his$|$her] work.}\end{center} In one set the \emph{entity} is always a profession (e.g. `doctor'). In the other it is either `\emph{[adjective] [man$|$woman]}'(e.g. `tall man') or a profession that does not occur in WinoMT source sentences (e.g. `trainer'.) We use the latter set to minimize the confounding effects of vocabulary memorization. It is possible to extract natural text with gendered entities, for example using GeBioToolkit \cite{costa2020gebiotoolkit}. The synthetic dataset is more suited to our work for two reasons: it has been shown to allow strong accuracy improvements on WinoMT, and it has a predictable format that can easily be augmented with gender tags. We leave the more complicated scenario of extracting and tagging natural adaptation data to future work. As well as the unchanged \textbf{S\&B} synthetic adaptation set, we propose four gender-tagged variations, which we illustrate in Table \ref{tab:examples}. In the first, \textbf{V1}, we add a gender tag following professions only (we do not tag adjective-based sentences since `man' and `woman' are already distinct words in English). For the second, \textbf{V2}, we use the same tagging scheme but note that the possessive pronoun offers a gender signal that may conflate with the tag, so change all examples to `... finished \emph{the} work'. The third, \textbf{V3}, is the same as \textbf{V2} but in each profession-based sentence a second profession-based entity with a different gender inflection tag is added. This is intended to discourage systems from over-generalizing one tag to all sentence entities. In the final scheme, \textbf{V4}, we simplify \textbf{V3} to a minimal, lexicon-like pattern: \begin{center}\textit{The [entity1], the [entity2].}\end{center} Both entities are tagged. We remove all adjective-based sentences, leaving only tagged coreference profession entities for adaptation. This set has the advantage of using simpler language than other sets, making it easier to extend to new target languages. \subsection{Exploring gender-neutral translation} We wish to extend previous machine translation coreference research to the translation of gender-neutral language, which may be used by non-binary individuals or to avoid the social impact of using gendered language \cite{zimman2017transgender,misersky2019grammatical}. Recently \newcite{cao-daume-iii-2020-toward} have encouraged inclusion of non-binary referents in NLP coreference work. Their study focuses heavily on English, which has minimal gender inflection and where gender-neutral language such as singular \emph{they} is in increasingly common use \cite{bradley2019singular}; the authors acknowledge that `some extensions ... to languages with grammatical gender are non-trivial'. In particular, existing NMT gender bias test sets typically analyse behaviour in languages with grammatical gender that corresponds to a referent's gender. Translation into these languages effectively highlights differences in translation between masculine and feminine referents, but these languages also often lack widely-accepted conventions for gender-neutral language \cite{ackerman2019syntactic,hord2016bucking}. In some languages with binary grammatical gender it is possible to avoid gendering referents by using passive or reflexive grammar, but such constructions can themselves invalidate individual identities \cite{auxlandtodes}. We therefore explore a proof-of-concept scheme for translating tagged neutral language into inflected languages by introducing synthetic gender-neutral placeholder articles and noun inflections in the target language. For example, we represent the gender-neutral inflection of `el entrenador' (the trainer) as `\texttt{DEF} entrenador\texttt{W\_END}' A variety of gender-neutral inflections have been proposed for various grammatically gendered languages, such as \emph{e} or \emph{x} Spanish \cite{papadopoulos2019innovaciones} and Portuguese \cite{auxlandtodes} noun inflections instead of masculine \emph{o} and feminine \emph{a}. These language-specific approaches may develop in various forms across social groups and networks, and can shift over time \cite{shroy2016innovations}. Our intent is not to prescribe which should be used, but to explore an approach which in principle could be extended to various real inflection schemes. We construct additional `neutral-augmented' versions of the adaptation sets described in \ref{sec:tags}, adding `\emph{The [adjective] person finished [their$|$the] work}' sentences to the adjective-based sets and sentences like `\emph{The trainer \texttt{$<$N$>$} finished [their$|$the] work}' to the profession-based sets, with synthetic placeholder articles \texttt{DEF} and inflections \texttt{W\_END} on the target side of profession sentences. We give examples for Spanish and German in Table \ref{tab:examples}. We also construct a neutral-label-only version of WinoMT containing the 1826 unique binary templates filled with they/them/their. We report results adapting to the original and neutral-augmented sets separately for ease of comparison with prior work. \section{Experiments} \label{ss:data} We use baseline Transformer models, BPE vocabularies, synthetic datasets and baseline rescoring gendered-alternative lattices from \newcite{saunders-byrne-2020-reducing}\footnote{\url{https://github.com/DCSaunders/gender-debias}} and follow the same adaptation scheme, assessing on English-to-German and English-to-Spanish translation. We define gender tags as unique vocabulary items which only appear in the source sentence. We adapt to synthetic data with minibatches of 256 tokens for 64 training updates, which we found gave good results when fine-tuning on the S\&B datasets. The V3 sets have about 30\% more tokens, the V4 sets about 30\% fewer and the neutral-augmented sets about 50\% more: we adjust the adaptation steps accordingly for these cases. For all results we rescore the baseline system gendered-alternative lattices with the listed model. This constrains the output hypothesis to be a gender-inflected version of the original baseline hypothesis. Lattice rescoring allows minimal degradation in BLEU while letting gender inflections in the hypothesis translation be varied for potentially large WinoMT accuracy increases. For the gender-neutral experiments we add synthetic inflections and articles to the lattices. When assessing automatic test set tagging we use the RoBERTa \cite{liu2019roberta} pronoun disambiguation function tuned on Winograd Schema Challenge data as described in Fairseq documentation\footnote{\url{https://github.com/pytorch/fairseq/tree/master/examples/roberta/wsc}}. We wish to improve coreference without loss of general translation quality, and so assess BLEU on a separate, untagged general test set. For ease of comparison with previous work, we report general translation quality on the test sets from WMT18 (en-de) and WMT13 (en-es), reporting cased BLEU using SacreBLEU\footnote{BLEU+case.mixed+numrefs.1+smooth.exp+tok.13a+v.1.4.8} \cite{post-2018-call}. \subsection{Measured improvements in gender accuracy are often accompanied by over-generalization} Table \ref{tab:mfresults} gives BLEU score and primary-entity accuracy for the original, binary versions of synthetic adaptation sets described in section \ref{sec:tags}. WinoMT test sentences have primary entities tagged with their gender label if the adaptation set had tags, and are unlabeled otherwise. We note that lattice rescoring keeps the general test set score within 0.3 BLEU of the baseline for all adaptation sets, and focus on the variation in WinoMT performance. Primary-entity accuracy increases significantly over the baseline for all adaptation schemes. V3 and V4, which contain coreference examples, are most effective for en-es, while V2, which contains a single entity, is slightly more effective for en-de. This may reflect the difference in baseline quality: the stronger en-de baseline is more likely to have already seen multiple-entity sentences. We also report $\Delta$L2, the change in the secondary entity's label correspondence compared to the baseline. High $\Delta$L2 implies that the model is over-generalizing a gender signal intended for the primary entity to the secondary entity. In other words, the gender signal intended for the primary entity has a very strong influence on the translation of the secondary entity. $\Delta$L2 does indeed increase strongly from the baseline for the S\&B and V1 systems, confirming our suspicion that these models trained on sentences with a single entity simply learn to apply any gender feature to both entities in the test sentences indiscriminately. Remarkably, for adaptation to S\&B and V1 datasets we found that the secondary entity is inflected to correspond with the pronoun more often than the primary entity which is labeled as coreferent with it. A possible explanation is that the secondary entity occurs at the start of the sentence in about two thirds of test sentences, compared to about one third for the primary entity. Adapting to single-entity test sets may encourage the model to simply inflect the first entity in the sentence using the gender signal. For V2, where the source possessive pronoun is removed and the tag is the only gender signal, $\Delta$L2 still increases significantly, although less than for V1. This indicates that even if the only signal is a gender tag applied directly to the correct word, it may be wrongly taken as a signal to inflect other words. The V3 scheme is the most promising, with a 17\% increase in accuracy for en-de and a 30\% increase for en-es corresponding to very small changes in L2, suggesting this model minimizes over-generalization from gender features beyond the tagged word. V4 performs similarly to V3 for en-de but suffers from an L2 increase for en-es. It is possible that a lexicon-style set with tags in every example may cause undesirable over-generalisation. \subsection{Reference labeled, auto-labeled and unlabeled test sentences} \begin{table*} \centering \small \begin{tabular}{|c|c|ccc|ccc|} \hline \textbf{System} & \textbf{Labeled WinoMT} & \multicolumn{3}{c|}{\textbf{en-de}} & \multicolumn{3}{c|}{\textbf{en-es}}\\ \hline & & BLEU & Acc & $\Delta$L2 & BLEU & Acc & $\Delta$L2\\ Baseline & $\times$ & 42.7 & 60.1 & - & 27.8 & 49.6& - \\ S\&B & $\times$ & 42.4 & 82.3 & 27.4 & 27.7 & 66.3 & 29.7 \\ V1 & \checkmark & 42.5 &81.7 & 26.6 & 27.7 &69.0 & 26.4\\ V2 & \checkmark& 42.5 &\textbf{84.1} & 24.2 & 27.5 & 70.9 & 13.2 \\ V3 & \checkmark & 42.6 & 77.4 & \textbf{1.1}& 27.5 & 80.6 & \textbf{0.3} \\ V4 & \checkmark & 42.6 & 80.6 & 2.0 & 27.6& \textbf{83.1} & 8.7\\ \hline \end{tabular} \caption{Test BLEU, WinoMT primary-entity accuracy (Acc), and change in second-entity label correspondence $\Delta$L2. We adapt the baseline to a set without tags (S\&B), or to one of the binary gender-inflection tagging schemes (V1-V4). `Labeled WinoMT' indicates whether WinoMT primary entities are tagged with their reference gender label. All results are for rescoring the baseline system gendered-alternative lattices with the listed model.} \label{tab:mfresults} \end{table*} \begin{table*} \centering \small \begin{tabular}{|c|cc|cc|cc|cc|cc|cc|} \hline \textbf{System} & \multicolumn{6}{c|}{\textbf{en-de}} & \multicolumn{6}{c|}{\textbf{en-es}}\\ & \multicolumn{2}{c}{Unlabeled} & \multicolumn{2}{c}{Auto-labeled} & \multicolumn{2}{c|}{Reference labeled} & \multicolumn{2}{c}{Unlabeled} & \multicolumn{2}{c}{Auto-labeled} & \multicolumn{2}{c|}{Reference labeled}\\ \hline & Acc & $\Delta$L2& Acc & $\Delta$L2& Acc & $\Delta$L2 & Acc & $\Delta$L2 & Acc & $\Delta$L2& Acc & $\Delta$L2\\ Baseline & 60.1 & - & -& - & - & -& 49.6 & - &-&- & - & -\\ S\&B & \textbf{82.3} & 27.4 &- &-& -& -& 66.3 & 29.7 & -& -& -& -\\ V1 & 81.5 & 26.6& 81.7& 26.5& 81.7 &26.6 & \textbf{67.3} & 29.6 & 68.5 & 31.2 &69.0 & 26.4\\ V2 & 71.2 &9.2 & \textbf{83.6} &24.8 & \textbf{84.1}& 24.2 & 52.1 & 3.5& 69.7 & 18.4& 70.9 & 13.2 \\ V3 & 57.5 & -5.8 &79.9 &\textbf{3.7} & 77.4& \textbf{1.1} & 47.9 & -2.5 & 77.7 & 6.4& 80.6 & \textbf{0.3} \\ V4 & 60.5&\textbf{-2.0} & 79.2 & 4.6 & 80.6 & 2.0 &48.5 & \textbf{-0.6} &\textbf{80.6} &12.6 & \textbf{83.1} &8.7 \\ \hline \end{tabular} \caption{WinoMT accuracy and change in second-entity label correspondence for the adaptation schemes in Table \ref{tab:mfresults} when changing how tags are determined for \textbf{WinoMT source sentences}. The primary entity's gender label in each test sentence is either unlabeled, auto-labeled with RoBERTa, or labeled with the reference gender.} \label{tab:secondaryresults} \end{table*} Table \ref{tab:secondaryresults} lists accuracy and $\Delta$L2 with and without WinoMT source sentence labeling for the same systems as Table \ref{tab:mfresults}. We also experiment with labeling WinoMT sentences automatically, using RoBERTa to predict the antecedent of the single pronoun in each test sentence -- we note this would not necessarily be as effective in sentences with multiple pronouns. V1 gives similar performance to S\&B with and without WinoMT labeling. Removing the possessive pronoun as in V2 decreases accuracy compared to V1 without labeling and slightly increases it with labeling, suggesting removing the source pronoun forces the model to rely on the gender tag. Accuracy under V2, V3 and V4 improves dramatically when gender labels are added to WinoMT primary entities. Without labels the accuracies for these systems improve far less or not at all. This is unsurprising, since in these datasets the gender tag is the only way to infer the correct target inflection. Nevertheless some accuracy improvement is still possible for V2 with neither tags nor possessive pronouns, possibly because the model `sees' more examples of profession constructions in the target language. Without test set labels, the V3 and V4 systems have negative $\Delta$L2, implying that the second entity's inflection corresponds to the primary entity label less often than for the baseline. This is not necessarily bad, as they are still low absolute values. Small absolute $\Delta$L2 indicates that added primary-entity gender signals have little impact on the secondary entity relative to the baseline, which is the desired behaviour. Small negative values are therefore better than large positive values. Auto-labeling WinoMT source sentences performs only slightly worse than using reference labels. We find that the automatic tags agree with human tags for 84\% of WinoMT sentences, with no difference in performance between masculine- and feminine-labeled sentences, or pro- and anti-stereotypical sentences. This is encouraging, and suggests that the tagged inflection approach may also be applicable to natural text, for which manual labeling is often impractical. \subsection{Gender-neutral translation} \begin{table*} \centering \small \begin{tabular}{|c|c|cc|cc|} \hline \textbf{System} & \textbf{Labeled WinoMT} & \multicolumn{2}{c|}{\textbf{en-de}} & \multicolumn{2}{c|}{\textbf{en-es}}\\ \hline & & Acc & $\Delta$L2 & Acc & $\Delta$L2 \\ Baseline &$\times$ & 2.7 & - & 4.2 & -\\ S\&B & $\times$& 13.5& 28.8 &6.4 & 3.9 \\ V1 & \checkmark & \textbf{27.3}& 28.2 & 25.4 & 25.1 \\ V2 & \checkmark & 23.0& 39.6 & 32.1 & 27.5\\ V3 & \checkmark & 20.2& 18.7 & 38.8 & 10.0\\ V4 & \checkmark & 19.4 & \textbf{4.4} & \textbf{56.5} & \textbf{0.7}\\ \hline \end{tabular} \caption{Primary-entity accuracy and second-entity label correspondence $\Delta$L2 on a neutral-label-only WinoMT version. Adaptations sets and lattices are augmented with synthetic neutral articles and nouns. `Labeled WinoMT' indicates whether sentences are tagged with their reference (neutral) gender label.} \label{tab:neutral} \end{table*} In Table \ref{tab:neutral} we report on systems adapted to the neutral-augmented synthetic sets, evaluated on the neutral-only WinoMT set. We use test labeling for all cases where models are trained with tags -- as with the binary experiments we found that performance was otherwise poor. Unsurprisingly, the baseline model is unable to generate the newly defined gender-neutral articles or noun inflections -- the non-zero accuracy is a result of existing WinoMT sentences with neutral entities like `someone'. Adapting on the neutral-augmented S\&B set does little better for en-es, although it gives a larger gain for en-de. This discrepancy may be because the only neutral gender signal in the S\&B source sentences is from the possessive pronoun \emph{their}. In Spanish, which has one gender-neutral third-person singular possessive pronoun, \emph{their} has the same Spanish translation as \emph{his} or \emph{her} and therefore does not constitute a strong gender signal. By contrast in German we add a synthetic singular gender-neutral pronoun, which indicates neutral gender even without tags. This may also explain why V3 and V4 give weaker performance than V1 for German, as these sets no longer contain singular pronouns. Adding a gender tag significantly improves primary entity accuracy. As with Table \ref{tab:mfresults}, there is little difference in labeled-WinoMT performance when the possessive pronoun is removed. Also as previously, the V3 and V4 `tagged coreference' sets shows far less over-generalization in terms of $\Delta$L2 than the other tagged schemes, although V4 significantly outperforms V3 for en-es on this set. We note that primary-entity accuracy is relatively low compared to results for the original WinoMT set, with our best-performing system reaching 56.5\% accuracy. We consider this unsurprising since the model has never encountered most of the neutral-inflected occupation terms before, even during adaptation, due to the lack of overlap between the adaptation and WinoMT test sets. However, it does suggest that more work remains for introducing novel gender inflections for NMT. \section{Conclusions} Tagging words with target language gender inflection is a powerful way to improve accuracy of translated inflections. This could be applied in cases where the correct grammatical gender to use for a given referent is known, or as monolingual coreference resolution tools improve sufficiently to be used for automatic tagging. It also has potential application to new inflections defined for gender-neutral language. However, there is a risk that gender features will be used in an over-general way. Providing a strong gender signal for one entity has the potential to harm users and referents by erasing other entities in the same sentence, unless a model is specifically trained to translate sentences with multiple entities. In particular we find that our V3 system, which is trained on multiple-entity translation examples, allows good performance while minimizing peripheral effects. We conclude by emphasising that work on gender coreference in translation requires care to ensure that the effects of interventions are as intended, as well as testing scenarios that capture the full complexity of the problem, if the work is to have an impact on gender bias. \section*{Acknowledgments} This work was supported by EPSRC grants EP/M508007/1 and EP/N509620/1 and has been performed using resources provided by the Cambridge Tier-2 system operated by the University of Cambridge Research Computing Service\footnote{\url{http://www.hpc.cam.ac.uk}} funded by EPSRC Tier-2 capital grant EP/P020259/1. Work by R. Sallis during a research placement was funded by the Humanities and Social Change International Foundation. \bibliographystyle{coling}
{'timestamp': '2020-12-11T02:19:33', 'yymm': '2010', 'arxiv_id': '2010.05332', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05332'}
arxiv
\section{Introduction} A wide variety of data are represented as graphs, such as road networks~\cite{lammer2006scaling,geng2019spatiotemporal}, citation graphs~\cite{ding2011scientific}, metabolic pathways~\cite{kanehisa2000kegg}, ecosystem~\cite{roberts1978food}, and social networks~\cite{wasserman1994social}. In this paper, we consider node response prediction tasks, where a response value for each node is predicted given an attributed graph. Node response prediction is an important task, which includes congestion prediction with a road network~\cite{li2017diffusion,cui2019traffic}, scientific paper classification with a citation graph~\cite{yang2016revisiting}, and user preference prediction with a social network~\cite{jamali2010matrix,walter2008model}. As the number of nodes with observed responses increases, the performance of node response prediction is improved in general. However, a sufficient number of observed responses are often unavailable since obtaining responses requires high cost, e.g., placing sensors at many roads, and manually labeling by experts with domain knowledge. For improving performance with a small number of observations, many meta-learning methods have been proposed~\cite{schmidhuber:1987:srl,bengio1991learning,ravi2016optimization,andrychowicz2016learning,vinyals2016matching,snell2017prototypical,bartunov2018few,finn2017model,li2017meta,kimbayesian,finn2018probabilistic,rusu2018meta,yao2019hierarchically,edwards2016towards,garnelo2018conditional,kim2019attentive,hewitt2018variational,bornschein2017variational,reed2017few,rezende2016one,tang2019,narwariya2020meta,xie2019meta,lake2019compositional}. Meta-learning is to learn a model that can predict unseen response variables with only a few observed nodes. However, when observed nodes are unbalancedly placed in a graph, e.g., observations are obtained with nodes that are directly connected to each other and no observations are given with other distant nodes, it is difficult to improve the prediction performance even with meta-learning methods. In this paper, we propose an active learning method to select nodes to observe in an attributed graph so that the prediction performance is improved with as few observed nodes as possible. We assume that many attributed graphs with observed responses are given as a training dataset. Our task is to improve the node response prediction performance with fewer observations in an unseen attributed graph with an unseen response variable. The proposed method contains two models: a response prediction model, and node selection model. The response prediction model predicts node responses given an attributed graph, and the node selection model outputs scores for selecting a node to observe given an attributed graph. Figure~\ref{fig:task} illustrates the response prediction and node selection models. We use graph convolutional neural networks (GCNs)~\cite{kipf2016semi} for both of the models. By taking attributes, observed responses, and masks that indicating observed nodes as input, the GCNs can output predictions or scores for unseen graphs depending on the observed responses by aggregating information of all nodes considering the graph structure. The response prediction model is trained by minimizing the expected test prediction error using an episodic training framework~\cite{ravi2016optimization,santoro2016meta,snell2017prototypical,finn2017model,li2017meta}. The episodic training framework, which is often used for meta-learning, simulates a test phase by randomly selecting observed and unobserved nodes using training attributed graphs. The node selection model is trained by maximizing the expected test error reduction by reinforcement learning. Although many existing active learning methods use heuristics, such as uncertainty~\cite{lewis1994sequential,holub2008entropy,yu2010active,jing2004entropy,gal2017deep}, for selecting node policies, our meta-learning framework directly optimizes an active learning policy that maximizes the expected test error reduction, where the policy is applicable to unseen graphs with unseen response variables. Figure~\ref{fig:task} illustrates our training framework. Our main contributions are as follows: \begin{itemize} \item We propose a meta-active learning method for node response prediction in graphs, where our models can be used for unseen graphs with unseen response variables. \item The proposed method directly maximizes the expected test error reduction for node response prediction tasks. \item We demonstrate the effectiveness of the proposed method using 11 types of road congestion prediction tasks. \end{itemize} \begin{figure}[t!] \centering {\tabcolsep=2em \begin{tabular}{cc} \includegraphics[height=24em]{images/model.png}& \includegraphics[height=24em]{images/task.png}\\ (a) Models & (b) Training \\ \end{tabular}} \caption{(a) Our response prediction and node selection models. These models take attributed graphs with a few response observations as input, where observed and unobserved nodes are represented by red and gray circles. The response prediction model outputs predicted responses for each node, where red (yellow) indicates high (low) predicted values. The node selection model outputs scores for each node that are used for selecting nodes to observe in active learning, where a selected node is represented by the big blue circle. (b) Our training framework. First, the response prediction model is trained using a training dataset, which contains various graphs with various response types. Second, the node selection model is trained using the training dataset and trained response prediction model.} \label{fig:task} \end{figure} The remainder of this paper is organized as follows. Section~\ref{sec:related} briefly reviews related work. Section~\ref{sec:proposed} defines our problem, proposes our response prediction and node selection models, and presents their training procedures. In Section~\ref{sec:experiments}, we demonstrate the effectiveness of the proposed method with congestion prediction tasks using road graphs in the UK. Finally, we give a concluding remark and future work in Section~\ref{sec:conclusion}. \section{Related work} \label{sec:related} Active learning selects examples to be labeled for improving the performance while reducing costly labeling effort. Many active learning methods have been proposed~\cite{fu2013survey}, such uncertainty sampling~\cite{lewis1994sequential,holub2008entropy,yu2010active,jing2004entropy,gal2017deep}, query-by-committee~\cite{seung1992query,freund1997selective}, mutual information~\cite{guestrin2005near,houlsby2011bayesian,iwata2013active}, core-set~\cite{sener2017active}, and mean standard deviation~\cite{kendall2015bayesian,kampffmeyer2016semantic}. Although the metrics used in these methods are computed efficiently, they are different from the expected test error that we want to minimize. Active learning methods that directly reduce the test error have been proposed~\cite{cohn1996active,roy2001toward}. These methods use simple models that can calculate the test error in closed form~\cite{cohn1996active}, or use sampling to estimate the test error~\cite{roy2001toward}. On the other hand, the proposed method directly optimizes a policy that maximizes the test error reduction, by which we do not need to calculate the test error in a test phase. Although a number of active learning methods using reinforcement learning have been proposed~\cite{fang2017learning,liu2018learning,liu2018translation,haussmann2019deep,konyushkova2017learning,pang2018meta,ebert2012ralf,hsu2015active,bachman2017learning,woodward2017active}, but they are not for graphs. Active learning for graph embedding has been proposed~\cite{cai2017active} but it is not for node response prediction tasks. GCNs have been in a wide variety of applications~\cite{scarselli2008graph,kipf2016semi,defferrard2016convolutional,duvenaud2015convolutional,hamilton2017inductive}, including meta-learning~\cite{bose2019meta,garcia2017few}. However, they are not used for active learning. \section{Proposed method} \label{sec:proposed} \subsection{Problem definition} In a training phase, we are given a set of $D$ graphs with attributes and responses, $\mathcal{G}=\{\vec{G}_{d}\}_{d=1}^{D}$, where $\vec{G}_{d}=(\vec{A}_{d},\vec{X}_{d},\vec{y}_{d})$ is the $d$th graph, $\vec{A}_{d}\in\{0,1\}^{N_{d}\times N_{d}}$ is the adjacency matrix, $N_{d}$ is the number of nodes, $\vec{X}_{d}=(\vec{x}_{dn})_{n=1}^{N_{d}}\in\mathbb{R}^{N_{d}\times J_{d}}$, $\vec{y}_{d}=(y_{dn})_{n=1}^{N_{d}}\in\mathbb{R}^{N_{d}}$, $\vec{x}_{dn}\in\mathbb{R}^{J_{d}}$ is the attributes of the $n$th node, and $y_{dn}\in\mathbb{R}$ is its response. Although we assume undirected and unweighted graphs for simplicity, we can straightforwardly extend the proposed method for directed and/or weighted graphs. In a test phase, we are given target graph $\vec{G}_{*}=(\vec{A}_{*},\vec{X}_{*})$ without responses. The response type of the target graph is different from that of the training graphs, e.g., the target response variable is bicycle traffic, and the training response variables are car, taxis and bus traffic. Our task is to improve the response prediction performance of all nodes in the target graph by selecting nodes to observe, where a smaller number of observed nodes is preferred. \subsection{Model} Graph convolutional neural networks (GCNs) are used for modeling both predicting responses and selecting nodes to observe. Let $\vec{m}_{d}\in\{0,1\}^{N_{d}}$ be the binary mask vector for indicating observed nodes, where $m_{dn}=1$ if the response of the $n$th node is observed, and $m_{dn}=0$ otherwise. Let $\bar{\vec{y}}_{d}$ be the observed response vector, where $\bar{y}_{dn}=y_{dn}$ if $m_{dn}=1$, $\bar{y}_{dn}=0$ otherwise. For the input of a GCN, we use the following concatenated vector of the attributes, observed responses, and masks, \begin{align} \vec{z}_{dn}^{(0)}=[\vec{x}_{dn},\bar{y}_{dn},m_{dn}], \label{eq:input} \end{align} where $\vec{z}_{dn}^{(0)}$ is the input vector of the $n$th node, and $[\cdot,\cdot]$ represents a concatenation. With the above input, we can output predictions and scores without retraining even when responses of nodes are additionally observed by changing the input such that $\bar{y}_{dn}=y_{dn}$ and $m_{dn}=1$ for additionally observed node $n$. With GCNs, the hidden state at the next layer is calculated by \begin{align} \vec{z}_{dn}^{(k+1)}=\sigma\left( \vec{W}^{(k)}\vec{z}_{dn}^{(k)}+ \frac{1}{N_{dn}}\sum_{m=1}^{N_{d}}a_{dnm} \vec{U}^{(k)}\vec{z}_{dm}^{(k)} \right), \label{eq:gcn} \end{align} where $\vec{z}_{dn}^{(k)}$ is the hidden state of the $n$th node at the $k$th layer, $\sigma$ is the activation function, $a_{dnm}$ is the $(n,m)$th element of adjacency matrix $\vec{A}_{d}$, $N_{dn}=\sum_{m}a_{dnm}$ is the number of neighbors of the $n$th node, $\vec{W}^{(k)}\in\mathbb{R}^{H_{k+1}\times H_{k}}$ and $\vec{U}^{(k)}\in\mathbb{R}^{H_{k+1}\times H_{k}}$ are the linear projection matrices of the $k$th layer, and $H_{k}$ is the hidden state size of the $k$th layer. Eq.~(\ref{eq:gcn}) aggregates the information of the own node (the first term) and its neighbor nodes (the second term) with transformation. The hidden state at the last $K$th layer is the output of the GCN. We use a GCN for response prediction model $f$ with parameters $\bm{\Phi}=\{\vec{W}_{\mathrm{f}}^{(k)},\vec{U}_{\mathrm{f}}^{(k)}\}_{k=1}^{K_{\mathrm{f}}}$ as follows, \begin{align} \hat{\vec{y}}_{d}=f(\vec{G}_{d},\vec{m}_{d};\bm{\Phi}), \label{eq:f} \end{align} where $\hat{\vec{y}}_{d}\in\mathbb{R}^{N_{d}}$ is the predicted responses, and the $K_{\mathrm{f}}$ is the number of layers. The input of the GCN in Eq.~(\ref{eq:input}) is calculated using $\vec{G}_{d}$ and $\vec{m}_{d}$. Also, we use another GCN for node selection model $g$ with parameters $\bm{\Theta}=\{\vec{W}_{\mathrm{g}}^{(k)},\vec{U}_{\mathrm{g}}^{(k)}\}_{k=1}^{K_{\mathrm{g}}}$ as follows, \begin{align} \vec{s}_{d}=g(\vec{G}_{d},\vec{m}_{d};\bm{\Theta}), \label{eq:g} \end{align} where $\vec{s}_{d}=(s_{dn})_{n=1}^{N_{d}}\in\mathbb{R}^{N_{d}}$, and $s_{dn}$ is the score that the $n$th node is selected to observe the response. Our model can be used for meta-learning, where values of unseen response variables are predicted, since it has similar operations to existing meta-learning methods, such as conditional neural processes~\cite{garnelo2018conditional}. Conditional neural processes consist of an encoder, an aggregator, and a decoder. The encoder takes observed attributes and responses as input, and outputs a representation for each observed node. The aggregator summarizes the set of representations for the observed nodes into a single representation. The decoder takes the aggregated representation and attributes without responses as input, and predicts responses. Since our model takes the attributes, observed responses, and masks as input, the GCN simultaneously works as an encoder, aggregator, and decoder. In particular, the first term in Eq.~(\ref{eq:gcn}) works as an encoder for nodes with observed responses, and as a decoder for nodes without observed responses. The second term in Eq.~(\ref{eq:gcn}) works as an aggregator by summarizing representations of the neighbor nodes. \subsection{Training} First, we train parameters $\bm{\Phi}$ of response prediction model $f$, and then train parameters $\bm{\Theta}$ of node selection model $g$ while fixing $f$. \subsubsection{Response prediction model} We estimate parameters $\bm{\Phi}$ of response prediction model $f$ in Eq.~(\ref{eq:f}) by minimizing the expected test prediction error, \begin{align} \hat{\bm{\Phi}}=\arg\min_{\bm{\Phi}}\mathbb{E}_{\vec{G}_{d}}[\mathbb{E}_{\vec{m}_{d}}[L(\vec{G}_{d},\vec{m}_{d};\bm{\Phi})]], \end{align} using training graph set $\mathcal{G}$ with an episodic training framework. Here, $\mathbb{E}$ represents an expectation, and the expectation are taken over various graphs $\vec{G}_{d}$ in training graph set $\mathcal{G}$, and over various observation patterns $\vec{m}_{d}$ in each graph, where we randomly generate target graphs for simulating a test phase. The test prediction error for a target graph is calculated by \begin{align} L(\vec{G}_{d},\vec{m}_{d};\bm{\Phi})= \frac{1}{\sum_{n=1}^{N_{d}}(1-m_{dn})} \sum_{n=1}^{N_{d}}(1-m_{dn})\parallel y_{dn}-f_{n}(\vec{G}_{d},\vec{m}_{d};\bm{\Phi})\parallel^{2}, \label{eq:L} \end{align} where $f_{n}(\vec{G}_{d},\vec{m}_{d};\bm{\Phi})$ is the $n$th element of the output of the response prediction model, the responses are predicted using the observed nodes, $m_{dn}=1$, and the test prediction error is calculated for the unobserved nodes, $m_{dn}=0$. When response variables are categorical, the cross-entropy loss with the softmax function can be used instead of the squared error loss. Algorithm~\ref{alg:prediction} shows the training procedures of the response prediction model. For each epoch, we simulate a test phase by uniform randomly sampling a graph from the training dataset (Line~3) and uniform randomly selecting observed nodes in the graph (Line~4). \begin{algorithm}[t!] \caption{Training procedure of response prediction model $f$.} \label{alg:prediction} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \REQUIRE{Set of training graphs $\mathcal{G}$, support set size $N_{\mathrm{S}}$} \ENSURE{Trained model parameters $\bm{\Phi}$} \STATE Initialize parameters $\bm{\Phi}$ randomly \WHILE{not done} \STATE Sample graph $\vec{G}_{d}$ from $\mathcal{G}$ \STATE Sample $N_{\mathrm{S}}$ observed nodes $\mathcal{S}$ from $\{1,\cdots,N_{d}\}$ \STATE Set mask vector $\vec{m}_{d}$ using the sampled observed nodes, such that $m_{dn}=1$ if $n\in\mathcal{S}$, and $m_{dn}=0$ otherwise \STATE Calculate loss $L(\vec{G}_{d},\vec{m}_{d};\bm{\Phi})$ by Eq.~(\ref{eq:L}) and its gradients \STATE Update parameters $\bm{\Phi}$ using the gradients \ENDWHILE \end{algorithmic} \end{algorithm} \subsubsection{Node selection model} We estimate parameters $\bm{\Theta}$ of node selection model $g$ in Eq.~(\ref{eq:g}) by maximizing the expected test error reduction using training graph set $\mathcal{G}$ based on reinforcement learning with an episodic training framework. For rewards, we use the test error reduction when node $n$ is selected to observe with graph $\vec{G}_{d}$ and mask $\vec{m}_{d}$ as follows, \begin{align} R(\vec{G}_{d},\vec{m}_{d},n)= \frac{L(\vec{G}_{d},\vec{m}_{d};\hat{\bm{\Phi}})-L(\vec{G}_{d},\vec{m}_{d}^{(+n)};\hat{\bm{\Phi}})}{L(\vec{G}_{d},\vec{m}_{d};\hat{\bm{\Phi}})}, \label{eq:r} \end{align} where $\vec{m}_{d}^{(+n)}$ is the updated mask vector of $\vec{m}_{d}$ when node $n$ is additionally observed, $m_{dn'}^{(+n)}=1$ if $n'=n$, and $m_{dn'}^{(+n)}=m_{dn'}$ otherwise. Here, parameters of trained response prediction models $\hat{\bm{\Phi}}$ is used. We can calculate the error $L(\vec{G}_{d},\vec{m}_{d}^{(+n)};\hat{\bm{\Phi}})$ when node $n$ is additionally observed by feeding the updated mask vector and graph into our response prediction model based on GCNs without retraining. In terms of reinforcement learning, a pair of graph $\vec{G}_{d}$ and mask $\vec{m}_{d}$ is a state, node to observe $n$ is an action, and node selection model $g(\vec{G}_{d},\vec{m}_{d};\bm{\Theta})$ that outputs scores of actions given a state is a policy. The expected test error reduction is calculated by \begin{align} \hat{\bm{\Theta}}=\arg\max_{\bm{\Theta}} \mathbb{E}_{\vec{G}_{d}}[\mathbb{E}_{(\vec{m},n)\sim\bm{\pi}(\bm{\Theta})}[R(\vec{G}_{d},\vec{m},n)]], \end{align} where $\bm{\pi}(\bm{\Theta})$ is the probability distribution of the policy for selecting nodes, which is defined by node selection model $g$ with parameter $\bm{\Theta}$. Algorithm~\ref{alg:active} shows the training procedures of the node selection model with policy gradients, where active learning is simulated using randomly selected graphs (Line~3). Each active learning task starts with a graph without observed responses (Line~4), and we iterate until $N_{\mathrm{A}}$ nodes are observed (Line~5). A node is selected according to the following policy that is calculated from scores $\vec{s}_{d}$ (Lines~6--7), \begin{align} \pi_{dn}=\frac{\exp(s'_{dn})}{\sum_{m=1}^{N_{d}}\exp(s'_{dm})}, \label{eq:pi} \end{align} where $s'_{dn}=s_{dn}$ if $m_{dn}=0$, and $s'_{dn}=-\infty$ otherwise, by which already observed nodes are excluded from selection. A node is sampled according to the categorical distribution with parameters $\bm{\pi}_{d}$ (Line~8). The test error reduction, or reward, is calculated at Line~9. At Line~10, parameters $\bm{\Phi}$ are updated by using the log-derivative trick, or Reinforce~\cite{williams1992simple}, where the average total reward was used for the baseline~\cite{zhao2011analysis}. Although we use the myopic rewards in the algorithm, we can also use non-myopic rewards. \begin{algorithm}[t!] \caption{Training procedure of node selection model $g$.} \label{alg:active} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \REQUIRE{Set of training graphs $\mathcal{G}$, maximum support set size $N_{\mathrm{A}}$} \ENSURE{Trained model parameters $\bm{\Theta}$} \STATE Initialize parameters $\bm{\Theta}$ randomly \WHILE{not done} \STATE Sample graph $\vec{G}_{d}$ from $\mathcal{G}$ \STATE Initialize mask vector $\vec{m}_{d}=\bm{0}$ \FOR{$t=1,\cdots,N_{\mathrm{A}}$} \STATE Calculate score $\vec{s}_{d}=g(\vec{G}_{d},\vec{m}_{d};\bm{\Theta})$ \STATE Set policy $\bm{\pi}_{d}$ by Eq.~(\ref{eq:pi}) \STATE Sample an observed node according to the policy $n\sim\mathrm{Categorical}(\bm{\pi}_{d})$ \STATE Calculate test error reduction $R(\vec{G}_{d},\vec{m}_{d},n)$ by Eq.~(\ref{eq:r}) \STATE Update parameters $\bm{\Theta}\leftarrow\bm{\Theta}+\alpha R(\vec{G}_{d},\vec{m}_{d},n) \nabla_{\bm{\Theta}}\log \pi_{dn}$ \STATE Update mask to include selected node $n$ in observed nodes $m_{dn}=1$ \ENDFOR \ENDWHILE \end{algorithmic} \end{algorithm} \subsection{Test} In a test phase, given target $\vec{G}_{*}$ without responses, we first initialize mask vector $\vec{m}_{*}=\bm{0}$. Second, we select a node with the maximum score \begin{align} \hat{n}=\arg\max_{n:m_{*n}=0}s_{*n}, \end{align} among unobserved nodes using the trained node selection model. Third, we update the mask vector with the selected node by $m_{*\hat{n}}=1$. We iterate the second and third steps until an end condition is satisfied. \section{Experiments} \label{sec:experiments} \subsection{Data} We evaluated the proposed method with 11 types of congestion prediction tasks using road graphs in the UK. The original data were obtained from UK Department for Transport~\footnote{\url{https://roadtraffic.dft.gov.uk/downloads}}. The data contained road level Annual Average Daily Flow (AADF) at major and minor roads in the UK for the following 11 types: pedal cycles, two-wheeled motor vehicles, car and taxis, buses and coaches, light goods vehicles (LGVs), two-rigid axle heavy good vehicle (HGVs), three-rigid axle HGVs, four or more rigid axle HGVs, three or four-articulated axle HGVs, five-articulated axle HGVs, and six-articulated axle HGVs. We used the 11 AADFs for response variables, and used road categories, road types, longitude and latitude for attributes. There were six road categories, and two road types (major and minor). These categorical attributes were transformed to one-hot vectors. The real-valued attributes and responses were normalized in the range of zero to one. We generated an undirected road graph for each local authority, where a node was a road, and nodes with four nearest neighbors based on their latitude and longitude were connected with edges. Examples of the generated road graphs are shown in Figure~\ref{fig:task}. There were 206 graphs in total for each response variable and for each year, where the average, minimum and maximum number of nodes for each graph was 103, 5 and 562. For each experiment, we used an AADF in a region for target data, and used the other AADFs in the other regions for training and validation data; i.e., the AADF or region in target data are not contained in training and validation data. There were 11 regions, such as East-Midlands, London, Scotland and Wales. A region was used for validation, and the remaining nine regions were used for training. \subsection{Comparing methods} We compared the proposed active learning method with the following methods for selecting nodes to observe: Random, Variance, Entropy, MI (mutual information), and FF (feed-forward neural network). All the methods used the same response prediction model in Eq.~(\ref{eq:f}) to evaluate the active learning performance. The Random method randomly selects a node to observe. The Entropy method selects a node that maximizes the entropy, or uncertainty~\cite{lewis1994sequential,holub2008entropy,yu2010active,jing2004entropy,gal2017deep}. With the entropy method, first, we trained a GCN that outputs mean and standard deviation of responses, \begin{align} \hat{\vec{y}}_{d},\hat{\bm{\sigma}}_{d} = f_{\mathrm{entropy}}(\vec{G}_{d},\vec{m}_{d};\bm{\Phi}), \label{eq:f_entropy} \end{align} by minimizing the negative Gaussian likelihood loss instead of the test prediction error in Eq.~(\ref{eq:L}), \begin{align} L_{\mathrm{entropy}}(\vec{G}_{d},\vec{m}_{d};\bm{\Phi})= \frac{1}{\sum_{n=1}^{N_{d}}(1-m_{dn})} \sum_{n=1}^{N_{d}}(1-m_{dn})\log \mathcal{N}(y_{dn};\hat{y}_{dn},\hat{\sigma}_{dn}^{2}), \label{eq:L_entropy} \end{align} where $\mathcal{N}(x;\mu,\sigma^{2})$ is the probability density function at $x$ of the Gaussian distribution with mean $\mu$ and standard deviation $\sigma$, and $\hat{y}_{dn}$ and $\hat{\sigma}_{dn}$ are the estimated mean and standard deviation for the $n$th node by Eq.~(\ref{eq:f_entropy}). The GCN in Eq.~(\ref{eq:f_entropy}) is the same with Eq.~(\ref{eq:f}) except that its final layer additionally outputs standard deviation. Using the trained GCN in Eq.~(\ref{eq:f_entropy}), we select a node that maximizes the entropy, $\hat{n}=\arg\max_{n:m_{*n}} \mathbb{H}[y_{dn}|\vec{G}_{d},\vec{m}_{d}]$, where the entropy is calculated by \begin{align} \mathbb{H}[y_{dn}|\vec{G}_{d},\vec{m}_{d}]=\log\hat{\sigma}_{dn}+\frac{1}{2}(\log(2\pi)+1). \label{eq:H} \end{align} The Variance method selects a node that maximizes the variance estimated using dropout~\cite{tsymbalov2018}. Dropout randomly sets hidden unit activities to zero~\cite{srivastava2014dropout}. Let $\hat{y}_{dn}^{(\ell)}\in\mathbb{R}^{N_{d}}$ be the $\ell$th output of the GCN in Eq.~(\ref{eq:f}) in stochastic runs with dropout. The variance of prediction $\hat{y}_{dn}$ was calculated by \begin{align} \mathrm{Var}[\hat{y}_{dn}] = \frac{1}{L}\sum_{\ell=1}^{L}(\hat{y}_{dn}^{(\ell)}-\bar{\hat{y}}_{dn})^{2}, \end{align} where $L$ is the number of stochastic runs, $\bar{\hat{y}}_{dn}=\frac{1}{L}\sum_{\ell=1}^{L}\hat{y}_{dn}^{(\ell)}$ is the average over the stochastic runs. We used $L=10$. The MI method selects a node that maximizes the mutual infromation~\cite{gal2017deep} between responses and model parameters, \begin{align} \mathbb{I}[y_{dn},\bm{\Phi}|\vec{G}_{d},\vec{m}_{d}] = \mathbb{H}[y_{dn}|\vec{G}_{d},\vec{m}_{d}]-\mathbb{E}_{p(\bm{\Phi}|\vec{G}_{d},\vec{m}_{d})}[\mathbb{H}[y_{dn}|\vec{G}_{d},\vec{m}_{d},\bm{\Phi}]]. \end{align} The first term was calculated with Eq.~(\ref{eq:H}). The second term was calculated using dropout as follows, \begin{align} \mathbb{E}_{p(\bm{\Phi}|\vec{G}_{d},\vec{m}_{d})}[\mathbb{H}[y_{dn}|\vec{G}_{d},\vec{m}_{d},\bm{\Phi}]]=\frac{1}{L}\sum_{\ell=1}^{L}(\log\hat{\sigma}_{dn}^{(\ell)}+\frac{1}{2}(\log(2\pi)+1))), \end{align} where $\hat{\sigma}_{dn}^{(\ell)}$ is the $\ell$th estimate of the standard deviation by Eq.~(\ref{eq:f_entropy}) in stochastic runs with dropout. The FF method used feed-forward neural networks for the node selection model instead of Eq.~(\ref{eq:g}) based on GCNs. The FF method takes attributes $\vec{x}_{dn}$, and outputs score $s_{dn}$ for each node. The neural networks were trained in the same way with the proposed method. Since the FF method outputs the score for each node individually, it does not meta-learn, but learns the relationship between the attributes and scores. \subsection{Proposed method setting} With GCNs for response prediction and node selection models, the number of hidden units was 32, the number of layers was three with residual connections. The models were trained by Adam~\cite{kingma2014adam} with learning rate $10^{-3}$ and dropout rate $0.1$. The maximum number of epochs was 1,000, and the validation data were used for early stopping. The support set size was $N_{\mathrm{S}}=5$ for training response prediction models, and the maximum support set size was $N_{\mathrm{A}}=10$ for training node selection models. \subsection{Results} Figure~\ref{fig:results} shows the mean squared error and its standard error with different numbers of observations for each AADF prediction task. All the methods decreased the error as the number of observed nodes increased, which implied that the response prediction model improved the performance by observing node responses. The proposed method achieved the lowest mean squared error in most cases. This result indicates that training node selection models by directly maximizing test reduction errors using reinforcement learning is effective. The Entropy method achieved the second lowest error. Even if we observed a node has high entropy, the test errors for other nodes might not decrease when the observed node has little relationships with other nodes. On the other hand, the proposed method selects nodes so as to maximize the test error reduction by considering the information of all nodes by GCNs. The MI and Variance methods did not perform well. This result implies that the estimation of variance and entropy based on dropout is difficult in this task. Since the FF method cannot use the information of other nodes, it performed badly. The computational time for training node selection and response prediction models with the proposed method was 3.7 and 44.5 hours, respectively, by computers with 2.10-GHz Xeon Gold 6130 CPU. \begin{figure}[t!] \centering {\tabcolsep=0.0em \begin{tabular}{ccc} \includegraphics[height=11em]{images/active_meta_y0.pdf}& \includegraphics[height=11em]{images/active_meta_y1.pdf}& \includegraphics[height=11em]{images/active_meta_y2.pdf}\\ (a) pedal cycles & (b) two-wheeled & (c) car \\ \\ \includegraphics[height=11em]{images/active_meta_y3.pdf}& \includegraphics[height=11em]{images/active_meta_y4.pdf}& \includegraphics[height=11em]{images/active_meta_y5.pdf}\\ (d) buses and coaches & (e) LGVs & (f) 2-rigid \\\ \\ \includegraphics[height=11em]{images/active_meta_y6.pdf}& \includegraphics[height=11em]{images/active_meta_y7.pdf}& \includegraphics[height=11em]{images/active_meta_y8.pdf}\\ (g) 3-rigid & (h) 4-rigid & (i) 3-articulated \\ \\ \includegraphics[height=11em]{images/active_meta_y9.pdf}& \includegraphics[height=11em]{images/active_meta_y10.pdf}& \\ (j) 5-articulated& (k) 6-articulated& \\ \end{tabular}} \caption{Test mean squared error (vertical axis) with different numbers of observations (horizontal axis) for each AADF task. The bar shows the standard error.} \label{fig:results} \end{figure} \section{Conclusion} \label{sec:conclusion} We proposed an active learning method for meta-learning on node response prediction tasks in graph data. With the proposed method, graph convolutional neural networks are used for calculating scores to select nodes to observe, where attributes, observed responses, and masks indicating observed nodes are taken as input. By using the graph convolutional neural networks, we can select nodes for unseen graphs with unseen response variables depending on a few observed responses and the graph structure. We demonstrated that the proposed method achieved higher performance for road congestion prediction tasks with fewer observed nodes compared with existing active learning methods. For future work, we want to apply the proposed method to tasks other than node response prediction, such as link prediction and graph generation. Although we used graph convolutional neural networks, we plan to use other meta-learning models for meta-active learning.
{'timestamp': '2020-10-13T02:26:50', 'yymm': '2010', 'arxiv_id': '2010.05387', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05387'}
arxiv
\section{Introduction} We consider the estimation of conditional statistics of a response variable, $Y\in\mathbb{R}^m$, given the value of a predictor or covariate $X\in\mathbb{R}^n$. The single most important instance of these types of problems involves estimating the conditional mean, or also known as the regression function. Under finite variance assumptions, the conditional mean $\mathds{E}_\mbb P[Y | X = x_0]$ is technically defined as $\psi^\star(x_0)$ for some measurable function $\psi^\star$ that solves the minimum mean square error problem \begin{equation} \nota \min\limits_{\psi} ~\mathds{E}_\mbb P[ \| Y - \psi(X) \|_2^2 ], \end{equation} where the minimization is taken over the space of all measurable functions from $\mathbb{R}^n$ to $\mathbb{R}^m$. While the optimal solution $\psi^\star$ is unique up to sets of $\mbb P$-measure zero, unfortunately, solving for $\psi^\star$ is challenging because it is an infinite-dimensional optimization problem. The regression function $\psi^\star$ can be efficiently found only under specific settings, for example, if one assumes that $(X, Y)$ follows a jointly Gaussian distribution. However, these specific situations are overly restrictive in practice. In order to bypass the infinite-dimensional challenge involved in directly computing $\psi^\star$, we may instead consider a family of optimization problems that are parametrized by $x_0$. More specifically, in the presence of a regular conditional distribution, the conditional mean $\mathds{E}_{\mbb P}[Y | X = x_0]$ can be estimated pointwise by $\widehat \beta$ defined as \[ \widehat \beta \in \arg \min\limits_{\beta} \mathds{E}_{\mbb P} [ \| Y - \beta \|_2^2 | X = x_0 ] \] for any covariate value $x_0$ of interest. This presents the challenge of effectively accessing the conditional distribution, which is particularly difficult if the event $X=x_0$ has $\mbb P$-probability zero. Using an analogous argument, if we are interested in the conditional $(\tau \times 100\%)$-quantile of $Y$ given $X$, then this conditional statistics can be estimated pointwise at any location $x_0$ of interest by \[ \widehat \beta \in \arg \min\limits_{\beta } \mathds{E}_{\mbb P}[ \max\{-\tau(Y - \beta), (1-\tau)(Y - \beta)\} | X = x_0]. \] The previous examples illustrate that the estimation of a wide range of conditional statistics can be recast into solving a family of finite-dimensional optimization problems parametrically in $x_0$ \begin{equation} \label{eq:original} \min\limits_{\beta}~\mathds{E}_{\mbb P} [ \ell(Y, \beta) | X = x_0] \end{equation} with an appropriately chosen statistical loss function $\ell$. Problem \eqref{eq:original} poses several challenges, some of which were alluded to earlier. First, it requires the integration with respect to a difficult to compute conditional probability distribution. Second, the probability measure $\mbb P$ is generally unknown, hence we lack a fundamental input to solve \eqref{eq:original}. Finally, in a data-driven setting, there may be few, or even no, observations with value covariate $X = x_0$. To alleviate these difficulties, our formulation, as we shall explain, involves two features. First, we consider a relaxation of problem~\eqref{eq:original} in which the event $X=x_0$ is replaced by a neighborhood $\mathcal N_{\gamma}(x_0)$ of a suitable radius $\gamma \ge 0$ around $x_0$. Second, we introduce a data-driven distributionally robust optimization (DRO) formulation (e.g. \cite{ref:delage2010distributionally, ref:blanchet2019quantifying, ref:kuhn2019wasserstein}) in order to mitigate the problem that $\mbb P$ is unknown. In turn, the DRO formulation involves a novel class of conditional ambiguity set which copes with the underlying {\it conditional distribution} being unknown. In particular, we propose the following \textit{distributionally robust local conditional estimation problem} \begin{equation} \label{eq:local_DRO} \min\limits_{\beta } \sup\limits_{\mbb Q \in \mathbb B_\rho^\infty, \mbb Q (X \in \mathcal N_{\gamma}(x_0)) > 0 } \mathds{E}_{\mbb Q} \big[ \ell(Y, \beta) | X \in \mathcal N_{\gamma}(x_0) \big], \end{equation} where the maximization is taken over all probability measures $\mbb Q$ that are within $\rho$ distance in the $\infty$-Wasserstein sense of a benchmark nominal model, which often corresponds to the empirical distribution of available data. The probability measures $\mbb Q$ are constrained so that $\mbb Q(X \in \mathcal N_{\gamma}(x_0))>0$ to eliminate the complication of conditioning on a set of measure zero. \textbf{Contributions.} Resting on formulation \eqref{eq:local_DRO}, our main contributions are summarized as follows. \begin{enumerate}[leftmargin = 5mm] \item We introduce a novel paradigm of non-parametric local \textit{conditional} estimation based on distributionally robust optimization. In contrast to classical non-parametric conditional estimators, our new class of estimators are endowed by design with robustness features. They are structurally built to mitigate the impact of model contamination and therefore they may be reasonably applied to heterogeneous data (e.g., non i.i.d.~input). \item We demonstrate that when the ambiguity set is a type-$\infty$ Wasserstein ball around the empirical measure, the proposed min-max estimation problem can be efficiently solved in many applicable settings, including notably the local conditional mean and quantile estimation. \item We show that this class of type-$\infty$ Wasserstein local conditional estimators can be considered as a systematic robustification of the $k$-nearest neighbor estimator. We also provide further insights on the statistical properties of our approach and empirical evidence, with both a synthetic and real data sets, that our approach can provide more accurate estimations in practically relevant settings. \end{enumerate} \textbf{Related work.} One can argue that every single prediction task in machine learning ultimately relates to conditional estimation. So, attempting to provide a full literature survey on non-parametric conditional estimation is an impossible task. Since our contribution is primarily on introducing a novel conceptual paradigm powered by DRO, we focus on discussing well-understood estimators that encompass most of the conceptual ideas used to mitigate the challenges exposed earlier. The challenges of conditioning on zero probability events and the fact that $x_0$ may not be a part of the sample are addressed based on the idea of averaging around a neighborhood of the point of interest and smoothing. This gives rise to estimators such as $k$-NN (see, for example, \cite{ref:devroye1978uniform}), and kernel density estimators, including, for instance the Nadaraya-Watson estimator (\cite{ref:nadaraya1964estimating, ref:watson1964smooth}) and the Epanechnikov estimator \cite{ref:epanechnikov1969non}, among others. Additional averaging methods include, for example, random forests~\cite{ref:breiman2001random} and Classification and Regression Trees (CARTs, \cite{ref:breiman1984classification}), see also \cite{ref:hastie2009elements} for other techniques. These averaging and smoothing ideas are well understood, leading to the optimal selection (in a suitable sense) of the kernel along with the associated tuning parameters such as the bandwidth size. These choices are then used to deal with the ignorance of the true data generating distribution by assuming a certain degree of homogeneity in the data, such as stationarity and weak dependence, in order to guarantee consistency and recovery of the underlying generating model. However, none of these estimators are directly designed to cope with the problem of general (potentially adversarial) data contamination. The later issue revolving around the evaluation of an unknown conditional probability model is connected with robustness, another classical topic in statistics \cite{ref:huber1992robust}. Much of the classical literature on robustness focuses on the impact of outliers. The work of \cite{ref:zhao2016robust} studies robust-against-outliers kernel regression which enjoys asymptotic consistency and normality under i.i.d.~assumptions in a setting where the data contamination becomes negligible. In contrast to this type of contamination, our estimators are designed to be min-max optimal in the DRO sense by supplying the best response against a large (non-parametric) class of adversarial contamination. \modif{Our results can also be seen as connected to adversarial training, which has received a significant amount of attention in recent years \cite{ref:goodfellow2015texplaining,ref:kurakin2016adversarial,ref:madry2018towards,ref:tramer2018ensemble, ref:sinha2017certifying,ref:raghunathan2018certified}. Existing robustification of the nearest neighbors and of the nonparametric classifiers in general can be streamlined into two main strategies: i) global approaches that modify the whole training dataset, e.g., adversarial pruning \cite{ref:wang2018analyzing, ref:yang2020robustness, ref:bhattacharjee2020when}, and ii) local approaches that study well-crafted attack and seek appropriate defense for specific classifiers such as {$1$-NN} \cite{ref:khoury2018geometry, ref:wang2019evaluating,ref:li2019advknn}. Following this line of ideas, one can interpret our approach as a novel method to train conditional estimators against adversarial attacks. The difference, in the $k$-NN estimation setting for example, is that our attacks are optimal in a distributional sense. Our proposed estimator is thus provably the best for a uniform class of distributional attacks. Compared to the current literature, we believe that our approach is also more general in two significant ways: first, we start from a generic min-max estimation problem, and our ideas and methodology are easily applicable to other non-parametric settings, and second, we allow for perturbations on $Y$ to hedge against label contamination. } DRO-based estimators have generated a great deal of interest because they possess various desirable properties in connection to various forms of regularization (e.g., variance~\cite{ref:namkoong2017variance}; norm~\cite{ref:shafieezadeh2019regularization}; shrinkage~\cite{ref:nguyen2018distributionally}). The tools that we employ are related to those currently being investigated. Our formulation considers adversarial perturbations based on the Wasserstein distance~\cite{ref:esfahani2018data, ref:blanchet2019quantifying, ref:gao2016distributionally, ref:kuhn2019wasserstein}. In particular, the type-$\infty$ Wasserstein distance \cite{ref:givens1984class} is recently applied in DRO formulations \cite{ref:bertsimas2018data, ref:bertsimas2019computational, ref:xie2019tractable}. In particular, the work of \cite{ref:bertsimas2019dynamic} considers adversarial conditional estimation, taking as input various classical estimators (e.g., $k$-NNs, kernel methods, etc.) and proposes a robustification approach considering only perturbation in the response variable. Our method whereas allows perturbations both to the covariate and response variables, which is technically more subtle because of the local conditioning problem. Within the $k$-NN DRO conditional robustification, our numerical experiments in Section~\ref{sect:numerical} show substantial benefits of our local conditioning approach, especially in dealing with non-homogeneity and sharp variations in the underlying density. \textbf{Notations.} For any integer $M \in \mathbb N_+$, we denote by $[M]$ the set $\{1, \ldots, M\}$. For any set $\mathcal S$, $\mathcal M(\mathcal S)$ is the space of all probability measures supported on $\mathcal S$. \section{Local Conditional Estimate using Type-$\infty$ Wasserstein Ambiguity Set} \label{sect:infty-set} We start by delineating the building blocks of our distributionally robust estimation problem~\eqref{eq:local_DRO}. The nominal measure is set to the empirical distribution of the available data, $\wh{\mbb P} = N^{-1} \sum_{i \in [N]} \delta_{(\widehat x_i, \widehat y_i)}$, where $\delta_{(\widehat x, \widehat y)}$ represents the Dirac distribution at $(\widehat x, \widehat y)$. The ambiguity set $\mathbb B_\rho^\infty$ is a Wasserstein ball around $\wh{\mbb P}$ that contains the true distribution $\mbb P$ with high confidence. \begin{definition}[Wasserstein distance] Let $\mbb D$ be a metric on $\Xi$. The type-$p$ $(1 \leq p < +\infty)$ Wasserstein distance between $\mbb Q_1$ and $\mbb Q_2$ is defined as \[ \mathds{W}_{p}(\mbb Q_1, \mbb Q_2) \Let \inf \left\{ \big(\mathds{E}_\pi [\mbb D(\xi_1, \xi_2)^p] \big)^{\frac{1}{p}}: \pi \in \Pi(\mbb Q_1, \mbb Q_2) \right\}, \] where $\Pi(\mbb Q_1 , \mbb Q_2)$ is the set of all probability measures on $\Xi \times \Xi$ with marginals $\mbb Q_1$ and $\mbb Q_2$, respectively. The type-$\infty$ Wasserstein distance is defined as the limit of $\mathds{W}_p$ as $p$ tends to $\infty$ and amounts to \[ \mathds{W}_{\infty}(\mbb Q_1, \mbb Q_2) \Let \inf \left\{ \mathrm{ess} \sup\limits_{\pi} \big\{ \mbb D(\xi_1, \xi_2) : (\xi_1, \xi_2) \in \Xi \times \Xi \big\} : \pi \in \Pi(\mbb Q_1, \mbb Q_2) \right\}. \] \end{definition} We assume that $(X,Y)$ admits values in $\mathcal X \times \mathcal Y \subseteq \mathbb{R}^n \times \mathbb{R}^m$, and the distance $\mbb D$ on $\mathcal X \times \mathcal Y$ is \[ \mbb D\big( (x, y), (x', y') \big) = \mbb D_{\mathcal X}(x, x') + \mbb D_{\mathcal Y}(y, y') \qquad \forall (x, y), (x', y') \in \mathcal X \times \mathcal Y, \] where $\mbb D_{\mathcal X}$ and $\mbb D_{\mathcal Y}$ are continuous metric on $\mathcal X$ and $\mathcal Y$, respectively. The joint ambiguity set $\mathbb B^\infty_\rho$ is now formally defined as a type-$\infty$ Wasserstein ball in the space of joint probability measures \[ \mathbb B^\infty_\rho \Let \left\{ \mbb Q \in \mathcal M(\mathcal X \times \mathcal Y): \mathds{W}_\infty(\mbb Q, \wh{\mbb P}) \leq \rho \right\}. \] We assume further that the compact neighborhood $\mathcal N_\gamma(x_0)$ around $x_0$ is prescribed using the distance $\mbb D_{\mathcal X}$ as $\mathcal N_\gamma(x_0)\Let\{ x \in \mathcal X: \mbb D_{\mathcal X}(x,x_0)\le\gamma\}$, and the loss function $\ell$ is jointly continuous in $y$ and $\beta$. To solve the estimation problem~\eqref{eq:local_DRO}, we study the worst-case conditional expected loss function \[ f(\beta) \Let\sup_{\mbb Q \in \mathbb B_\rho, \mbb Q (X \in \mathcal N_{\gamma}(x_0)) > 0 } \mathds{E}_{\mbb Q} \big[ \ell(Y, \beta) | X \in \mathcal N_{\gamma}(x_0) \big], \] which corresponds to the inner maximization problem of~\eqref{eq:local_DRO}. To ensure that the value $f(\beta)$ is well-defined, we first investigate the conditions under which the above supremum problem has a non-empty feasible set. Towards this end, for any set $\mathcal N_\gamma(x_0) \subset \mathcal X$, define the quantities $\kappa_{i, \gamma}$ as \begin{equation} \label{eq:kappa-def} 0 \le \kappa_{i, \gamma} \Let \min_{x \in \mathcal N_\gamma(x_0)}\mbb D_{\mathcal X}(x, \widehat x_i) + \inf_{y \in \mathcal Y}~\mbb D_{\mathcal Y}(y, \widehat y_i) \qquad \forall i \in [N]. \end{equation} The value $\kappa_{i, \gamma}$ signifies the unit cost of moving a point mass from an observation $(\widehat x_i, \widehat y_i)$ to the fiber set $ \mathcal N_\gamma(x_0) \times \mathcal Y$. We also define $\widehat x_i^p$ as the projection of $\widehat x_i$ onto the neighborhood $\mathcal N_\gamma(x_0)$, which coincides with the optimal solution in the variable $x$ of the minimization problem in~\eqref{eq:kappa-def}. The next proposition asserts that $f(\beta)$ is well-defined if the radius $\rho$ is sufficiently large. \begin{proposition}[Minimum radius] \label{prop:infty-vanilla-set} For any $x_0 \in \mathcal X$ and $\gamma \in \mathbb{R}_+$, there exists a distribution $\mbb Q \in \mathbb B_\rho$ that satisfies $\mbb Q(X \in \mathcal N_\gamma(x_0)) > 0$ if and only if $\rho \ge \min_{i \in [N]} \kappa_{i, \gamma}$. \end{proposition} \begin{wrapfigure}{R}{0.42\textwidth} \centering \includegraphics[width=0.4\textwidth]{I-set.png} \caption{Illustration around the neighborhood of $x_0$ with $\rho < \gamma$. Black crosses are samples in the set $\mathcal I$.} \label{fig:I-set} \end{wrapfigure} We now proceed to the reformulation of $f(\beta)$. Let $\mathcal I$ be the index set defined as \begin{subequations} \begin{equation} \label{eq:I-def1} \mathcal I \Let \left\{ i \in [N] : \mbb D_{\mathcal X}(x_0, \widehat x_i) \le \rho + \gamma \right\}, \end{equation} and $\mathcal I$ is decomposed further into two disjoint subsets \begin{equation} \label{eq:I-def2} \mathcal I_1 = \left\{ i \in \mathcal I: \mbb D_{\mathcal X}(x_0, \widehat x_i) + \rho \le \gamma \right\} ~~ \text{and} ~~ \mathcal I_2 = \mathcal I \backslash \mathcal I_1. \end{equation} \end{subequations} Intuitively speaking, $\mathcal I$ contains the indices of data points whose covariate $\widehat x_i$ is sufficiently close to $x_0$ measured by $\mbb D_{\mathcal X}$, and are thus relevant to the local estimation problem. The index set $\mathcal I_1$ indicates the data points that lie strictly inside the neighborhood, while the set $\mathcal I_2$ contains those points that are on the boundary ring of width $\rho$ around the neighborhood $\mathcal N_{\gamma}(x_0)$. The value $f(\beta)$ can be efficiently computed in a quasi-closed form thanks to the following result. \begin{theorem}[Worst-case conditional expected loss computation] \label{thm:infty-refor} For any $\gamma \in \mathbb{R}_+$, suppose that $\rho \ge \min_{i \in [N]} \kappa_{i, \gamma}$. For any $\beta \in \mathcal Y$, let $v_i^\star(\beta)$ be defined as \begin{equation} \label{eq:vi-def} v_i ^\star(\beta) \Let \sup\limits_{y_i} \left\{ \ell(y_i, \beta) : y_i \in \mathcal Y,~\mbb D_{\mathcal Y}(y_i, \widehat y_i) \leq \rho - \mbb D_{\mathcal X}(\widehat x_i^p, \widehat x_i) \right\} \quad \forall i \in \mathcal I. \end{equation} The worst-case conditional expected loss is equal to $ f(\beta) = \big(\sum_{i \in \mathcal I} \alpha_i\big)^{-1} \sum_{i \in \mathcal I} \alpha_i v_i^\star(\beta), $ where $\alpha$ admits the value \begin{equation} \notag \forall i \in \mathcal I: \quad \alpha_i = \begin{cases} 1 & \text{if } i \in \mathcal I_1 \text{ or } (\mathcal I_1 = \emptyset \text{ and } v_i^\star(\beta) = \max_{j \in \mathcal I_2} v_j^\star(\beta)), \\ 1 & \text{if } \displaystyle v_i^\star(\beta) > \frac{\sum_{i \in \mathcal I_1} v_i^\star(\beta) + \sum_{j \in \mathcal I_2: v_j^\star(\beta) > v_i^\star(\beta)} v_j^\star(\beta)}{|\mathcal I_1| + |\{j \in \mathcal I_2: v_j^\star(\beta) > v_i^\star(\beta) \}|},\\ 0 & \text{otherwise.} \end{cases} \end{equation} \end{theorem} If we possess an oracle that evaluates~\eqref{eq:vi-def} at a complexity $\mathcal O$, then by Theorem~\ref{thm:infty-refor}, quantifying $f(\beta)$ is reduced to calculating $|\mathcal I|$ values of $v_i^\star(\beta)$ and then sorting these values in order to determine the value of $\alpha$. Thus, computing $f(\beta)$ takes an amount of time of order $O\big(| \mathcal I | (\log | \mathcal I| + \mathcal O)\big)$. Moreover, $f(\beta)$ depends solely on the observations in the locality of $x_0$ whose indices belong to the index set $\mathcal I$, the cardinality of which can be substantially smaller than the total number of training samples $N$. If $\ell$ is a convex function in $\beta$, then a standard result from convex analysis implies that $f$, being a pointwise supremum of convex functions, is also convex. If $\mathcal Y$, and hence $\beta$, is unidimensional, a golden section search algorithm can be utilized to identify the local conditional estimate $\beta^*$ that solves~\eqref{eq:local_DRO} in an amount of time of order $O\big(\log(1/\epsilon) |\mathcal I| (\log(|\mathcal I|)+\mathcal O)\big)$, where $\epsilon> 0$ is an arbitrary accuracy level. Fortunately, in the case of conditional mean and quantile estimation, we also have access to the closed form expressions of $v_i^\star(\beta)$ as long as $\mbb D_{\mathcal Y}$ is an absolute distance. \begin{corollary}[Value of $v_i^\star(\beta)$] \label{corol:vi-opt} Suppose that $\mathcal Y= [a, b] \subseteq [-\infty, +\infty]$ and $\mbb D_{\mathcal Y}(y_i, \widehat y_i)=|y_i- \widehat y_i|$. \begin{enumerate}[label=(\roman*), leftmargin=6mm] \item Conditional mean estimation: if $\ell(y, \beta) = (y - \beta)^2$, then $\forall i \in \mathcal I$ \[ v_i^\star(\beta) = \max\big\{ (\max\{ \widehat y_i + \rho - \mbb D_{\mathcal X}(\widehat x_i^p, \widehat x_i), a\} - \beta)^2, (\min\{ \widehat y_i + \rho - \mbb D_{\mathcal X}(\widehat x_i^p, \widehat x_i), b\} - \beta)^2 \big\}. \] \item Conditional quantile estimation: if $\ell(y, \beta)=\max\{-\tau(y - \beta), (1-\tau)(y - \beta)\}$, then $\forall i \in \mathcal I$ \[ v_i^\star(\beta) \!=\!\max\big\{-\tau(\max\{ \widehat y_i + \rho - \mbb D_{\mathcal X}(\widehat x_i^p, \widehat x_i), a\} - \beta), (1-\tau)(\min\{ \widehat y_i + \rho - \mbb D_{\mathcal X}(\widehat x_i^p, \widehat x_i), b\} - \beta)\big\}. \] \end{enumerate} \end{corollary} If $\mathcal Y$ is multidimensional, the structure of $\ell(y,\beta)$ and $\mbb D_{\mathcal Y}$ might be exploited to identify tractable optimization reformulations. The next result focuses on the local conditional mean estimation. \begin{proposition}[Multivariate conditional mean estimation] \label{prop:cond-exp} Let $\mathcal Y = \mathbb{R}^m$ and $\ell(y, \beta) = \| y - \beta \|_2^2$. \begin{enumerate}[label=(\roman*), leftmargin=6mm] \item \label{item:cond-exp-2} Suppose that $\mbb D_{\mathcal Y}$ is a 2-norm on $\mathcal Y$, that is, $\mbb D_{\mathcal Y}(y, \widehat y) = \| y - \widehat y\|_2$. The distributionally robust local conditional estimation problem~\eqref{eq:local_DRO} is equivalent to the second-order cone program \[ \begin{array}{cll} \min & \lambda \\ \st & \beta\in \mathbb{R}^m,\;\lambda \in \mathbb{R},\;u_i \in \mathbb{R}\;\forall i \in \mathcal I_1,\;u_i \in \mathbb{R}_+\;\forall i \in \mathcal I_2,\;t_i \in \mathbb{R}_+\;\forall i \in \mathcal I \\ & \sum_{i \in \mathcal I} u_i \le 0, \quad t_i \geq \|\widehat y_i-\beta\|_2 \quad \forall i \in \mathcal I\\ & \|[t_i+\rho-\mbb D_{\mathcal X}(\widehat x_i^p, \widehat x_i)\;;\;(1/2)(1-\lambda-u_i)]\|_2\le (1/2)(1+\lambda + u_i) \quad \forall i \in \mathcal I. \end{array} \] \item \label{item:cond-exp-infty} Suppose that $\mbb D_{\mathcal Y}$ is a $\infty$-norm on $\mathcal Y$, that is, $\mbb D_{\mathcal Y}(y, \widehat y) = \| y - \widehat y\|_\infty$. The distributionally robust local conditional estimation problem~\eqref{eq:local_DRO} is equivalent to the second-order cone program \[ \begin{array}{cll} \min & \lambda \\ \st & \beta\in \mathbb{R}^m,\;\lambda \in \mathbb{R},\; T \in \mathbb{R}_+^{|\mathcal I| \times m},\;u_i \in \mathbb{R} \;\forall i \in \mathcal I_1,\;u_i \in \mathbb{R}_+\;\forall i \in \mathcal I_2 \\ & \sum_{i \in \mathcal I} u_i \le 0, \;;\; \|[T_{i1}\;;\; T_{i2}\;;\;\cdots\;;\;T_{im}\;;\;\frac{1}{2}(1-\lambda-u_i)]\|_2\leq \frac{1}{2}(1+\lambda + u_i) \;\; \forall i \in \mathcal I \\ & \hspace{-2mm}\left. \begin{array}{l} T_{ij} \leq \widehat y_{ij} - \beta_j - \rho + \mbb D_{\mathcal X}(\widehat x_i^p, \widehat x_i) \leq T_{ij} \\ T_{ij}\leq \widehat y_{ij} - \beta_j + \rho - \mbb D_{\mathcal X}(\widehat x_i^p, \widehat x_i) \le T_{ij} \end{array} \right\} \forall (i, j) \in \mathcal I \times [m], \end{array} \] where $\widehat y_{ij}$ and $\beta_j$ are the $j$-th component of $\widehat y_i$ and $\beta$, respectively. \end{enumerate} \end{proposition} Both optimization problems presented in Proposition~\ref{prop:cond-exp} can be solved in large scale by commercial optimization solvers such as MOSEK \cite{mosek}. For other multivariate conditional estimation problems, there is also a possibility of employing subgradient methods by leveraging on the next proposition \begin{proposition}[Subgradient of $f$] \label{prop:gradient} Suppose that $\mbb D_{\mathcal Y}$ is coercive and $\ell(y,\cdot)$ is convex. Under the conditions of Theorem~\ref{thm:infty-refor}, for any $\beta \in \mathbb{R}^m$, a subgradient of the function $f$ at $\beta$ is given by $ \partial f(\beta) = (\sum_{i \in \mathcal I} \alpha_i)^{-1} \sum_{i \in \mathcal I} \alpha_i \partial_\beta \ell(y_i^\star, \beta)$, where the value of $\alpha$ is as defined in Theorem~\ref{thm:infty-refor} and $y_i^\star$ satisfies $y_i^\star \in \{y_i\in \mathcal Y:\mbb D_{\mathcal Y}(y_i, \widehat y_i) \le \rho - \mbb D_{\mathcal X}(\widehat x_i^p, \widehat x_i),\;\ell(y_i^\star, \beta) = v_i^\star(\beta)\}$ for all $i \in \mathcal I$. \end{proposition} \modif{Just as an adversarial example provides a description on how to optimally perturb a data point from the adversary's viewpoint~\cite{ref:khoury2018geometry, ref:wang2019evaluating}, the worst-case distribution provides full information on how to adversarially perturb the empirical distribution $\wh{\mbb P}$. For our distributionally robust estimator, the worst-case distribution can be obtained from the result of Theorem~\ref{thm:infty-refor}. \begin{lemma}[Worst-case distribution] Fix an estimate $\beta \in \mathcal Y$. Suppose that $\rho \ge \min_{i \in [N]} \kappa_{i, \gamma}$ and let $v^\star(\beta)$ and $\alpha$ be determined as in Theorem~\ref{thm:infty-refor}. Moreover, let $y_i^\star$ satisfy $y_i^\star \in \{y_i\in \mathcal Y:\mbb D_{\mathcal Y}(y_i, \widehat y_i) \le \rho - \mbb D_{\mathcal X}(\widehat x_i^p, \widehat x_i),\;\ell(y_i^\star, \beta) = v_i^\star(\beta)\}$ for all $i \in \mathcal I$. Then the distribution \[ \mbb Q^\star = \frac{1}{N} \left( \sum_{i\in \mathcal I: \alpha_i = 1} \delta_{(\widehat x_i^p, y_i^\star)} + \sum_{i \in \mathcal I: \alpha_i = 0} \delta_{(\widehat x_i, \widehat y_i)} + \sum_{i \in [N] \backslash \mathcal I} \delta_{(\widehat x_i, \widehat y_i)} \right) \] satisfies $f(\beta) = \mathds{E}_{\mbb Q^\star} \big[ \ell(Y, \beta) | X \in \mathcal N_{\gamma}(x_0) \big]$. \end{lemma} The values of $\alpha$ calculated in Theorem~\ref{thm:infty-refor} are of indicative nature: $\alpha_i = 1$ if it is optimal to perturb the sample point $i$ to compute the worst-case conditional expected loss. The construction of the worst-case distribution is hence intuitive: it involves computing and sorting the values $v^\star_i(\beta)$, and then performing a greedy assignment in order to maximize the objective value. } \section{Probabilistic Theoretical Properties} \label{sect:guarantee} We now study the some statistical properties of our proposed estimator. Under some regularity conditions, the type-$\infty$ Wasserstein ball can be viewed as a confidence set that contains the true distribution $\mbb P$ with high probability, provided that the radius $\rho$ is chosen judiciously. The value $f(\beta^\star)$ thus constitutes a generalization bound on the out-of-sample performance of the optimal conditional estimate $\beta^\star$. This idea can be formalized as follows \begin{proposition}[Finite sample guarantee] \label{prop:finite} Suppose that $\mathcal X \times \mathcal Y$ is bounded, open, connected with a Lipschitz boundary. Suppose that the true probability measure $\mbb P$ of $(X, Y)$ admits a density function $\nu$ satisfying $\bar{\nu}^{-1} \le \nu(x, y) \le \bar \nu$ for some constant $\bar \nu \ge 1$. For any $\gamma > 0$, if \[ \rho \ge \begin{cases} C N^{-\frac{1}{2}} \log(N)^{\frac{3}{4}} & \text{when } n + m = 2, \\ C N^{-\frac{1}{n+m}} \log(N)^{\frac{1}{n+m}} & \text{otherwise}, \end{cases} \] where $C$ is a constant dependent on $\mathcal X\times\mathcal Y$ and $\bar \nu$, then for a probability of at least $1-O(N^{-c})$, where ${c\!>\!1}$ is a constant dependent on $C$, we have $\mathds{E}_{\mbb P}[\ell(Y, \beta^\star) | X \in \mathcal N_{\gamma}(x_0)] \le f(\beta^\star)$, where $\beta^\star$ is the optimal conditional estimate that solves problem~\eqref{eq:local_DRO}. \end{proposition} We now switch gear to study the properties of our estimator in the asymptotic regime, in particular, we focus on the consistency of our estimator. The interplay between the neighborhood radius $\gamma$ and the ambiguity size $\rho$ often produces tangling effects on the asymptotic convergence of the estimate. We thus showcase two exemplary setups with either $\gamma$ or $\rho$ is zero, which interestingly produce two opposite outcomes on the consistency of the estimator. This underlines the intricacy of the problem. \begin{example}[Non-consistency when $\gamma = 0$] \label{example:non-consistency} Suppose that $\gamma = 0$, $\rho \in \mathbb{R}_{++}$ be a fixed constant, $\mathcal Y = \mathbb{R}$, $\ell(y, \beta) = (y - \beta)^2$, and $\mbb D_{\mathcal Y}$ is the absolute distance. Let $ \beta_{N}^\star$ be the optimal estimate that solves~\eqref{eq:local_DRO} dependent on $\{(\widehat x_i, \widehat y_i)\}_{i=1, \ldots, N}$. If under the true distribution $\mbb P$, $X$ is independent of $Y$, $\mbb P(\mbb D_{\mathcal X}(X,x_0)\leq\rho) > 0$, $\mbb P(Y\!\geq\!0)\!=\!1$ and $\mbb P(Y\!\geq\!y)\!>\!0~ \forall y\!>\!0$, then with probability 1, we have $ \widehat \beta_{N} \rightarrow +\infty$ while $\mathds{E}_{\mbb P}[Y|X\!=\!x_0]\!<\!\infty$. \end{example} \begin{example}[Consistency when $\rho = 0$] \label{example:k-nn} Suppose that $\rho = 0$, $\mathcal Y = \mathbb{R}$, $\ell(y, \beta) = (y - \beta)^2$, $\mbb D_{\mathcal X}$ and $\mbb D_{\mathcal Y}$ are the Euclidean distance, $k_N$ is a sequence of integer. Let $\gamma$ be the $k_N$-th smallest value of $\mbb D_{\mathcal X}(x_0, \widehat x_i)$, then $\beta_{N}^\star$ that solves~\eqref{eq:local_DRO} recovers the $k_N$-nearest neighbor regression estimator. If $k_N$ satisfies $\lim_{N\rightarrow \infty} k_N = \infty$ and $\lim_{N\rightarrow \infty} k_N/N = 0$, and $\mathds{E}_{\mbb P}[Y|X=x]$ is a continuous function of $x$, then $\lim_{N\rightarrow\infty}\beta_{N}^\star = \mathds{E}_{\mbb P}[Y|X=x_0]$ by \cite[Corollary~3]{ref:stone1977consistent}. \end{example} Example~\ref{example:k-nn} suggests that if the radius $\gamma$ of the neighborhood is chosen adaptively based on the available training data, then our proposed estimator coincides with the $k$-nearest neighbor estimator, and hence consistency is inherited in a straightforward manner. The robust estimator with an ambiguity size $\rho > 0$ and an adaptive neighborhood radius $\gamma$ can thus be considered as a robustification of the $k$-nearest neighbor, which is obtained in a systematic way using the DRO framework. It is desirable to provide a descriptive connection between the distributionally robust estimator vis-\`{a}-vis some popular statistical quantities. For the local conditional mean estimation, our estimate $\beta^\star$ coincides with the conditional mean of the distribution with the highest conditional variance. This insight culminates in the next proposition and bolsters the explainability of this class of estimators. \begin{proposition}[Conditional mean estimate] \label{prop:max-var} Suppose that $\mathcal Y = \mathbb{R}$, $\ell(y, \beta) = ( y - \beta )^2$ and $\mbb D_{\mathcal Y}(\cdot, \widehat y)$ is convex, coercive for any $\widehat y$. For any $\rho \ge \min_{i \in [N]} \kappa_{i, \gamma}$, define $\mbb Q^\star$ as \begin{equation} \notag \mbb Q^\star = \arg\max_{\mbb Q \in \mathbb B_\rho^\infty, \mbb Q(X \in \mathcal N_\gamma(x_0)) > 0} ~\textrm{Variance}_{\mbb Q}(Y | X \in \mathcal N_\gamma(x_0)), \end{equation} then $\beta^\star = \mathds{E}_{\mbb Q^\star}[Y | X \in \mathcal N_\gamma(x_0)]$ is the optimal estimate that solves problem~\eqref{eq:local_DRO}. \end{proposition} \section{Numerical Experiment} \label{sect:numerical} \newcommand{{DRCME} }{{DRCME} } \newcommand{{BertEtAl} }{{BertEtAl} } In this section we compare the quality of our proposed Distributionally Robust Conditional Mean Estimator (DRCME) to $k$-nearest neighbour ($k$-NN), Nadaraya-Watson (N-W), and Nadaraya-Epanechnikov (N-E) estimators, together with the robust $k$-NN approach in \cite{ref:bertsimas2019dynamic} (BertEtAl) using a synthetic and the MNIST datasets. \begin{figure}[ht] \centering \begin{minipage}{0.48\textwidth} \centering \includegraphics[width=0.90\textwidth]{local_Error.pdf} \caption{Comparison of the mean absolute errors of conditional mean estimators for synthetic data. The gray shade shows the density of $X$.} \label{fig:local-error} \end{minipage}\hfill \begin{minipage}{0.48\textwidth} \centering \includegraphics[width=0.90\textwidth]{local_cdf.pdf} \caption{Comparison of the distributions of absolute estimation errors of conditional mean estimators for synthetic data.} \label{fig:local-cdf} \end{minipage} \vspace{-3mm} \end{figure} \subsection{Conditional Mean Estimation With Synthetic Data} In this section, we conducted $500$ independent experiments where the training set contains $N = 100$ i.i.d.~samples of $(X,Y)$ in each experiment. The marginal distribution of $X$ has piecewise constant density function $p(x)$, which is chosen as $p(x) = 100/72$ if $x\in[0,0.3]\cup[0.7,1]$ and $p(x) = 30/72$ if $x\in(0.3,0.7)$. Given $X$, the distribution of $Y$ is determined by $Y = f(X) + \varepsilon$, where $f = \sin(10\cdot x)$ and $\varepsilon$ is i.i.d.~Gaussian noise independent of $X$ with mean $0$ and variance $0.01$. The conditional mean estimation problem is challenging when $x_0$ is close to the jump points of the density function $p(x)$, that is at $x_0 = 0.3$ or $x_0 = 0.7$, because the data are gathered unequally in the neighborhoods. Thus, to test the robustness of all the estimators, we employ all the five estimators to estimate the conditional mean $\mathds{E}_{\mbb P} [Y| X = x_0]$, for $x_0 = 0.2,0.21,\ldots, 0.4$ around the jump point $x_0 = 0.3$. We select $\mbb D_{\mathcal X}(x,x') = |x-x'|$ and $\mbb D_{\mathcal Y}(y,y') = |y-y'|$. The hyperparameters of all the estimators, whose range and selection are given in Appendix~\ref{sect:add-result}, are chosen by leave-one-out cross validation. Figure \ref{fig:local-error} displays the average of the mean estimation errors taken over 500 independent runs for different values $x_0\in[0.2,0.4]$. One can observe from the figure that {DRCME} uniformly outperforms $k$-NN, {BertEtAl} for all $x_0$ of interest. When compared with N-W and N-E, we remark that {DRCME} is the most accurate estimator around the jump point of $p(x)$. As $x_0$ moves away from the location $0.3$, the performance of {DRCME} decays and becomes slightly worse than N-W as $x_0$ goes far from the jump point. Figure~\ref{fig:local-cdf} presents the cumulative distribution of the estimation errors when $x_0\in[0.28,0.32]$. The empirical error distribution of {DRCME} is stochastically smaller than that of other estimators, which reinforces that {DRCME} outperforms around the jump point in a strong sense. \subsection{Digit Estimation With MNIST Database} In this section, we compare the quality of the estimators on a digit estimation problem using the MNIST database~\cite{MNIST}. While to this date most studies have focused on out-of-sample classification performances for this dataset, here we shift our attention to the task of estimation of digits as \textbf{cardinal} quantities and are especially interested in performance at a low-data regime. Treating the labels as cardinal quantities allows us to assess the distinctive features of {DRCME} in its most simplistic form (i.e. univariate conditional mean estimation of a real random variable). Mean estimation might in fact be more relevant than classification when trying to recognize handwritten measurements where confusing a 0 with a 6 is more damaging than with a 3. \begin{table} \parbox{.48\linewidth}{ \centering \begin{tabular}{ |l|c|c|c|c| } \hline Method & H.P. &$N$=50 & $N$=100 & $N$=500\\ \hline $k$-NN & $k$&3 & 4 & 4\\ \hline N-W & $h$ & 0.022 & 0.019 & 0.015 \\ \hline N-E & $h$ & 0.087 & 0.078 & 0.068 \\ \hline {BertEtAl} & $k$ & 3 & 4 & 5 \\ & $\rho$ & 0.712 & 1.313 & 1.313\\ \hline & $\gamma$ & $h^\gamma_{1.3}(\cdot)$ & $h^\gamma_{1.3}(\cdot)$ & $h^\gamma_{1.6}(\cdot)$ \\ {DRCME} & $\rho$ & 0.13$\gamma$ & 0.13$\gamma$ & 0.06$\gamma$\\ & $\theta$ & 0.004& 0.002 & 0.001\\ \hline \end{tabular} \caption{Median of hyper-parameters (H.P.) obtained with cross-validation.}\label{table:MNISThyperParams} } \hspace{0.7cm} \parbox{.4\linewidth}{ \centering \begin{tabular}{ |l|c|c|c| } \hline Method & $N$=50 & $N$=100 & $N$=500\\ \hline $k$-NN & $24 \pm 2$ & $35 \pm 2$ & $60 \pm 1$ \\ \hline N-W & $30 \pm 2$ & $38 \pm 2$ & $65 \pm 1$ \\ \hline N-E & $26 \pm 1$ & $32 \pm 1$ & $50 \pm 1$ \\ \hline {BertEtAl} & $29 \pm 2$ & $41 \pm 2$ & $67 \pm 1$ \\ \hline {DRCME} & $36 \pm 2$ & $46 \pm 2$ & $71 \pm 1$ \\ \hline \end{tabular} \caption{Comparison of expected out-of-sample classification accuracy (in \% with 90\% confidence intervals) from rounded estimates.}\label{table:accuracyMNIST} } \vspace{-8mm} \end{table} We executed 100 experiments where training and test sets were randomly drawn without replacement from the 60,000 training examples of this dataset. Training set sizes were $N=50$, 100, or 500 while test sets' size remained at 100. Each $(x,y)$ pair is composed of the normalized vector, in $\mathbb{R}^{28^2}$ of grayscale intensities normalized so that $\|x\|_1=1$. For simplicity, we let $\mbb D_{\mathcal X}(x,\widehat x)=\|x-\widehat x\|_2$ and $\mbb D_{\mathcal Y}(y,\widehat y)=\theta|y-\widehat y|$. In each experiment, the hyper-parameters of all four methods were chosen based on a leave-one-out cross validation process. In the case of {DRCME} \!, we adapt the radius of the neighborhood $\gamma$ and $\rho$ locally at $x_0$ to account for the non-uniform density of $X$.\footnote{ Specifically, we let $\gamma=h^\gamma_i(x_0):=\kappa_{[\lfloor i\rfloor],0}+(i-\lfloor i\rfloor)(\kappa_{[\lceil i\rceil],0}-\kappa_{[\lfloor i\rfloor],0})$, where $[j]$ refers to the $j$-th smallest element while $\lfloor \cdot\rfloor$ and $\lceil \cdot\rceil$ refer to the floor and ceiling operations, i.e., the radius is set to the linear interpolation between the distance of the $\lfloor i\rfloor$-th and $\lfloor i\rfloor+1$-th closest members of the training set to $x_0$. We further let $\rho$ be proportional to $\gamma$. This lets {DRCME} reduce to $k$-NN when $\gamma=h^\gamma_k(x_0)$, $\rho=0$, and $\theta=1$.} Table \ref{table:MNISThyperParams} presents the median choice of hyper parameters for each estimator. \begin{figure}[!ht] \centering \includegraphics[width=0.9\textwidth]{MNIST_errorCDFs.pdf} \caption{Comparison of the distributions of out-of-sample absolute estimation errors of conditional mean estimators for the MNIST database under different training set sizes.} \label{fig:errorDistMNIST} \end{figure} \begin{figure}[!ht] \centering \includegraphics[width=0.49\textwidth]{adversarialFig1.pdf}\hspace{0.015\textwidth}\includegraphics[width=0.49\textwidth]{adversarialFig2.pdf} \caption{Comparison of estimations from N-W and {DRCME} on entropic regularized Wasserstein barycenters of pairs of images from the training set. Estimations are presented above each image in the format \quoteIt{(N-W,\;{DRCME} )}.} \label{fig:advMNIST} \vspace{-5mm} \end{figure} Figure \ref{fig:errorDistMNIST} presents the out-of-sample estimation error distribution of all four conditional estimators. One can quickly remark that the {DRCME} outperforms {BertEtAl} , $k$-NN, and N-E estimators, especially for low-data regime. In particular, for all three training set sizes, the distribution of error for {DRCME} stochastically dominates the three other distributions. In particular, one even notices in (c) that {DRCME} has the largest chance of reaching an exact estimation: 66\% compared to 60\%, 55\%, 30\%, and 8\% for the other estimators. This explains why {DRCME} is also the most accurate estimator when rounding it to the nearest integer as reported in Table \ref{table:accuracyMNIST}: with a margin greater than 4\% from all estimators across all $N$'s. It is worth noting that while N-W does not produce high accuracy estimate, it however has less chances of producing estimation with large errors. This is also apparent when comparing the expected type-$p$ deviation of the estimation error, i.e. $(\mathds{E}[|y-\hat{y}|^p])^{1/p}$, for each estimator. Specifically, N-W slightly outperforms {DRCME} for deviation metrics of type $p\geq 1$, e.g. with a root mean square error of 1.32 compared to 1.41 when $N=500$. On the other hand, {DRCME} significantly outperforms N-W when $p<1$ where high precision estimators are encouraged. We refer the reader to Appendix~\ref{sect:add-result} for further details. Finally, we report on an experiment that challenges the capacity of both N-W and {DRCME} estimators to be resilient to adversarial corruption of the test images. This is done by exposing the two estimators to images from the training set ($N=100$) that have been corrupted in a way that makes them resemble the closest differently-labeled image in the set.\footnote{Implementation wise, we exploit the Python Optimal Transport toolbox \cite{flamary2017pot} to compute different entropic regularized Wasserstein barycenters of the two normalized images treated as distributions.} Figure \ref{fig:advMNIST} presents several visual examples of the progressively corrupted images and the resulting N-W and {DRCME} estimations. Overall, one quickly notices how the estimation produced by {DRCME} is less sensitive to such attacks, \quoteIt{sticking} to the original label until there is substantial evidence of a new label. More examples are in Appendix~\ref{sect:add-result}. \paragraph{\bf Acknowledgments.} Material in this paper is based upon work supported by the Air Force Office of Scientific Research under award number FA9550-20-1-0397. Additional support is gratefully acknowledged from NSF grants 1915967, 1820942, 1838676 and from the China Merchant Bank.
{'timestamp': '2020-10-13T02:26:24', 'yymm': '2010', 'arxiv_id': '2010.05373', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05373'}
arxiv
\section{Introduction} Defining efficient optimization algorithms for reinforcement learning (RL) that are able to leverage a meaningful measure of similarity between policies is a longstanding and challenging problem \citep{Lee:2010,Meyerson:2016,Conti:2018a}. Many such works rely on similarity measures such as the Kullback-Leibler (KL) divergence \citep{Kullback:1951} to define procedures for updating the policy of an agent as it interacts with the environment. These are generally motivated by the need to maintain a small variation in the KL between successive updates in an off-policy context to control the variance of the importance weights used in fthe estimation of the gradient. This includes work by \cite{Kakade:2002} and \cite{Schulman:2015}, who propose to use the \textit{Fisher Natural Gradient} \citep{Amari:1997} as a way to update policies, using \textit{local} geometric information to allow larger steps in directions where policies vary less; and the work of \cite{Schulman:2017}, which relies on a \textit{global} measure of proximity using a soft KL penalty to the objective. While those methods achieve impressive performance, and the choice of the KL is well-motivated, one can still ask if it is possible to include information about the behavior of policies when measuring similarity, and whether this could lead to more efficient algorithms. \cite{Pacchiano:2019} provide a first insight into this question, representing policies using \textit{behavioral distributions} which incorporate information about the outcome of the policies in the environment. The Wasserstein Distance (WD) \citep{Villani:2009} between those behavioral distributions is then used as a similarity measure between their corresponding policies. They further propose to use such behavioral similarity as a \textit{global} soft penalty to the total objective. Hence, like the KL penalty, proximity between policies is measured globally, and does not necessarily exploit the local geometry defined by the behavioral embeddings. In this work, we show that substantial improvements can be achieved by taking into account the \textit{local} behavior of policies. We introduce new, efficient optimization methods for RL that incorporate the local geometry defined by the behavioral distributions for both policy gradient (PG) and evolution strategies (ES) approaches. Our main contributions are as follows: \textbf{1-} We leverage recent work in \citep{Li:2018a,Li:2018b,Li:2018c,Li:2019b,Chen:2018a} which introduces the notion of the Wasserstein Information Matrix to define a \textit{local behavioral similarity} measure between policies. This allows us to identify the Wasserstein Natural Gradient (WNG) as a key ingredient for optimization methods that rely on the local behavior of policies. To enable efficient estimation of WNG, we build on the recent work of \cite{Arbel:2019a}, and further extend it to cases where the re-parameterization trick is not applicable, but only the score function of the model is available. \textbf{2-} This allows us to introduce two novel methods: \emph{Wasserstein natural policy gradients} (WNPG) and \emph{Wasserstein natural evolution strategies} (WNES) which use the local behavioral structure of policies through WNG and can be easily incorporated into standard RL optimization routines. When combined in addition with a global behavioral similarity such as a WD penalty, we show substantial improvement over using the penalty alone without access to local information. We find that such WNG-based methods are especially useful on tasks in which initial progress is difficult. \textbf{3-} Finally, we demonstrate, to our knowledge, the first in-depth comparative analysis of the FNG and WNG, highlighting a clear interpretable advantage of using WNG over FNG on tasks where the optimal solution is deterministic. This scenario arises frequently in ES and in policy optimization for MDPs \citep{Puterman:2010}. This suggests that WNG could be a powerful tool for this class of problems, especially when reaching accurate solutions quickly is crucial. In Section \ref{sect:background}, we present a brief review of policy gradient approaches and the role of divergence measures as regularization penalties. In Section \ref{sect:WNG} we introduce the WNG and detail its relationship with the FNG and the use of Wasserstein penalties, and in Section \ref{sect:algos} we derive practical algorithms for applying the WNG to PG and ES. Section \ref{sect:experiments} contains our empirical results. \section{Background} \label{sect:background} {\bf Policy Gradient (PG)} methods directly parametrize a policy $\pi_{\theta}$, optimizing the parameter $\theta$ using stochastic gradient ascent on the expected total discounted reward $\mathcal{R}(\theta)$. An estimate $\hat{g}_k$ of the gradient of $\mathcal{R}(\theta)$ at $\theta_k$ can be computed by differentiating a surrogate objective $\mathcal{L}_{\theta}$ which often comes in two flavors, depending on whether training is \textit{on-policy} (left) or \textit{off-policy} (right): \begin{align} \mathcal{L}(\theta) = \hat{\mathbb{E}}\left[\log \pi_{\theta}(a_t|s_t) \hat{A}_t\right], \qquad \text{or} \qquad \mathcal{L}(\theta) = \hat{\mathbb{E}}\left[ \frac{\pi_{\theta}(a_t|s_t)}{\pi_{\theta_k}(a_t|s_t) }\hat{A}_{t} \right]. \end{align} The expectation $\hat{\mathbb{E}}$ is an empirical average over $N$ trajectories $\tau_i = (s_1^i, a_1^i,r_1^i,...,s_T^i,a_T^i,r_T^i)$ of state-action-rewards obtained by simulating from the environment using $\pi_{\theta_k}$. The scalar $\hat{A}_t$ is an estimator of the advantage function and can be computed, for instance, using \begin{align} \hat{A}_t = r_{t} + \gamma V(s_{t+1})- V(s_t) \end{align} where $\gamma\in[0,1)$ is a discount factor and $V$ is the value function often learned as a parametric function via temporal difference learning \citep{Sutton:1998}. Reusing trajectories can reduce the computational cost at the expense of increased variance of the gradient estimator \citep{Schulman:2017}. Indeed, performing multiple policy updates while using trajectories from an older policy $\pi_{\theta_{old}}$ means that the current policy $\pi_{\theta}$ can drift away from the older policy. On the other hand, the objective is obtained as an expectation under $\pi_{\theta}$ for which fresh trajectories are not available. Instead, the objective is estimated using importance sampling (by re-weighting the old trajectories according to importance weights $ \pi_{\theta}/\pi_{\theta_{old}} $ ). When $\pi_{\theta}$ is too far from $\pi_{\theta_{old}}$, the importance weight can have a large variance. This can lead to a drastic degradation of performance if done na\"ively \citep{Schulman:2017}. KL-based policy optimization (PO) aims at addressing these limitations. {\bf KL-based PO methods} ensure that the policy does not change substantially between successive updates, where change is measured by the KL divergence between the resulting action distributions. The general idea is to add either a hard KL constraint, as in TRPO \citep{Schulman:2015}, or a soft constraint, as in PPO \citep{Schulman:2017}, to encourage proximity between policies. In the first case, TRPO recovers the FNG with a step-size further adjusted using line-search to enforce the hard constraint. The FNG permits larger steps in directions where policy changes the least, thus reducing the number of updates required for optimization. In the second case, the soft constraint leads to an objective of the form: \begin{align}\label{eq:KL_PPO} \text{maximize}_{\theta}~ \mathcal{L}(\theta) - \beta\hat{\mathbb{E}}\left[\text{KL}(\pi_{\theta_k}\left(\cdot|s_t), \pi_{\theta}(\cdot|s_t) \right)\right]. \end{align} The $\text{KL}$ penalty prevents the updates from deviating too far from the current policy $\pi_{\theta_k}$, thereby controlling the variance of the gradient estimator. This allows making multiple steps with the same simulated trajectories without degradation of performance. While both methods take into account the proximity between policies as measured using the KL, they do not take into account the \emph{behavior} of such policies in the environment. Exploiting such information can greatly improve performance. {\bf Behavior-Guided Policy Optimization.} Motivated by the idea that policies can differ substantially as measured by their KL divergence but still \emph{behave} similarly in the environment, \cite{Pacchiano:2019} recently proposed to use a notion of proximity in \textit{behavior} between policies for PO. Exploiting similarity in behavior during optimization allows to take larger steps in directions where policies behave similarly despite having a large KL divergence. To capture a sense of global behavior, they define a \emph{behavioral embedding map} (BEM) $\Phi$ that maps every trajectory $\tau$ to a behavior variable $X = \Phi(\tau)$ belonging to some embedding space $\mathcal E$. The behavior variable $X$ provides a simple yet meaningful representation of each the trajectory $\tau$. As a random variable, $X$ is distributed according to a distribution $q_{\theta}$, called the \textit{behavior distribution}. Examples of $\Phi$ include simply returning the final state of a trajectory ($\Phi(\tau) = s_T$) or its concatenated actions ($\Phi(\tau) = [a_0,\dots,a_T]$). Proximity between two policies $\pi_{\theta}$ and $\pi_{\theta'}$ is then measured using the Wasserstein distance between their \textit{behavior distributions} $q_{\theta}$ and $q_{\theta'}$. Although, the KL could also be used in some cases, the Wasserstein distance has the advantage of being well-defined even for distributions with non-overlapping support, therefore allowing more freedom in choosing the embedding $\Phi$ (see \cref{sec:why_WNG}). This leads to a penalized objective that regulates behavioral proximity: \begin{align}\label{eq:proximal_expression_wasserstein} \text{maximize}_{\theta}~ \mathcal{L}(\theta) - \frac{\beta}{2}\text{W}_2(q_{\theta_k}, q_{\theta}), \end{align} where $\beta\in\mathbb{R}$ is a hyper-parameter controlling the strength of the regularization. To compute the penalty, \cite{Pacchiano:2019} use an iterative method from \cite{Genevay:2016}. This procedure is highly accurate when the Wasserstein distance changes slowly between successive updates, as ensured when $\beta$ is large. At the same time, larger values for $\beta$ also mean that the policy is updated using smaller steps, which can impede convergence. An optimal trade-off between the rate of convergence and the precision of the estimated Wasserstein distance can be achieved using an adaptive choice of $\beta$ as done in the case of PPO \cite{Schulman:2017}. For a finite value of $\beta$, the penalty accounts for \emph{global} proximity in behavior and doesn't explicitly exploit the local geometry induced by the BEM, which can further improve convergence. We introduce an efficient method that explicitly exploits the local geometry induced by the BEM through the Wasserstein Natural gradient (WNG), leading to gains in performance at a reduced computational cost. When global proximity is important to the task, we show that using the Wasserstein penalty in \cref{eq:proximal_expression_wasserstein} and optimizing it using the WNG yields more efficient updates, thus converging faster than simply optimizing \cref{eq:proximal_expression_wasserstein} using standard gradients. \section{The Wasserstein Natural Gradient} \label{sect:WNG} \label{sec:def_WNG} The Wasserstein natural gradient (WNG) \citep{Li:2018a,Li:2018b} corresponds to the steepest-ascent direction of an objective within a trust region defined by the local behavior of the Wasserstein-$2$ distance ($W_2$). The $W_2$ between two nearby densities $q_{\theta}$ and $q_{\theta + u}$ can be approximated by computing the average cost of moving every sample $X$ from $q_{\theta}$ to a new sample $X'$ \textbf{approximately} distributed according to $q_{\theta + u}$ using an \textbf{optimal} vector field of the form $\nabla_x f_u(x)$ so that $X' = X + \nabla_x f_u(X) $ (see \cref{fig:wasserstein}). Optimality of $\nabla_x f_u$ is defined as a trade-off between accurately moving mass from $q_{\theta}$ to $q_{\theta + u}$ and reducing the transport cost measured by the average squared norm of $\nabla_x f_u$ \begin{align}\label{eq:legendre_duality_wasserstein} \sup_{f_u}~ \nabla_{\theta} \mathbb{E}_{q_{\theta}}\left[ f_u(X) \right]^{\top}u -\frac{1}{2} \mathbb{E}_{q_{\theta}} \left[\Vert \nabla_x f_u(X) \Vert^2 \right], \end{align} where the optimization is over a suitable set of smooth real valued functions on $\mathcal{E}$. Hence, the optimal function $f_u$ solving \cref{eq:legendre_duality_wasserstein} defines the \textbf{optimal} vector field $\nabla_x f_{u}(x)$. Proposition \ref{prop:WIM} makes this intuition more precise and defines the Wasserstein Information Matrix. \begin{proposition}[Adapted from Defintion 3 \cite{Li:2019b}]\label{prop:WIM} The second-order Taylor expansion of $W_2$ between two nearby parametric probability distributions $q_{\theta}$ and $q_{\theta+u}$ is given by \begin{align}\label{eq:second_order_exansion} W_2^2(q_{\theta},q_{\theta+u}) = u^{\top}G(\theta)u + o(\Vert u \Vert^2) \end{align} where $G(\theta)$ is the Wasserstein Information Matrix (WIM), with components in a basis $(e_1,...,e_p)$ \begin{align}\label{eq:WIM} G_{j,j'}(\theta) = \mathbb{E}_{q_{\theta}}\left[\nabla_x f_{j}(X)^{\top} \nabla_x f_{j'}(X)\right]. \end{align} The functions $f_j$ solve \cref{eq:legendre_duality_wasserstein} with $u$ chosen as $e_j$. Moreover, for any given $u$, the solution $f_u$ to \cref{eq:legendre_duality_wasserstein} satisfies $\mathbb{E}_{\theta}[\Vert \nabla_x f_u(X)\Vert^2 ] = u^{\top}G(\theta)u$. \end{proposition} When $q_{\theta}$ and $q_{\theta+u}$ are the behavioral embedding distributions of two policies $\pi_{\theta}$ and $\pi_{\theta+u}$, the function $f_u$ allows to transport behavior from a policy $\pi_{\theta}$ to a behavior as close as possible to $\pi_{\theta+u}$ with the least cost. We thus refer to $f_u$ as the \textit{behavioral transport function}. The function $f_u$ determines how hard it is to change behavior \textbf{locally} from policy $\pi_{\theta}$ in a direction $u$, thus providing a tool to find update directions $u$ with either \textit{maximal} or \textit{minimal} change in behavior. Probing all directions in a basis $(e_1,...,e_p)$ of parameters allows us to construct the WIM $G(\theta)$ in \cref{eq:WIM} which summarizes proximity in behavior along all possible directions $u$ using $ u^{\top}G(\theta) u = \mathbb{E}_{q_{\theta}}[ \Vert \nabla_x f_u(X) \Vert^2 ] $. For an objective $\mathcal{L}(\theta)$, such as the expected total reward of a policy, the Wasserstein natural gradient (WNG) is then defined as the direction $u$ that locally increases $\mathcal{L}(\theta+u)$ the most with the least change in behavior as measured by $f_u$. Formally, the WNG is related to the usual Euclidean gradient $g = \nabla_{\theta}\mathcal{L}(\theta) $ by \begin{align}\label{eq:WNG} g^{W} = \mathop{\mathbox{argmax}}_u 2g^{\top}u- u^{\top}G(\theta)u. \end{align} From \cref{eq:WNG}, the WNG can be expressed in closed-form in terms of $G(\theta)$ and $g$ as $g^{W} = G^{-1}(\theta)g$. Hence, WNG ascent is simply performed using the update equation $\theta_{k+1} = \theta_k + \lambda g^W_k $. We'll see in \cref{sec:efficient_wng} how to estimate WNG efficiently without storing or explicitly inverting the matrix $G$. Next, we discuss the advantages of using WNG over other methods. \subsection{Why use the Wasserstein Natural Gradient?}\label{sec:why_WNG} To illustrate the advantages of the WNG, we consider a simple setting where the objective is of the form $\mathcal{L}(\theta) = \mathbb{E}_{q_{\theta}}[\psi(x)]$, with $q_{\theta}$ being a gaussian distribution. The optimal solution in this example is a deterministic point mass located at the global optimum $x^{\star}$ of the function $\psi(x)$. This situation arises systematically in the context of ES when using a gaussian noise distribution with learnable mean and variance. Moreover, the optimal policy of a Markov Decision Processes (MDP) is necessarily deterministic \citep{Puterman:2010}. Thus, despite its simplicity, this example allows us to obtain closed-form expressions for all methods while capturing a crucial property in many RL problems (deterministic optimal policies) which, as we will see, results in differences in performance. \begin{figure}[!t] \centering \includegraphics[width=\textwidth]{figs/all_toy_dim_100_v4} \caption{ Different optimization methods using an objective $\mathcal{L}(\theta) = \mathbb{E}_{q_{\theta}}[\psi(x)]$ where $q_{\theta}$ is a gaussian of $100$ dimensions with parameters $\theta= (\bm{\mu}, v)$. Here $\bm{\mu}$ in bold is the mean vector, $v$ parameterizes the covariance matrix $\Sigma$, which is chosen to be diagonal. Two parameterizations for the covariance matrix are considered: $\Sigma_{ii} = e^{v_i}$ (log-diagonal) and $\Sigma_{ii} = v_i$ (diagonal). $\psi(x)$ is the sum of $sinc$ functions over all dimensions. Training is up to 4000 iterations, with $\lambda = .9$ and $\beta =.1$ unless they are varied. In \cref{fig:toys} (c), $\sigma$ and $\mu$ refer to the std of the first component of the gaussian $\sigma= \sqrt{\Sigma_{11}}$ and $\mu = \bm{\mu}_1$. More details about the experimental setting are provided in \cref{sec:exp_setting_toy}. } \label{fig:toys} \end{figure} \paragraph{Wasserstein natural gradient vs Fisher natural gradient} While \cref{fig:toys} (c) shows that both methods seem to reach the same solution, a closer inspection of the loss, as shown in \cref{fig:toys} (d) and (e) for two different parameterizations of $q_{\theta}$, shows that the FNG is faster at first, then slows down to reach a final error of $10^{-4}$. On the other hand, WNG is slower at first then transitions suddenly to an error of $10^{-8}$. The optimal solution being deterministic, the variance of the gaussian $q_{\theta}$ needs to shrink to $0$. In this case, the KL blows up, while the $W_2$ distance remains finite. As the natural gradient methods are derived from those two divergences (\cref{prop:proximal_limit} of \cref{sec:wng_appendix}), they inherit the same behavior. This explains why, unlike the WNG, the FNG doesn't achieve the error of $10^{-8}$. Beyond this example, when the policy $\pi_{\theta}$ is defined only implicitly using a generative network, as in \cite{Tang:2019}, the FNG and KL penalty are ill-defined since $\pi_{\theta_k}$ and $\pi_{\theta_{k+1}}$ might have non-overlapping supports. However, the WNG remains well-defined (see \cite{Arbel:2019a}) and allows for more flexibility in representing policies, such as with behavioral embeddings. \paragraph{Wasserstein penalty vs Wasserstein natural gradient} The Wasserstein penalty \cref{eq:proximal_expression_wasserstein} encourages \textit{global} proximity between updates $q_{\theta_k}$. For small values of the penalty parameter $\beta$, the method behaves like standard gradient descent (\cref{fig:toys} (a)). As $\beta$ increases, the penalty encourages more local updates and thus incorporates more information about the local geometry defined by $q_{\theta}$. In fact, it recovers the WNG direction (\cref{prop:proximal_limit} of \cref{sec:wng_appendix}) albeit with an infinitely small step-size which is detrimental to convergence of the algorithm. To avoid slowing-down, there is an intricate balance between the step-size and penalty $\beta$ that needs to be maintained \citep{Schulman:2017}. All of these issues are avoided when directly using the WNG, as shown in \cref{fig:toys} (a), which performs the best and tolerates the widest range of step-sizes \cref{fig:toys} (f). Moreover, when using the \textit{log-diagonal parameterization} as in \cref{fig:toys} (d,a), the WNGD (in red) achieves an error of 1e-8, while $W_2$-penalty achieves a larger error of order 1e-0 for various values of the $\beta$. When using the \textit{diagonal parameterization} instead, as shown in \cref{fig:toys} (e), both methods achieve a similar error of 1e-6. This discrepancy in performance highlights the robustness of WNG to parameterization of the model. {\bf Combining WNG and a Wasserstein penalty.} The global proximity encouraged by a $W_2$ penalty can be useful on its own, for instance, to explicitly guarantee policy improvement as in \cite[Theorem 5.1]{Pacchiano:2019}. However, this requires estimating the $W_2$ at every iteration, which can be costly. Using WNG instead of the usual gradient can yield more efficient updates, thus reducing the number of time $W_2$ needs to be estimated. The speed-up can be understood as performing second-order optimization on the $W_2$ penalty since the WNG arises precisely from a second-order expansion of the $W_2$ distance, as shown in \cref{sec:def_WNG} (See also Example 2 in \cite{Arbel:2019a}). \section{Policy Optimization using Behavioral Geometry} \label{sect:algos} We now present practical algorithms to exploit the behavioral geometry induced by the embeddings $\Phi$. We begin by describing how to efficiently estimate the WNG. \paragraph{Efficient estimation of the WNG}\label{sec:efficient_wng} can be performed using kernel methods, as shown in \cite{Arbel:2019a} in the case where the re-parametrization trick is applicable. This is the case, if for instance, the behavioral variable is the concatenation of actions $X = [ a_0,...,a_T]$ and if actions are sampled from a gaussian with mean and variance parameterized by a neural network, as is often done in practice for real-valued actions. Then $X$ can be expressed as $X = B_{\theta}(Z) $ where $B_{\theta}$ is a known function and $Z$ is an input sample consisting in the concatenation of states $[s_0,...,s_T]$ and the gaussian noise used to generate the actions. However, the proposed algorithm is not readily applicable if for instance the behavioral variable $X$ is a function of the reward. We now introduce a procedure that extends the previous method to more general cases, including those where only the score $\nabla_{\theta}\log q_{\theta} $ is available without an explicit re-parametrization trick. The core idea is to approximate the functions $f_{e_j}$ defining $G(\theta_k)$ in \cref{eq:WIM} using a linear combinations of user-specified basis functions $(h_1(x),...,h_M(x))$: \begin{align}\label{eq:linear_combination} \hat{f}_{e_j}(x) = \sum_{m=1}^M \alpha_{m}^j h_m(x), \end{align} The number $M$ controls the computational cost of the estimation and is typically chosen on the order of $M=10$. The basis can be chosen to be \textit{data-dependent} using kernel methods. More precisely, we use the same approach as in \cite{Arbel:2019a}, where we first subsample $M$ data-points $Y_m$ from a batch of $N$ variables $X_n$ and $M$ indices $i_m$ from $\{1,...,d\}$ where $d$ is the dimension of $X_n$. Then, each basis can of the form $h_m(x) = \partial_{i_m}K(Y_m,x) $ where $K$ is a positive semi-definite kernel, such as the gaussian kernel $K(x,y) = \exp(- \frac{\Vert x-y \Vert^2}{\sigma^2} )$. This choice of basis allows us to provide guarantees for functions $f_j$ in terms of the batch size $N$ and the number of basis points $M$ \cite[Theorem 7]{Arbel:2019a}. Plugging-in each $\hat{f}_{j}$ in the transport cost problem \cref{eq:legendre_duality_wasserstein} yields a quadratic problem of dimension $M$ in the coefficients $\alpha^j$: \begin{align*} \text{maximize}_{\alpha^j}~ 2J_{.,j}\alpha^{j} - (\alpha^j)^{\top}L\alpha^j \end{align*} where $L$ is a square matrix of size $M\times M$ independent of the index $j$ and $J$ is a Jacobian matrix of shape $ M\times p $ with rows given by $ J_{m,.} = \nabla_{\theta}\mathbb{E}_{q_{\theta_k}}[h_m(X)]$. There are two expressions for $J$, depending on the applicability of the re-parametrization trick or the availability of the score \begin{align}\label{eq:jacobian} J_{m,.} = \hat{\mathbb{E}}_{q_{\theta}}[\nabla_x h_m(X) \nabla_{\theta} B_{\theta}(Z)]\qquad \text{or}\qquad J_{m,.} = \hat{\mathbb{E}}_{q_{\theta}}[\nabla_{\theta}\log q_{\theta}(X)h_m(X)] \end{align} Computing $J$ can be done efficiently for moderate size $M$ by first computing a surrogate vector of $V$ of size $M$ whose Jacobian recovers $J$ using automatic differentiation software: \begin{align}\label{eq:surrogate_loss} V_m = \hat{\mathbb{E}}_{q_{\theta}}\left[ h_m(X_n)\right] , \qquad \text{or} \qquad V_m = \hat{\mathbb{E}}_{q_{\theta}}\left[ \log q_{\theta}(X_n) h_m(X_n)\right]. \end{align} The optimal coefficients $\alpha^{j}$ are then simply expressed as $\alpha = L^{\dagger}J$. Plugging-in the optimal functions in the expression of the Wasserstein Information Matrix (\cref{eq:WIM}), yields a low rank approximation of $G$ of the form $ \hat{G} = J^{\top}L^{\dagger} J $. By adding a small diagonal perturbation matrix $\epsilon I$, it is possible efficiently compute $ (\hat{G} + \epsilon I)^{-1}\hat{g} $ using a generalized Woodbury matrix identity which yields an estimator for the Wasserstein Natural gradient \begin{align}\label{eq:wng_estimator} \hat{g}^{W} = \frac{1}{\epsilon}\left( \hat{g} - J^{\top}\left( JJ^{\top} + \epsilon L \right)^{\dagger}J\hat{g} \right). \end{align} The pseudo-inverse is only computed for a matrix of size $M$. Using the Jacobian-vector product, \cref{eq:wng_estimator} can be computed without storing large matrices $G$ as shown in \cref{alg:KWNG_3}. \paragraph{Wasserstein Natural Policy Gradient (WNPG). It is possible to incorporate local information about the behavior of a policy in standard algorithms for policy gradient as summarized in \cref{alg:WNPG}. In its simplest form, one first needs to compute the gradient $\hat{g}_k$ of the objective $\mathcal{L}(\theta_k)$ using, for instance, the REINFORCE estimator computed using $N$ trajectories $\tau_n$. The trajectories are then used to compute the BEMs which are fed as input, along with the gradient $\hat{g}_k$ to get an estimate of the WNG $g^W_{k}$. Finally, the policy can be updated in the direction of $g^W_k$. \cref{alg:WNPG} can also be used in combination with an explicit $W_2$ penalty to control non-local changes in behavior of the policy thus ensuring a policy improvement property as in \cite[Theorem 5.1]{Pacchiano:2019}. In that case, WNG enhances convergence by acting as a second-order optimizer, as discussed in \cref{sec:why_WNG}. The standard gradient $\hat{g}_k$ in \cref{alg:WNPG} is then simply replaced by the one computed in \cite[Algorithm 3]{Pacchiano:2019}. In \cref{sect:experiments}, we show that this combination, which we call behavior-guided WNPG (BG-WNPG), leads to the best overall performance. \begin{algorithm}[t] \caption{Wasserstein Natural Policy Gradient}\label{alg:WNPG} \begin{algorithmic}[1] \STATE \textbf{Input} Initial policy $\pi_{\theta_0}$ \FOR{ iteration $k=1,2,...$} \STATE Obtain $N$ rollouts $\{\tau\}_{n=1}^N$ of length $T$ using policy $\pi_{\theta_k}$ \STATE Compute loss $\mathcal{L}(\theta_k)$ in a forward pass \STATE Compute gradient $\hat{g}_k$ in the backward pass on $\mathcal{L}(\theta_k)$ \STATE Compute Behavioral embeddings $\{X_n = \Phi(\tau^n)\}_{n=1}^N$ \STATE Compute WNG $\hat{g}^W_k$ using \cref{alg:KWNG_3} with samples $\{X_n\}_{n=1}^N$ and gradient estimate $\hat{g}_k$. \STATE Update policy using: $\theta_{k+1} = \theta_k + \lambda \hat{g}_{k}^{W}$. \ENDFOR \end{algorithmic} \end{algorithm} \paragraph{Wasserstein Natural Evolution Strategies (WNES).} \label{sec:WNES} ES treats the total reward observed on a trajectory under policy $\pi_{\theta}$ as a black-box function $\mathcal{L}(\theta)$ \citep{Salimans:2017,Mania:2018,Choromanski:2020}. Evaluating it under $N$ policies whose parameters $\widetilde{\theta}^n$ are gaussian perturbations centered around $\theta_k$ and with variance $\sigma$ can give an estimate of the gradient of $\mathcal{L}(\theta_k)$: \begin{align}\label{eq:ES_gradient} \hat{g}_k = \frac{1}{N\sigma} \sum_{n=1}^N \left(\mathcal{L}(\widetilde{\theta}^n)- \mathcal{L}(\theta_k)\right)(\widetilde{\theta}^n-\theta_k). \end{align} Instead of directly updating the policy using \cref{eq:ES_gradient}, it is possible to encourage either proximity or diversity in behavior using the embeddings $X_n = \Phi(\tau_n)$ of the trajectories $\tau_n$ generated for each perturbed policy $\pi_{\widetilde{\theta}_n}$. Those embeddings can be used as input to \cref{alg:KWNG_3} (see appendix), along with \cref{eq:ES_gradient} to estimate the $\hat{g}^W_k$, which captures similarity in behavior. The algorithm remains unchanged except for the estimation of the Jacobian $J$ of \cref{eq:jacobian} which becomes \begin{align}\label{eq:ES_jacobian} J_{m,.} = \frac{1}{N\sigma} \sum_{n=1}^N h_m(X_n)(\widetilde{\theta}^n-\theta_k). \end{align} The policy parameter can then be updated using an interpolation between $\hat{g}_k$ and the WNG $\hat{g}_k^W$, i.e., \begin{align}\label{eq:update_gradient_ES} \Delta \theta_k \propto (1-\delta)\hat{g}_k + \delta \hat{g}_k^W \end{align} with $\delta\leq 1$ that can also be negative. Positive values for $\delta$ encourage proximity in behavior, the limit case being $\delta=1$ where a full WNG step is taken. Negative values encourage repulsion and therefore need to compensated by $\hat{g}_k$ to ensure overall policy improvement. \cref{alg:WNES} summarizes the whole procedure, which can be easily adapted from existing ES implementations by calling a variant of \cref{alg:KWNG_3}. In particular, it can also be used along with an explicit $W_2$ penalty, in which case the proposed algorithm in \cite{Pacchiano:2019} is used to estimate the standard gradient $\hat{g}_k$ of the penalized loss. Then the policy is updated using \cref{eq:update_gradient_ES} instead of $\hat{g}_k$. We refer to this approach as behavior-guided WNES (BG-WNES). \begin{algorithm}[!t] \caption{Wasserstein Natural Evolution Strategies}\label{alg:WNES} \begin{algorithmic}[1] \STATE \textbf{Input} Initial policy $\pi_{\theta_0}$, $\alpha>0$, $\delta\leq 1$ \FOR{ iteration $k=1,2,...$} \STATE Sample $\epsilon_1,\dots,\epsilon_n \sim \mathcal N(0, I)$. \STATE Perform rollouts $\{\tau_n\}_{n-1}^{N}$ of length $T$ using the perturbed parameters $\{\widetilde{\theta}^n = \theta_k + \sigma \epsilon_n\}_{n=1}^{N}$ and compute behavioral embeddings $\{X_n = \Phi(\tau^n)\}_{n=1}^N$ \STATE Compute gradient estimate of $\mathcal{L}(\widetilde{\theta}^n)$ using \cref{eq:ES_gradient} and trajectories $\{\tau^{n}\}_{n=1}^N$. \STATE Compute Jacobian matrix $J$ appearing in \cref{alg:KWNG_3} using \cref{eq:ES_jacobian}. \STATE Compute WNG $\hat{g}^W_k$ using \cref{alg:KWNG_3}, with samples $\{X_n\}_{i=1}^N$ and computed $\hat{g}_k$ and $J$. \STATE Update policy using \cref{eq:update_gradient_ES}. \ENDFOR \end{algorithmic} \end{algorithm} \begin{figure}[!t] \centering \includegraphics[width=0.99\textwidth]{figs/pg_all.pdf} \caption{\textbf{WNG-based algorithms provide large gains on tasks where initial progress is difficult.} The performance mean $\pm$ standard deviation is plotted versus time steps for 5 random seeds on each task.} \label{fig:pg_exps} \end{figure} \section{Experiments}\label{sect:experiments} We now test the performance of our estimators for both policy gradients (PG) and evolution strategies (ES) against their associated baseline methods. We show that in addition to an improved computational efficiency, our approach can effectively utilize the geometry induced by a Wasserstein penalty to improve performance, particularly when the optimization problem is ill-conditioned. Further experimental details can be found in the appendix, and our code is available online\footnote{\texttt{https://github.com/tedmoskovitz/WNPG}}. {\bf Policy Gradients.} We first apply WNPG and BG-WNPG to challenging tasks from OpenAI Gym \citep{Brockman:2016} and Roboschool (RS). We compare performance against behavior-guided policy gradients (BGPG), \citep{Pacchiano:2019}, PPO with clipped surrogate objective \citep{Schulman:2017} (PPO (Clip)), and PG with no trust region (None). From \cref{fig:pg_exps}, we can see that BGPG outperforms the corresponding KL-based method (PPO) and vanilla PG, as also demonstrated in the work of \cite{Pacchiano:2019}. Our method (WNPG) matches or exceeds final performance of BGPG on all tasks. Moreover, combining both (BG-WNPG) produces the largest gains on all environments. Final mean rewards are reported in \cref{table:pg_results}. It is also important to note that WNG-based methods appear to offer the biggest advantage on tasks where initial progress is difficult. To investigate this further, we computed the hessian matrix at the end of training for each task and measured the ratios of its largest eigenvalue to each successive eigenvalue (\cref{fig:cond_number}). Larger ratios indicate ill-conditioning, and it is significant that WNG methods produce the greatest improvement on the environments with the poorest conditioning. This is consistent with the findings in \cite{Arbel:2019a} that showed WNG to perform most favorably compared to other methods when the optimization problem is ill-conditioned, and implies a useful heuristic for gauging when WNG-based methods are most useful for a given problem. \begin{wrapfigure}{R}{0.5\textwidth} \centering \includegraphics[trim={0.5cm 0.2cm 0.5cm 0.2cm}, clip, width=0.85\textwidth]{figs/condition_nums.pdf} \caption{Condition numbers for different tasks.} \label{fig:cond_number} \end{wrapfigure} \vspace{-.3cm} \paragraph{Evolution Strategies} To test our estimator for WNES, as well as BG-WNES, we applied our approach to the environment introduced by \cite{Pacchiano:2019}, designed to test the ability of behavior-guided learning to succeed despite deceptive rewards. During the task, the agent receives a penalty proportional to its distance from a goal, but a wall is placed directly in the agent's path (\cref{fig:quad_env_viz}). This barrier induces a local maximum in the objective---a na\"ive agent will simply walk directly towards the goal and get stuck at the barrier. The idea is that the behavioral repulsion fostered by applying a positive coefficient to the Wasserstein penalty ($\beta > 0$) will encourage the agent to seek novel policies, helping it to eventually circumvent the wall. As in \cite{Pacchiano:2019}, we test two agents, a simple point and a quadruped. We then compare our method with vanilla ES as described by \cite{Salimans:2017}, ES with gradient norm clipping, BGES \citep{Pacchiano:2019}, and NSR-ES \citep{Conti:2018}. In \cref{fig:es_exps}, we can see that WNES and BG-WNES improve over the baselines for both agents. To test that the improvement shown by BG-WNES wasn't simply a case of additional ``repulsion'' supplied by the WNG to BGES, we also tested BGES with an increased $\beta = 0.75$, compared to the default of $0.5$. This resulted in a decrease in performance, attesting to the unique benefit provided by the WNES estimator. \begin{figure}[!t] \centering \includegraphics[width=0.99\textwidth]{figs/es_exps.pdf} \caption{\textbf{WNES methods more reliably overcome local maxima.} Results obtained on the point (a) and quadruped (b) tasks. The mean $\pm$ standard deviation is plotted across 5 random seeds.} \label{fig:es_exps} \end{figure} {\bf Computational Efficiency} We define the \emph{computational efficiency} of an algorithm as the rate with which it accumulates reward relative to its runtime. To test the computational efficiency of our approach, we plotted the total reward divided by wall clock time obtained by each agent for each task (Fig. \ref{fig:rpm}). Methods using a WNG estimator were the most efficient on each task for both PG and ES agents. On several environments used for the policy gradient tasks, the added cost of BG-WNPG reduced its efficiency, despite having the highest absolute performance. \begin{figure}[!t] \centering \includegraphics[width=0.99\textwidth]{figs/rpm.pdf} \caption{\textbf{WNG methods improve computational efficiency.} Average reward per minute is plotted for both gradient tasks (left) and ES tasks (right) for the runs depicted above.} \label{fig:rpm} \end{figure} \section{Conclusion} Explicit regularization using divergence measures between policy representations has been a common theme in recent work on policy optimization for RL. While prior works have previously focused on the KL divergence, \cite{Pacchiano:2019} showed that a Wasserstein regularizer over behavioral distributions provides a powerful alternative framework. Both approaches implicitly define a form of natural gradient, depending on which divergence measure is chosen. Through the introduction of WNPG and WNES, we demonstrate that directly estimating the natural gradient of the un-regularized objective can deliver greater performance at lower computational cost. These algorithms represent novel extensions of previous work on the WNG to problems where the re-parameterization trick is not available, as well as to black-box methods like ES. Moreover, using the WNG in conjunction with a WD penalty allows the WNG to take advantage of the local geometry induced by the regularization, further improving performance. We also provide a novel comparison between the WNG and FNG, showing that the former has significant advantages on certain problems. We believe this framework opens up a number of avenues for future work. Developing a principled way to identify useful behavioral embeddings for a given RL task would allow to get the highest benefit form WNPG and WNES. From a theoretical perspective, it would be useful to characterize the convergence boost granted by the combination of explicit regularization and the corresponding natural gradient approach. \paragraph{Acknowledgments} The authors would like to thank Jack Parker-Holder for sharing his code for BGPG and BGES, as well as colleagues at Gatsby for useful discussions. \newpage \section{Introduction} Defining efficient optimization algorithms for reinforcement learning (RL) that are able to leverage a meaningful measure of similarity between policies is a longstanding and challenging problem \citep{Lee:2010,Meyerson:2016,Conti:2018a}. Many such works rely on similarity measures such as the Kullback-Leibler (KL) divergence \citep{Kullback:1951} to define procedures for updating the policy of an agent as it interacts with the environment. These are generally motivated by the need to maintain a small variation in the KL between successive updates in an off-policy context to control the variance of the importance weights used in fthe estimation of the gradient. This includes work by \cite{Kakade:2002} and \cite{Schulman:2015}, who propose to use the \textit{Fisher Natural Gradient} \citep{Amari:1997} as a way to update policies, using \textit{local} geometric information to allow larger steps in directions where policies vary less; and the work of \cite{Schulman:2017}, which relies on a \textit{global} measure of proximity using a soft KL penalty to the objective. While those methods achieve impressive performance, and the choice of the KL is well-motivated, one can still ask if it is possible to include information about the behavior of policies when measuring similarity, and whether this could lead to more efficient algorithms. \cite{Pacchiano:2019} provide a first insight into this question, representing policies using \textit{behavioral distributions} which incorporate information about the outcome of the policies in the environment. The Wasserstein Distance (WD) \citep{Villani:2009} between those behavioral distributions is then used as a similarity measure between their corresponding policies. They further propose to use such behavioral similarity as a \textit{global} soft penalty to the total objective. Hence, like the KL penalty, proximity between policies is measured globally, and does not necessarily exploit the local geometry defined by the behavioral embeddings. In this work, we show that substantial improvements can be achieved by taking into account the \textit{local} behavior of policies. We introduce new, efficient optimization methods for RL that incorporate the local geometry defined by the behavioral distributions for both policy gradient (PG) and evolution strategies (ES) approaches. Our main contributions are as follows: \textbf{1-} We leverage recent work in \citep{Li:2018a,Li:2018b,Li:2018c,Li:2019b,Chen:2018a} which introduces the notion of the Wasserstein Information Matrix to define a \textit{local behavioral similarity} measure between policies. This allows us to identify the Wasserstein Natural Gradient (WNG) as a key ingredient for optimization methods that rely on the local behavior of policies. To enable efficient estimation of WNG, we build on the recent work of \cite{Arbel:2019a}, and further extend it to cases where the re-parameterization trick is not applicable, but only the score function of the model is available. \textbf{2-} This allows us to introduce two novel methods: \emph{Wasserstein natural policy gradients} (WNPG) and \emph{Wasserstein natural evolution strategies} (WNES) which use the local behavioral structure of policies through WNG and can be easily incorporated into standard RL optimization routines. When combined in addition with a global behavioral similarity such as a WD penalty, we show substantial improvement over using the penalty alone without access to local information. We find that such WNG-based methods are especially useful on tasks in which initial progress is difficult. \textbf{3-} Finally, we demonstrate, to our knowledge, the first in-depth comparative analysis of the FNG and WNG, highlighting a clear interpretable advantage of using WNG over FNG on tasks where the optimal solution is deterministic. This scenario arises frequently in ES and in policy optimization for MDPs \citep{Puterman:2010}. This suggests that WNG could be a powerful tool for this class of problems, especially when reaching accurate solutions quickly is crucial. In Section \ref{sect:background}, we present a brief review of policy gradient approaches and the role of divergence measures as regularization penalties. In Section \ref{sect:WNG} we introduce the WNG and detail its relationship with the FNG and the use of Wasserstein penalties, and in Section \ref{sect:algos} we derive practical algorithms for applying the WNG to PG and ES. Section \ref{sect:experiments} contains our empirical results. \section{Background} \label{sect:background} {\bf Policy Gradient (PG)} methods directly parametrize a policy $\pi_{\theta}$, optimizing the parameter $\theta$ using stochastic gradient ascent on the expected total discounted reward $\mathcal{R}(\theta)$. An estimate $\hat{g}_k$ of the gradient of $\mathcal{R}(\theta)$ at $\theta_k$ can be computed by differentiating a surrogate objective $\mathcal{L}_{\theta}$ which often comes in two flavors, depending on whether training is \textit{on-policy} (left) or \textit{off-policy} (right): \begin{align} \mathcal{L}(\theta) = \hat{\mathbb{E}}\left[\log \pi_{\theta}(a_t|s_t) \hat{A}_t\right], \qquad \text{or} \qquad \mathcal{L}(\theta) = \hat{\mathbb{E}}\left[ \frac{\pi_{\theta}(a_t|s_t)}{\pi_{\theta_k}(a_t|s_t) }\hat{A}_{t} \right]. \end{align} The expectation $\hat{\mathbb{E}}$ is an empirical average over $N$ trajectories $\tau_i = (s_1^i, a_1^i,r_1^i,...,s_T^i,a_T^i,r_T^i)$ of state-action-rewards obtained by simulating from the environment using $\pi_{\theta_k}$. The scalar $\hat{A}_t$ is an estimator of the advantage function and can be computed, for instance, using \begin{align} \hat{A}_t = r_{t} + \gamma V(s_{t+1})- V(s_t) \end{align} where $\gamma\in[0,1)$ is a discount factor and $V$ is the value function often learned as a parametric function via temporal difference learning \citep{Sutton:1998}. Reusing trajectories can reduce the computational cost at the expense of increased variance of the gradient estimator \citep{Schulman:2017}. Indeed, performing multiple policy updates while using trajectories from an older policy $\pi_{\theta_{old}}$ means that the current policy $\pi_{\theta}$ can drift away from the older policy. On the other hand, the objective is obtained as an expectation under $\pi_{\theta}$ for which fresh trajectories are not available. Instead, the objective is estimated using importance sampling (by re-weighting the old trajectories according to importance weights $ \pi_{\theta}/\pi_{\theta_{old}} $ ). When $\pi_{\theta}$ is too far from $\pi_{\theta_{old}}$, the importance weight can have a large variance. This can lead to a drastic degradation of performance if done na\"ively \citep{Schulman:2017}. KL-based policy optimization (PO) aims at addressing these limitations. {\bf KL-based PO methods} ensure that the policy does not change substantially between successive updates, where change is measured by the KL divergence between the resulting action distributions. The general idea is to add either a hard KL constraint, as in TRPO \citep{Schulman:2015}, or a soft constraint, as in PPO \citep{Schulman:2017}, to encourage proximity between policies. In the first case, TRPO recovers the FNG with a step-size further adjusted using line-search to enforce the hard constraint. The FNG permits larger steps in directions where policy changes the least, thus reducing the number of updates required for optimization. In the second case, the soft constraint leads to an objective of the form: \begin{align}\label{eq:KL_PPO} \text{maximize}_{\theta}~ \mathcal{L}(\theta) - \beta\hat{\mathbb{E}}\left[\text{KL}(\pi_{\theta_k}\left(\cdot|s_t), \pi_{\theta}(\cdot|s_t) \right)\right]. \end{align} The $\text{KL}$ penalty prevents the updates from deviating too far from the current policy $\pi_{\theta_k}$, thereby controlling the variance of the gradient estimator. This allows making multiple steps with the same simulated trajectories without degradation of performance. While both methods take into account the proximity between policies as measured using the KL, they do not take into account the \emph{behavior} of such policies in the environment. Exploiting such information can greatly improve performance. {\bf Behavior-Guided Policy Optimization.} Motivated by the idea that policies can differ substantially as measured by their KL divergence but still \emph{behave} similarly in the environment, \cite{Pacchiano:2019} recently proposed to use a notion of proximity in \textit{behavior} between policies for PO. Exploiting similarity in behavior during optimization allows to take larger steps in directions where policies behave similarly despite having a large KL divergence. To capture a sense of global behavior, they define a \emph{behavioral embedding map} (BEM) $\Phi$ that maps every trajectory $\tau$ to a behavior variable $X = \Phi(\tau)$ belonging to some embedding space $\mathcal E$. The behavior variable $X$ provides a simple yet meaningful representation of each the trajectory $\tau$. As a random variable, $X$ is distributed according to a distribution $q_{\theta}$, called the \textit{behavior distribution}. Examples of $\Phi$ include simply returning the final state of a trajectory ($\Phi(\tau) = s_T$) or its concatenated actions ($\Phi(\tau) = [a_0,\dots,a_T]$). Proximity between two policies $\pi_{\theta}$ and $\pi_{\theta'}$ is then measured using the Wasserstein distance between their \textit{behavior distributions} $q_{\theta}$ and $q_{\theta'}$. Although, the KL could also be used in some cases, the Wasserstein distance has the advantage of being well-defined even for distributions with non-overlapping support, therefore allowing more freedom in choosing the embedding $\Phi$ (see \cref{sec:why_WNG}). This leads to a penalized objective that regulates behavioral proximity: \begin{align}\label{eq:proximal_expression_wasserstein} \text{maximize}_{\theta}~ \mathcal{L}(\theta) - \frac{\beta}{2}\text{W}_2(q_{\theta_k}, q_{\theta}), \end{align} where $\beta\in\mathbb{R}$ is a hyper-parameter controlling the strength of the regularization. To compute the penalty, \cite{Pacchiano:2019} use an iterative method from \cite{Genevay:2016}. This procedure is highly accurate when the Wasserstein distance changes slowly between successive updates, as ensured when $\beta$ is large. At the same time, larger values for $\beta$ also mean that the policy is updated using smaller steps, which can impede convergence. An optimal trade-off between the rate of convergence and the precision of the estimated Wasserstein distance can be achieved using an adaptive choice of $\beta$ as done in the case of PPO \cite{Schulman:2017}. For a finite value of $\beta$, the penalty accounts for \emph{global} proximity in behavior and doesn't explicitly exploit the local geometry induced by the BEM, which can further improve convergence. We introduce an efficient method that explicitly exploits the local geometry induced by the BEM through the Wasserstein Natural gradient (WNG), leading to gains in performance at a reduced computational cost. When global proximity is important to the task, we show that using the Wasserstein penalty in \cref{eq:proximal_expression_wasserstein} and optimizing it using the WNG yields more efficient updates, thus converging faster than simply optimizing \cref{eq:proximal_expression_wasserstein} using standard gradients. \section{The Wasserstein Natural Gradient} \label{sect:WNG} \label{sec:def_WNG} The Wasserstein natural gradient (WNG) \citep{Li:2018a,Li:2018b} corresponds to the steepest-ascent direction of an objective within a trust region defined by the local behavior of the Wasserstein-$2$ distance ($W_2$). The $W_2$ between two nearby densities $q_{\theta}$ and $q_{\theta + u}$ can be approximated by computing the average cost of moving every sample $X$ from $q_{\theta}$ to a new sample $X'$ \textbf{approximately} distributed according to $q_{\theta + u}$ using an \textbf{optimal} vector field of the form $\nabla_x f_u(x)$ so that $X' = X + \nabla_x f_u(X) $ (see \cref{fig:wasserstein}). Optimality of $\nabla_x f_u$ is defined as a trade-off between accurately moving mass from $q_{\theta}$ to $q_{\theta + u}$ and reducing the transport cost measured by the average squared norm of $\nabla_x f_u$ \begin{align}\label{eq:legendre_duality_wasserstein} \sup_{f_u}~ \nabla_{\theta} \mathbb{E}_{q_{\theta}}\left[ f_u(X) \right]^{\top}u -\frac{1}{2} \mathbb{E}_{q_{\theta}} \left[\Vert \nabla_x f_u(X) \Vert^2 \right], \end{align} where the optimization is over a suitable set of smooth real valued functions on $\mathcal{E}$. Hence, the optimal function $f_u$ solving \cref{eq:legendre_duality_wasserstein} defines the \textbf{optimal} vector field $\nabla_x f_{u}(x)$. Proposition \ref{prop:WIM} makes this intuition more precise and defines the Wasserstein Information Matrix. \begin{proposition}[Adapted from Defintion 3 \cite{Li:2019b}]\label{prop:WIM} The second-order Taylor expansion of $W_2$ between two nearby parametric probability distributions $q_{\theta}$ and $q_{\theta+u}$ is given by \begin{align}\label{eq:second_order_exansion} W_2^2(q_{\theta},q_{\theta+u}) = u^{\top}G(\theta)u + o(\Vert u \Vert^2) \end{align} where $G(\theta)$ is the Wasserstein Information Matrix (WIM), with components in a basis $(e_1,...,e_p)$ \begin{align}\label{eq:WIM} G_{j,j'}(\theta) = \mathbb{E}_{q_{\theta}}\left[\nabla_x f_{j}(X)^{\top} \nabla_x f_{j'}(X)\right]. \end{align} The functions $f_j$ solve \cref{eq:legendre_duality_wasserstein} with $u$ chosen as $e_j$. Moreover, for any given $u$, the solution $f_u$ to \cref{eq:legendre_duality_wasserstein} satisfies $\mathbb{E}_{\theta}[\Vert \nabla_x f_u(X)\Vert^2 ] = u^{\top}G(\theta)u$. \end{proposition} When $q_{\theta}$ and $q_{\theta+u}$ are the behavioral embedding distributions of two policies $\pi_{\theta}$ and $\pi_{\theta+u}$, the function $f_u$ allows to transport behavior from a policy $\pi_{\theta}$ to a behavior as close as possible to $\pi_{\theta+u}$ with the least cost. We thus refer to $f_u$ as the \textit{behavioral transport function}. The function $f_u$ determines how hard it is to change behavior \textbf{locally} from policy $\pi_{\theta}$ in a direction $u$, thus providing a tool to find update directions $u$ with either \textit{maximal} or \textit{minimal} change in behavior. Probing all directions in a basis $(e_1,...,e_p)$ of parameters allows us to construct the WIM $G(\theta)$ in \cref{eq:WIM} which summarizes proximity in behavior along all possible directions $u$ using $ u^{\top}G(\theta) u = \mathbb{E}_{q_{\theta}}[ \Vert \nabla_x f_u(X) \Vert^2 ] $. For an objective $\mathcal{L}(\theta)$, such as the expected total reward of a policy, the Wasserstein natural gradient (WNG) is then defined as the direction $u$ that locally increases $\mathcal{L}(\theta+u)$ the most with the least change in behavior as measured by $f_u$. Formally, the WNG is related to the usual Euclidean gradient $g = \nabla_{\theta}\mathcal{L}(\theta) $ by \begin{align}\label{eq:WNG} g^{W} = \mathop{\mathbox{argmax}}_u 2g^{\top}u- u^{\top}G(\theta)u. \end{align} From \cref{eq:WNG}, the WNG can be expressed in closed-form in terms of $G(\theta)$ and $g$ as $g^{W} = G^{-1}(\theta)g$. Hence, WNG ascent is simply performed using the update equation $\theta_{k+1} = \theta_k + \lambda g^W_k $. We'll see in \cref{sec:efficient_wng} how to estimate WNG efficiently without storing or explicitly inverting the matrix $G$. Next, we discuss the advantages of using WNG over other methods. \subsection{Why use the Wasserstein Natural Gradient?}\label{sec:why_WNG} To illustrate the advantages of the WNG, we consider a simple setting where the objective is of the form $\mathcal{L}(\theta) = \mathbb{E}_{q_{\theta}}[\psi(x)]$, with $q_{\theta}$ being a gaussian distribution. The optimal solution in this example is a deterministic point mass located at the global optimum $x^{\star}$ of the function $\psi(x)$. This situation arises systematically in the context of ES when using a gaussian noise distribution with learnable mean and variance. Moreover, the optimal policy of a Markov Decision Processes (MDP) is necessarily deterministic \citep{Puterman:2010}. Thus, despite its simplicity, this example allows us to obtain closed-form expressions for all methods while capturing a crucial property in many RL problems (deterministic optimal policies) which, as we will see, results in differences in performance. \begin{figure}[!t] \centering \includegraphics[width=\textwidth]{figs/all_toy_dim_100_v4} \caption{ Different optimization methods using an objective $\mathcal{L}(\theta) = \mathbb{E}_{q_{\theta}}[\psi(x)]$ where $q_{\theta}$ is a gaussian of $100$ dimensions with parameters $\theta= (\bm{\mu}, v)$. Here $\bm{\mu}$ in bold is the mean vector, $v$ parameterizes the covariance matrix $\Sigma$, which is chosen to be diagonal. Two parameterizations for the covariance matrix are considered: $\Sigma_{ii} = e^{v_i}$ (log-diagonal) and $\Sigma_{ii} = v_i$ (diagonal). $\psi(x)$ is the sum of $sinc$ functions over all dimensions. Training is up to 4000 iterations, with $\lambda = .9$ and $\beta =.1$ unless they are varied. In \cref{fig:toys} (c), $\sigma$ and $\mu$ refer to the std of the first component of the gaussian $\sigma= \sqrt{\Sigma_{11}}$ and $\mu = \bm{\mu}_1$. More details about the experimental setting are provided in \cref{sec:exp_setting_toy}. } \label{fig:toys} \end{figure} \paragraph{Wasserstein natural gradient vs Fisher natural gradient} While \cref{fig:toys} (c) shows that both methods seem to reach the same solution, a closer inspection of the loss, as shown in \cref{fig:toys} (d) and (e) for two different parameterizations of $q_{\theta}$, shows that the FNG is faster at first, then slows down to reach a final error of $10^{-4}$. On the other hand, WNG is slower at first then transitions suddenly to an error of $10^{-8}$. The optimal solution being deterministic, the variance of the gaussian $q_{\theta}$ needs to shrink to $0$. In this case, the KL blows up, while the $W_2$ distance remains finite. As the natural gradient methods are derived from those two divergences (\cref{prop:proximal_limit} of \cref{sec:wng_appendix}), they inherit the same behavior. This explains why, unlike the WNG, the FNG doesn't achieve the error of $10^{-8}$. Beyond this example, when the policy $\pi_{\theta}$ is defined only implicitly using a generative network, as in \cite{Tang:2019}, the FNG and KL penalty are ill-defined since $\pi_{\theta_k}$ and $\pi_{\theta_{k+1}}$ might have non-overlapping supports. However, the WNG remains well-defined (see \cite{Arbel:2019a}) and allows for more flexibility in representing policies, such as with behavioral embeddings. \paragraph{Wasserstein penalty vs Wasserstein natural gradient} The Wasserstein penalty \cref{eq:proximal_expression_wasserstein} encourages \textit{global} proximity between updates $q_{\theta_k}$. For small values of the penalty parameter $\beta$, the method behaves like standard gradient descent (\cref{fig:toys} (a)). As $\beta$ increases, the penalty encourages more local updates and thus incorporates more information about the local geometry defined by $q_{\theta}$. In fact, it recovers the WNG direction (\cref{prop:proximal_limit} of \cref{sec:wng_appendix}) albeit with an infinitely small step-size which is detrimental to convergence of the algorithm. To avoid slowing-down, there is an intricate balance between the step-size and penalty $\beta$ that needs to be maintained \citep{Schulman:2017}. All of these issues are avoided when directly using the WNG, as shown in \cref{fig:toys} (a), which performs the best and tolerates the widest range of step-sizes \cref{fig:toys} (f). Moreover, when using the \textit{log-diagonal parameterization} as in \cref{fig:toys} (d,a), the WNGD (in red) achieves an error of 1e-8, while $W_2$-penalty achieves a larger error of order 1e-0 for various values of the $\beta$. When using the \textit{diagonal parameterization} instead, as shown in \cref{fig:toys} (e), both methods achieve a similar error of 1e-6. This discrepancy in performance highlights the robustness of WNG to parameterization of the model. {\bf Combining WNG and a Wasserstein penalty.} The global proximity encouraged by a $W_2$ penalty can be useful on its own, for instance, to explicitly guarantee policy improvement as in \cite[Theorem 5.1]{Pacchiano:2019}. However, this requires estimating the $W_2$ at every iteration, which can be costly. Using WNG instead of the usual gradient can yield more efficient updates, thus reducing the number of time $W_2$ needs to be estimated. The speed-up can be understood as performing second-order optimization on the $W_2$ penalty since the WNG arises precisely from a second-order expansion of the $W_2$ distance, as shown in \cref{sec:def_WNG} (See also Example 2 in \cite{Arbel:2019a}). \section{Policy Optimization using Behavioral Geometry} \label{sect:algos} We now present practical algorithms to exploit the behavioral geometry induced by the embeddings $\Phi$. We begin by describing how to efficiently estimate the WNG. \paragraph{Efficient estimation of the WNG}\label{sec:efficient_wng} can be performed using kernel methods, as shown in \cite{Arbel:2019a} in the case where the re-parametrization trick is applicable. This is the case, if for instance, the behavioral variable is the concatenation of actions $X = [ a_0,...,a_T]$ and if actions are sampled from a gaussian with mean and variance parameterized by a neural network, as is often done in practice for real-valued actions. Then $X$ can be expressed as $X = B_{\theta}(Z) $ where $B_{\theta}$ is a known function and $Z$ is an input sample consisting in the concatenation of states $[s_0,...,s_T]$ and the gaussian noise used to generate the actions. However, the proposed algorithm is not readily applicable if for instance the behavioral variable $X$ is a function of the reward. We now introduce a procedure that extends the previous method to more general cases, including those where only the score $\nabla_{\theta}\log q_{\theta} $ is available without an explicit re-parametrization trick. The core idea is to approximate the functions $f_{e_j}$ defining $G(\theta_k)$ in \cref{eq:WIM} using a linear combinations of user-specified basis functions $(h_1(x),...,h_M(x))$: \begin{align}\label{eq:linear_combination} \hat{f}_{e_j}(x) = \sum_{m=1}^M \alpha_{m}^j h_m(x), \end{align} The number $M$ controls the computational cost of the estimation and is typically chosen on the order of $M=10$. The basis can be chosen to be \textit{data-dependent} using kernel methods. More precisely, we use the same approach as in \cite{Arbel:2019a}, where we first subsample $M$ data-points $Y_m$ from a batch of $N$ variables $X_n$ and $M$ indices $i_m$ from $\{1,...,d\}$ where $d$ is the dimension of $X_n$. Then, each basis can of the form $h_m(x) = \partial_{i_m}K(Y_m,x) $ where $K$ is a positive semi-definite kernel, such as the gaussian kernel $K(x,y) = \exp(- \frac{\Vert x-y \Vert^2}{\sigma^2} )$. This choice of basis allows us to provide guarantees for functions $f_j$ in terms of the batch size $N$ and the number of basis points $M$ \cite[Theorem 7]{Arbel:2019a}. Plugging-in each $\hat{f}_{j}$ in the transport cost problem \cref{eq:legendre_duality_wasserstein} yields a quadratic problem of dimension $M$ in the coefficients $\alpha^j$: \begin{align*} \text{maximize}_{\alpha^j}~ 2J_{.,j}\alpha^{j} - (\alpha^j)^{\top}L\alpha^j \end{align*} where $L$ is a square matrix of size $M\times M$ independent of the index $j$ and $J$ is a Jacobian matrix of shape $ M\times p $ with rows given by $ J_{m,.} = \nabla_{\theta}\mathbb{E}_{q_{\theta_k}}[h_m(X)]$. There are two expressions for $J$, depending on the applicability of the re-parametrization trick or the availability of the score \begin{align}\label{eq:jacobian} J_{m,.} = \hat{\mathbb{E}}_{q_{\theta}}[\nabla_x h_m(X) \nabla_{\theta} B_{\theta}(Z)]\qquad \text{or}\qquad J_{m,.} = \hat{\mathbb{E}}_{q_{\theta}}[\nabla_{\theta}\log q_{\theta}(X)h_m(X)] \end{align} Computing $J$ can be done efficiently for moderate size $M$ by first computing a surrogate vector of $V$ of size $M$ whose Jacobian recovers $J$ using automatic differentiation software: \begin{align}\label{eq:surrogate_loss} V_m = \hat{\mathbb{E}}_{q_{\theta}}\left[ h_m(X_n)\right] , \qquad \text{or} \qquad V_m = \hat{\mathbb{E}}_{q_{\theta}}\left[ \log q_{\theta}(X_n) h_m(X_n)\right]. \end{align} The optimal coefficients $\alpha^{j}$ are then simply expressed as $\alpha = L^{\dagger}J$. Plugging-in the optimal functions in the expression of the Wasserstein Information Matrix (\cref{eq:WIM}), yields a low rank approximation of $G$ of the form $ \hat{G} = J^{\top}L^{\dagger} J $. By adding a small diagonal perturbation matrix $\epsilon I$, it is possible efficiently compute $ (\hat{G} + \epsilon I)^{-1}\hat{g} $ using a generalized Woodbury matrix identity which yields an estimator for the Wasserstein Natural gradient \begin{align}\label{eq:wng_estimator} \hat{g}^{W} = \frac{1}{\epsilon}\left( \hat{g} - J^{\top}\left( JJ^{\top} + \epsilon L \right)^{\dagger}J\hat{g} \right). \end{align} The pseudo-inverse is only computed for a matrix of size $M$. Using the Jacobian-vector product, \cref{eq:wng_estimator} can be computed without storing large matrices $G$ as shown in \cref{alg:KWNG_3}. \paragraph{Wasserstein Natural Policy Gradient (WNPG). It is possible to incorporate local information about the behavior of a policy in standard algorithms for policy gradient as summarized in \cref{alg:WNPG}. In its simplest form, one first needs to compute the gradient $\hat{g}_k$ of the objective $\mathcal{L}(\theta_k)$ using, for instance, the REINFORCE estimator computed using $N$ trajectories $\tau_n$. The trajectories are then used to compute the BEMs which are fed as input, along with the gradient $\hat{g}_k$ to get an estimate of the WNG $g^W_{k}$. Finally, the policy can be updated in the direction of $g^W_k$. \cref{alg:WNPG} can also be used in combination with an explicit $W_2$ penalty to control non-local changes in behavior of the policy thus ensuring a policy improvement property as in \cite[Theorem 5.1]{Pacchiano:2019}. In that case, WNG enhances convergence by acting as a second-order optimizer, as discussed in \cref{sec:why_WNG}. The standard gradient $\hat{g}_k$ in \cref{alg:WNPG} is then simply replaced by the one computed in \cite[Algorithm 3]{Pacchiano:2019}. In \cref{sect:experiments}, we show that this combination, which we call behavior-guided WNPG (BG-WNPG), leads to the best overall performance. \begin{algorithm}[t] \caption{Wasserstein Natural Policy Gradient}\label{alg:WNPG} \begin{algorithmic}[1] \STATE \textbf{Input} Initial policy $\pi_{\theta_0}$ \FOR{ iteration $k=1,2,...$} \STATE Obtain $N$ rollouts $\{\tau\}_{n=1}^N$ of length $T$ using policy $\pi_{\theta_k}$ \STATE Compute loss $\mathcal{L}(\theta_k)$ in a forward pass \STATE Compute gradient $\hat{g}_k$ in the backward pass on $\mathcal{L}(\theta_k)$ \STATE Compute Behavioral embeddings $\{X_n = \Phi(\tau^n)\}_{n=1}^N$ \STATE Compute WNG $\hat{g}^W_k$ using \cref{alg:KWNG_3} with samples $\{X_n\}_{n=1}^N$ and gradient estimate $\hat{g}_k$. \STATE Update policy using: $\theta_{k+1} = \theta_k + \lambda \hat{g}_{k}^{W}$. \ENDFOR \end{algorithmic} \end{algorithm} \paragraph{Wasserstein Natural Evolution Strategies (WNES).} \label{sec:WNES} ES treats the total reward observed on a trajectory under policy $\pi_{\theta}$ as a black-box function $\mathcal{L}(\theta)$ \citep{Salimans:2017,Mania:2018,Choromanski:2020}. Evaluating it under $N$ policies whose parameters $\widetilde{\theta}^n$ are gaussian perturbations centered around $\theta_k$ and with variance $\sigma$ can give an estimate of the gradient of $\mathcal{L}(\theta_k)$: \begin{align}\label{eq:ES_gradient} \hat{g}_k = \frac{1}{N\sigma} \sum_{n=1}^N \left(\mathcal{L}(\widetilde{\theta}^n)- \mathcal{L}(\theta_k)\right)(\widetilde{\theta}^n-\theta_k). \end{align} Instead of directly updating the policy using \cref{eq:ES_gradient}, it is possible to encourage either proximity or diversity in behavior using the embeddings $X_n = \Phi(\tau_n)$ of the trajectories $\tau_n$ generated for each perturbed policy $\pi_{\widetilde{\theta}_n}$. Those embeddings can be used as input to \cref{alg:KWNG_3} (see appendix), along with \cref{eq:ES_gradient} to estimate the $\hat{g}^W_k$, which captures similarity in behavior. The algorithm remains unchanged except for the estimation of the Jacobian $J$ of \cref{eq:jacobian} which becomes \begin{align}\label{eq:ES_jacobian} J_{m,.} = \frac{1}{N\sigma} \sum_{n=1}^N h_m(X_n)(\widetilde{\theta}^n-\theta_k). \end{align} The policy parameter can then be updated using an interpolation between $\hat{g}_k$ and the WNG $\hat{g}_k^W$, i.e., \begin{align}\label{eq:update_gradient_ES} \Delta \theta_k \propto (1-\delta)\hat{g}_k + \delta \hat{g}_k^W \end{align} with $\delta\leq 1$ that can also be negative. Positive values for $\delta$ encourage proximity in behavior, the limit case being $\delta=1$ where a full WNG step is taken. Negative values encourage repulsion and therefore need to compensated by $\hat{g}_k$ to ensure overall policy improvement. \cref{alg:WNES} summarizes the whole procedure, which can be easily adapted from existing ES implementations by calling a variant of \cref{alg:KWNG_3}. In particular, it can also be used along with an explicit $W_2$ penalty, in which case the proposed algorithm in \cite{Pacchiano:2019} is used to estimate the standard gradient $\hat{g}_k$ of the penalized loss. Then the policy is updated using \cref{eq:update_gradient_ES} instead of $\hat{g}_k$. We refer to this approach as behavior-guided WNES (BG-WNES). \begin{algorithm}[!t] \caption{Wasserstein Natural Evolution Strategies}\label{alg:WNES} \begin{algorithmic}[1] \STATE \textbf{Input} Initial policy $\pi_{\theta_0}$, $\alpha>0$, $\delta\leq 1$ \FOR{ iteration $k=1,2,...$} \STATE Sample $\epsilon_1,\dots,\epsilon_n \sim \mathcal N(0, I)$. \STATE Perform rollouts $\{\tau_n\}_{n-1}^{N}$ of length $T$ using the perturbed parameters $\{\widetilde{\theta}^n = \theta_k + \sigma \epsilon_n\}_{n=1}^{N}$ and compute behavioral embeddings $\{X_n = \Phi(\tau^n)\}_{n=1}^N$ \STATE Compute gradient estimate of $\mathcal{L}(\widetilde{\theta}^n)$ using \cref{eq:ES_gradient} and trajectories $\{\tau^{n}\}_{n=1}^N$. \STATE Compute Jacobian matrix $J$ appearing in \cref{alg:KWNG_3} using \cref{eq:ES_jacobian}. \STATE Compute WNG $\hat{g}^W_k$ using \cref{alg:KWNG_3}, with samples $\{X_n\}_{i=1}^N$ and computed $\hat{g}_k$ and $J$. \STATE Update policy using \cref{eq:update_gradient_ES}. \ENDFOR \end{algorithmic} \end{algorithm} \begin{figure}[!t] \centering \includegraphics[width=0.99\textwidth]{figs/pg_all.pdf} \caption{\textbf{WNG-based algorithms provide large gains on tasks where initial progress is difficult.} The performance mean $\pm$ standard deviation is plotted versus time steps for 5 random seeds on each task.} \label{fig:pg_exps} \end{figure} \section{Experiments}\label{sect:experiments} We now test the performance of our estimators for both policy gradients (PG) and evolution strategies (ES) against their associated baseline methods. We show that in addition to an improved computational efficiency, our approach can effectively utilize the geometry induced by a Wasserstein penalty to improve performance, particularly when the optimization problem is ill-conditioned. Further experimental details can be found in the appendix, and our code is available online\footnote{\texttt{https://github.com/tedmoskovitz/WNPG}}. {\bf Policy Gradients.} We first apply WNPG and BG-WNPG to challenging tasks from OpenAI Gym \citep{Brockman:2016} and Roboschool (RS). We compare performance against behavior-guided policy gradients (BGPG), \citep{Pacchiano:2019}, PPO with clipped surrogate objective \citep{Schulman:2017} (PPO (Clip)), and PG with no trust region (None). From \cref{fig:pg_exps}, we can see that BGPG outperforms the corresponding KL-based method (PPO) and vanilla PG, as also demonstrated in the work of \cite{Pacchiano:2019}. Our method (WNPG) matches or exceeds final performance of BGPG on all tasks. Moreover, combining both (BG-WNPG) produces the largest gains on all environments. Final mean rewards are reported in \cref{table:pg_results}. It is also important to note that WNG-based methods appear to offer the biggest advantage on tasks where initial progress is difficult. To investigate this further, we computed the hessian matrix at the end of training for each task and measured the ratios of its largest eigenvalue to each successive eigenvalue (\cref{fig:cond_number}). Larger ratios indicate ill-conditioning, and it is significant that WNG methods produce the greatest improvement on the environments with the poorest conditioning. This is consistent with the findings in \cite{Arbel:2019a} that showed WNG to perform most favorably compared to other methods when the optimization problem is ill-conditioned, and implies a useful heuristic for gauging when WNG-based methods are most useful for a given problem. \begin{wrapfigure}{R}{0.5\textwidth} \centering \includegraphics[trim={0.5cm 0.2cm 0.5cm 0.2cm}, clip, width=0.85\textwidth]{figs/condition_nums.pdf} \caption{Condition numbers for different tasks.} \label{fig:cond_number} \end{wrapfigure} \vspace{-.3cm} \paragraph{Evolution Strategies} To test our estimator for WNES, as well as BG-WNES, we applied our approach to the environment introduced by \cite{Pacchiano:2019}, designed to test the ability of behavior-guided learning to succeed despite deceptive rewards. During the task, the agent receives a penalty proportional to its distance from a goal, but a wall is placed directly in the agent's path (\cref{fig:quad_env_viz}). This barrier induces a local maximum in the objective---a na\"ive agent will simply walk directly towards the goal and get stuck at the barrier. The idea is that the behavioral repulsion fostered by applying a positive coefficient to the Wasserstein penalty ($\beta > 0$) will encourage the agent to seek novel policies, helping it to eventually circumvent the wall. As in \cite{Pacchiano:2019}, we test two agents, a simple point and a quadruped. We then compare our method with vanilla ES as described by \cite{Salimans:2017}, ES with gradient norm clipping, BGES \citep{Pacchiano:2019}, and NSR-ES \citep{Conti:2018}. In \cref{fig:es_exps}, we can see that WNES and BG-WNES improve over the baselines for both agents. To test that the improvement shown by BG-WNES wasn't simply a case of additional ``repulsion'' supplied by the WNG to BGES, we also tested BGES with an increased $\beta = 0.75$, compared to the default of $0.5$. This resulted in a decrease in performance, attesting to the unique benefit provided by the WNES estimator. \begin{figure}[!t] \centering \includegraphics[width=0.99\textwidth]{figs/es_exps.pdf} \caption{\textbf{WNES methods more reliably overcome local maxima.} Results obtained on the point (a) and quadruped (b) tasks. The mean $\pm$ standard deviation is plotted across 5 random seeds.} \label{fig:es_exps} \end{figure} {\bf Computational Efficiency} We define the \emph{computational efficiency} of an algorithm as the rate with which it accumulates reward relative to its runtime. To test the computational efficiency of our approach, we plotted the total reward divided by wall clock time obtained by each agent for each task (Fig. \ref{fig:rpm}). Methods using a WNG estimator were the most efficient on each task for both PG and ES agents. On several environments used for the policy gradient tasks, the added cost of BG-WNPG reduced its efficiency, despite having the highest absolute performance. \begin{figure}[!t] \centering \includegraphics[width=0.99\textwidth]{figs/rpm.pdf} \caption{\textbf{WNG methods improve computational efficiency.} Average reward per minute is plotted for both gradient tasks (left) and ES tasks (right) for the runs depicted above.} \label{fig:rpm} \end{figure} \section{Conclusion} Explicit regularization using divergence measures between policy representations has been a common theme in recent work on policy optimization for RL. While prior works have previously focused on the KL divergence, \cite{Pacchiano:2019} showed that a Wasserstein regularizer over behavioral distributions provides a powerful alternative framework. Both approaches implicitly define a form of natural gradient, depending on which divergence measure is chosen. Through the introduction of WNPG and WNES, we demonstrate that directly estimating the natural gradient of the un-regularized objective can deliver greater performance at lower computational cost. These algorithms represent novel extensions of previous work on the WNG to problems where the re-parameterization trick is not available, as well as to black-box methods like ES. Moreover, using the WNG in conjunction with a WD penalty allows the WNG to take advantage of the local geometry induced by the regularization, further improving performance. We also provide a novel comparison between the WNG and FNG, showing that the former has significant advantages on certain problems. We believe this framework opens up a number of avenues for future work. Developing a principled way to identify useful behavioral embeddings for a given RL task would allow to get the highest benefit form WNPG and WNES. From a theoretical perspective, it would be useful to characterize the convergence boost granted by the combination of explicit regularization and the corresponding natural gradient approach. \paragraph{Acknowledgments} The authors would like to thank Jack Parker-Holder for sharing his code for BGPG and BGES, as well as colleagues at Gatsby for useful discussions. \newpage
{'timestamp': '2021-03-19T01:17:06', 'yymm': '2010', 'arxiv_id': '2010.05380', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05380'}
arxiv
\section{Introduction} Humans can produce and understand linguistic expressions that they have not encountered before, by systematically combining atomic building blocks \citep{montague1974english}. For instance, a speaker that knows the meaning of \textit{John loves Mary} is necessarily able to understand \textit{Mary loves John}, even if the speaker has not heard or uttered this sentence before \cite{fodor1988connectionism}. The discipline of formal semantics concerns itself with characterizing these building blocks, or ``primitives'', and the ways in which they combine to construct the meaning of a complex expression (e.g., Figure~\ref{fig:composition-example}). \begin{figure}[h] \centering \begin{subfigure}{\columnwidth} \includegraphics[width=\textwidth,trim=0 0.2in 0 0]{figs/semantics_tree.png} \caption{\label{fig:composition-example}} \end{subfigure} \begin{subfigure}{\columnwidth} \includegraphics[width=\textwidth]{figs/composition.png} \caption{\label{fig:inference-example}} \end{subfigure} \caption{(a) The meaning of a sentence (right) is compositionally built up from the meanings of its parts, in accordance with its structure (left). (b) Interpreting a familiar word in a structure it has not appeared in before. In colors: expressions providing the primitive meanings; in bold: expressions providing evidence that definite NPs may appear in both argument positions of a transitive verb. $[[x]]$ denotes the meaning of $x$.} \end{figure} To assess the abilities of computational models of language to generalize compositionally, we propose COGS, a \textbf{CO}mpositional \textbf{G}eneralization Challenge based on \textbf{S}emantic Interpretation, in which a model of language is expected to construct a semantic representation of a given English sentence (semantic parsing). The key component of this challenge is that the training and evaluation sets systematically differ in their properties, such that success on the evaluation set requires out-of-distribution generalization. Of the many possible ways that a model could systematically fill such gaps, we expect it to do so in a way that is consistent with the compositional principles that guide human linguistic generalization. Figure~\ref{fig:inference-example} illustrates how the meaning of the unseen expression \textit{The boy loves the hedgehog} could be compositionally inferred from known parts. In this case, the noun phrase (NP) \textit{the hedgehog}, which has only been observed as a subject, needs to be interpreted in the direct object position. The generalizations tested by COGS, described in detail in Section~\ref{sec:dataset}, include interpreting novel combinations of primitives and grammatical roles, interpreting novel combinations of modified phrases and grammatical roles, generalizing phrase nesting to unseen depths, verb argument structure alternation, and sensitivity to verb class. Rule-based semantic parsing systems such as Boxer \citep{bos2008wide} are able to generalize compositionally by design. By contrast, this ability does not constitute a part of the design of the neural network models of language that are standard in NLP; it could only arise in such models through learning, inductive biases, or a combination of the two. To test whether standard NLP models are equipped with the ability to generalize compositionally, we used COGS to evaluate three architectures: Transformer, Bidirectional LSTM, and Unidirectional LSTM (Section~\ref{sec:experiments}). We found that the out-of-distribution generalization set was significantly more challenging (16--35\% mean accuracy) than an in-distribution test set (96--99\% mean accuracy). Furthermore, generalization accuracy varied greatly across runs of the same architecture that differed only in random seed (6--8\% standard deviation). Further analysis revealed that structural generalization (to novel combinations of familiar syntactic structures) poses greater difficulties than lexical generalization (to novel combinations of a familiar primitive and a familiar structure). These results suggests that higher accuracy on COGS would require a stronger structural bias than that of Transformers and LSTMs. \section{Compositional Generalization} \citet{fodor1988connectionism} highlighted the intrinsic connection between the ability to produce and understand different sentences that are made up of the same building blocks, such as \textit{John loves Mary} and \textit{Mary loves John}. This connection, which they refer to as \textit{systematicity}, derives from a combinatorial mechanism that constructs the meaning of a complex expression from its parts: understanding \textit{John loves Mary} and \textit{Mary loves John} involves combining the same primitives using the same rules. The question of whether neural networks can display human-like systematicity has a long history. In a review of early work, \citet{hadley1994systematicity} argued that none of the connectionist models he examined displayed the degree of systematicity that humans do. Recently \citet{lake2018generalization} revisited this question using contemporary neural architectures---sequence-to-sequence models with LSTM and GRU units---and came to the same conclusion as Hadley. \citeauthor{lake2018generalization} based their study on the SCAN task, a novel task in which word sequences in a synthetic language need to be mapped to navigation command sequences (e.g., \textit{jump twice} $\rightarrow$ JUMP JUMP). Crucially, their training/evaluation split required compositional generalization. A number of models have been developed that have improved performance on SCAN \citep{li2019compositional,gordon2020permutation}. However, since the semantic representation used by SCAN only covers a small subset of English grammar, SCAN does not enable testing various systematic linguistic abstractions that humans are known to make (e.g., verb argument structure alternation). Thus, it is unclear whether progress on SCAN would generalize to natural language. To bring the evaluation of compositional generalization a step closer to natural language, COGS includes a wide range of syntactic constructions, and uses semantic representations based on lambda calculus, inspired by the formalisms employed in formal semantics \citep{parsons1990events} and semantic parsing \citep{palmer-etal-2005-proposition,reddy2017universal}. Following \citet{dong-lapata-2016-language} and \citet{daza-frank-2018-sequence}, we cast semantic parsing as a sequence-to-sequence problem. \begin{table*} \centering \resizebox{1\textwidth}{!}{ \begin{tabular}{lp{5cm}p{5cm}} \toprule Case & Training & Generalization \\ \midrule \multicolumn{3}{c}{S.\ref{subsubsec:prims}. Novel Combination of Familiar Primitives and Grammatical Roles} \\ \midrule Subject $\rightarrow$ Object (common noun) & A \textbf{hedgehog} ate the cake. & The baby liked the \textbf{hedgehog}. \\ Subject $\rightarrow$ Object (proper noun) & \textbf{Lina} gave the cake to Olivia. & A hero shortened \textbf{Lina}. \\ Object $\rightarrow$ Subject (common noun) & Henry liked a \textbf{cockroach}. & The \textbf{cockroach} ate the bat. \\ Object $\rightarrow$ Subject (proper noun) & The creature grew \textbf{Charlie}. & \textbf{Charlie} worshipped the cake. \\ Primitive noun $\rightarrow$ Subject (common noun) & \textbf{shark} & A \textbf{shark} examined the child. \\ Primitive noun $\rightarrow$ Subject (proper noun) & \textbf{Paula} & \textbf{Paula} sketched William. \\ Primitive noun $\rightarrow$ Object (common noun) & \textbf{shark} & A chief heard the \textbf{shark}. \\ Primitive noun $\rightarrow$ Object (proper noun) & \textbf{Paula} & The child helped \textbf{Paula}. \\ Primitive verb $\rightarrow$ Infinitival argument & \textbf{crawl} & A baby planned to \textbf{crawl}. \\ \midrule \multicolumn{3}{c}{S.\ref{subsubsec:mods}. Novel Combination Modified Phrases and Grammatical Roles} \\ \midrule Object modification $\rightarrow$ Subject modification & Noah ate \textbf{the cake on the plate.} & \textbf{The cake on the table} burned. \\ \midrule \multicolumn{3}{c}{S.\ref{subsubsec:recursion}. Deeper Recursion} \\ \midrule Depth generalization: Sentential complements & Emma said \textbf{that} Noah knew \textbf{that} the cat danced. & Emma said \textbf{that} Noah knew \textbf{that} Lucas saw \textbf{that} the cat danced. \\ Depth generalization: PP modifiers & Ava saw the ball \textbf{in the bottle on the table}. & Ava saw the ball \textbf{in the bottle on the table on the floor}. \\ \midrule \multicolumn{3}{c}{S.\ref{subsubsec:verb-argument-structure}. Verb Argument Structure Alternation} \\ \midrule Active $\rightarrow$ Passive & The crocodile \textbf{blessed} William. & A muffin \textbf{was blessed}. \\ Passive $\rightarrow$ Active & The book \textbf{was squeezed}. & The girl \textbf{squeezed} the strawberry. \\ Object-omitted transitive $\rightarrow$ Transitive & Emily \textbf{baked}. & The giraffe \textbf{baked a cake}. \\ Unaccusative $\rightarrow$ Transitive & The glass \textbf{shattered}. & Liam \textbf{shatterd} the jigsaw. \\ Double object dative $\rightarrow$ PP dative & The girl \textbf{teleported} Liam the cookie. & Benjamin \textbf{teleported} the cake \textbf{to} Isabella. \\ PP dative $\rightarrow$ Double Object Dative & Jane shipped the cake to John. & Jane shipped John the cake. \\ \midrule \multicolumn{3}{c}{S.\ref{subsubsec:verb-knowledge}. Verb Class} \\ \midrule Agent NP $\rightarrow$ Unaccusative subject & The \textbf{cobra} helped a dog. & The cobra \textbf{froze}. \\ Theme NP $\rightarrow$ Object-omitted transitive subject & The hippo \textbf{decomposed}. & The hippo \textbf{painted}. \\ Theme NP $\rightarrow$ Unergative subject & The hippo \textbf{decomposed}. & The hippo \textbf{giggled}. \\ \bottomrule \end{tabular} } \caption{A full list of generalization cases. Each sentence in the table represents a (sentence, logical form) pair. For instance, the sentence \textit{A hedgehog ate the cake} represents the following input-output mapping:\vspace{\baselineskip}\\\vspace{\baselineskip} \hspace{0.1in}\textit{A hedgehog ate the cake} $\rightarrow$ *cake($x_4$) ; hedgehog($x_1$) \textsc{and} eat.agent($x_2$,$x_1$) \textsc{and} eat.theme($x_2$,$x_4$)\\ ``Subject'' and ``Object'' include subjects and objects of both simple and embedded sentences. Due to space constraints, some sentences are simplified or rephrased versions of the sentences included in the dataset.} \label{table:case-list-full} \end{table*} \section{Overview of COGS} \label{sec:dataset} In a semantic parsing task such as COGS, the goal is to map a sentence to a logical form. Following recent works such as \citet{marvin2018targeted} and \citet{keysers2020measuring}, we generate the dataset using a rule-based approach; this allows us to maintain full control over the distribution of inputs that the learners are exposed to, and to ensure coverage of rare constructions that are not guaranteed to appear in natural corpora. COGS is not inherently grounded but could potentially be linked to a knowledge base or a visual world. The COGS dataset\footnote{\url{https://github.com/najoungkim/COGS}} is split into a training set and a generalization set. The training set includes systematic gaps that, in the generalization set, must be filled via compositional generalization. Success on the generalization set relies on several types of linguistic generalizations that humans are able to make. Instead of providing individual splits for each of the targeted generalizations, we expect the learner to make \textit{all} of the target generalizations at once. We describe below the five categories of generalizations targeted by COGS (see Table~\ref{table:case-list-full} for a full list). For a discussion of our design decisions from the perspective of formal semantics, see Appendix~\ref{app:linguistic-commentary}. \subsection{Novel Combination of Familiar Primitives and Grammatical Roles} \label{subsubsec:prims} English speakers can easily interpret an open-class primitive (e.g., a noun) in a grammatical role that is different from the one in which it was first observed. For example, a noun that was only observed as a subject can easily be interpreted as an object. This generalization capacity has been attested in children as young as 20 months old \citep{tomasello1993twenty}. We ensured that in the training set some lexical items only appear in subject position, and some only appear in object. In the generalization set, these lexical items appear in the opposite grammatical role. We test for generalization to the targeted grammatical roles not only in simple sentences, but also \textit{embedded} clauses; this form of generalization is a defining criterion of \textit{strong systematicity} \citep{hadley1994systematicity}. For instance, a noun that only occurred as a subject of a simple sentence in training may occur as an object of an embedded clause in the generalization set: \ex. \a.\textsc{Training}: A \textbf{hedgehog} ate the cake. \b.\textsc{Generalization}: A girl said that Emma called the \textbf{hedgehog}. While some primitives appear in the training set in the context of a sentence, others only occur in isolation. We express common noun meanings as unary predicates (\textit{shark} $\rightarrow$ $\lambda x. \text{shark}(x)$, proper noun meanings as constants (\textit{Emma} $\rightarrow$ Emma), and verb meanings as $n$-ary predicates with thematic role specifications (\textit{like} $\rightarrow$ $\lambda x. \lambda y. \lambda e.$like.agent($e, y$) \textsc{AND} like.theme($e, x$)) (see Appendix~\ref{app:linguistic-commentary} for more details). The training set contains these primitives as isolated words, but not as a part of a sentence; by contrast, the generalization set includes examples that require interpreting these primitives in context (e.g., \textit{The shark smiled}). \subsection{Novel Combination of Modified Phrases and Grammatical Roles} \label{subsubsec:mods} Phrases with a modifier, such as an NP modified by a prepositional phrase (PP), can occupy the same grammatical roles as unmodified phrases. For example, just like [\textit{the cat}]$_{\mathit{NP}}$, the phrase [[\textit{the cat}]$_{\mathit{NP}}$ [\textit{on the mat}]$_{\mathit{PP}}$]$_{\mathit{NP}}$ is an NP, and can occupy the same syntactic positions. Children acquiring language are most likely not exposed to modifiers in every possible syntactic position that the modified element may occur, yet learn a context-free phrasal modification rule (e.g., NP $\rightarrow$ NP PP) rather than a rule localized to a specific grammatical role (e.g., NP$_{\mathit{obj}}$ $\rightarrow$ NP PP). To test for generalization to modifiers in an unseen grammatical role, our training set includes only examples with PP modifiers within object NPs, and the generalization set contains PP modifiers within subject NPs. We note that this is a simplification of the generalization problem that humans may encounter; see Appendix~\ref{app:linguistic-commentary} for a further discussion. \subsection{Deeper Recursion} \label{subsubsec:recursion} The ability to derive an infinite number of expressions from a finite set of building blocks is a defining characteristic of human linguistic competence \citep{hauser2002faculty}. Human language achieves this property by allowing certain phrase types to be nested within a phrase of the same type. In [\textit{Mary knows that} [\textit{John knows} [\textit{that Emma cooks}]$_{\mathit{CP}}$~]$ _{\mathit{CP}}$~]$_{\mathit{CP}}$, clauses (CP) are nested inside other clauses. Our dataset includes two types of recursive constructions that allow arbitrary depths of nesting: sentential complements (nested CPs) and nominal PP modifiers (nested PPs). The training set contains nestings of depth \mbox{0--2,} where depth 0 is a phrase without nesting. The generalization set contains nestings of strictly greater depths (3--12). \subsection{Verb Argument Structure Alternation} \label{subsubsec:verb-argument-structure} Many English verbs participate in argument structure alternations \citep{levin1993english}. For instance, \textit{break} can be used both as a transitive verb (\textit{John broke the window}), and as an unaccusative verb, with its theme in the subject position (\textit{The window broke}). Likewise, agent-patient verbs can passivize; \textit{John broke the window} can be passivized to \textit{The window was broken}, or with an optional agent \textit{by}-phrase, \textit{The window was broken by John}. These alternation patterns are not restricted to particular lexical items, and humans can often apply such alternations to verbs that have only been observed in one of the forms. To illustrate, a person told that \textit{I floosed the cat} means ``I fed the cat twice'' would immediately be able to interpret \textit{The cat was floosed} (though see Section~\ref{sec:overgeneralization} for a caveat). COGS contains alternation patterns that humans have been shown in experiments to generalize to nonce verbs: active-passive \citep{brooks1999young}, transitive-intransitive (unaccusative and object-omitted transitives; \citealt{ono2006young,hu2007individual,kline2014syntactic}), and the alternation between double-object and prepositional-phrase datives \citep{conwell2007early}. For several verbs, we include only one of the alternating forms (e.g., active) in the training set, and only the other form (e.g., passive) in the generalization set. \subsection{Verb Class} \label{subsubsec:verb-knowledge} In English, the semantic role of the argument of a verb with a single argument depends on the identity of the verb; the surface syntax of the sentence is not enough to determine its interpretation. For instance, \textit{froze} in the sentence \textit{The lake froze} is an unaccusative verb, which takes a theme (or patient) as its grammatical subject, whereas in \textit{The dog smiled}, \textit{smiled} is an unergative verb that takes an agent as its grammatical subject. Inspired by this property, we include in our generalization set combinations of verbs and NPs, which all occur separately in the training set, but such that the NPs never appear as the thematic role specified by the verb in the training set. For instance, the training set contains a sentence with \textit{cobra} as an agent subject~\ref{ex:cobra-agent}, and sentences with unaccusative verbs~\ref{ex:freeze-unacc}, and the generalization set contains examples in which \textit{cobra} and \textit{freeze} appear together \ref{ex:cobra-freeze}. Correctly interpreting \textit{cobra} as the theme, even though it only appears in the training set as an agent, requires sensitivity to the argument structure of \textit{freeze}. \ex.\textsc{Training} \a. \begin{flushleft}\label{ex:cobra-agent} A cobra helped a dog. $\rightarrow$ \\ \textcolor{blue}{cobra($x_1$)} \textsc{and} help.\textcolor{blue}{agent}($x_2$,\textcolor{blue}{$x_1$}) \textsc{and} help.theme($x_2$,$x_4$) \textsc{and} dog($x_4$)\end{flushleft} \b. \begin{flushleft}\label{ex:freeze-unacc} The drink froze. $\rightarrow$ \\ *drink($x_1$) \textsc{and} freeze.\textcolor{red}{theme}($x_2$,\textcolor{red}{$x_1$})\end{flushleft} \ex.\textsc{Generalization} \vspace{-0.2cm} \begin{flushleft}\label{ex:cobra-freeze} The cobra froze. $\rightarrow$ \\ \textcolor{blue}{*cobra($x_1$)} \textsc{and} freeze.\textcolor{red}{theme}($x_2$,\textcolor{red}{$x_1$}) \end{flushleft} \section{Dataset Generation} \label{sec:dataset-generation} \paragraph{Grammar and logical forms.} We generated the constructions described in Section~\ref{sec:dataset} using a Probabilistic Context-Free Grammar (PCFG; Appendix~\ref{app:grammar}). The types of sentences covered by this PCFG accounted for 70--80\% of naturally-occurring English sentences, according to the analysis of five English corpora conducted by \citet{roland2007frequency}. The semantic interpretation of a sentence follows deterministically from the PCFG rules, which were annotated with semantic class information needed to disambiguate ambiguous syntactic structures (Section~\ref{subsubsec:verb-knowledge}). Sentences were first mapped to the simplified logical formalism proposed by \citet{reddy2017universal} using their codebase,\footnote{\url{https://github.com/sivareddyg/udeplambda}} and then passed through several postprocessing steps (see Appendix~\ref{app:postprocessing}). The logical forms use indexed constants that express the existence of an entity or an event denoted by the predicate. For example, in \ref{ex:constant}, $x_1$ expresses the existence of an entity that is both a cat and an agent of a smiling event; $x_2$ expresses the existence of an event that is a smiling event. \ex. \begin{flushleft} A cat smiled $\rightarrow$ \\cat($x_1$) \textsc{and} smile.agent($x_2$, $x_1$) \end{flushleft} \label{ex:constant} Our constants are named after indices of the phrasal head in the original sentence; in \ref{ex:constant}, the noun \textit{cat} is in position 1, so the corresponding constant is $x_1$. This indexing scheme was adopted to avoid the need to select arbitrary constant names (e.g, $x$, $y$, $z$, $\dots$) as the number of entities and events in the expression grows. \paragraph{Primitive exposure examples.} Many generalization cases crucially rely on particular training examples. For instance, to apply the Subject~$\rightarrow$ Object generalization to \textit{hedgehog}, at least one example with \textit{hedgehog} as subject must be included in the training set. Human learners only need to observe an item in a small number of distinct contexts before they can generalize to new contexts. For example, children of age 2 years and 11 months were able to produce in a passive construction a nonce verb they have only heard in an active transitive construction, after being exposed to 8 distinct usages of the construction \citep{brooks1999young}. \citet{borovsky2010learning,borovsky2012once} further suggest that humans are even capable of single-shot learning of word meaning in context. We include in our training set a single example to generalize from (``primitive exposure example'') per generalization case that requires it. In Appendix~\ref{app:shots} we report results on a version of COGS with 100 primitive exposure examples. \paragraph{Training and generalization sets.} We sampled 30,000 distinct sentences from our PCFG, excluding ones with duplicate nominals (e.g., \textit{The \textbf{cat} saw a \textbf{cat}}). These sentences were divided into training ($80\%; n$ = 24,000), development ($10\%; n$ = 3000), and test ($10\%; n$ = 3000) sets. We then added to the training set examples that specify the primitive meanings of 80 verbs and 60 nouns (including common and proper nouns). Separately, we generated primitive exposure examples ($n$ = 15, see previous paragraph) to add to the training set. The resulting training set consists of 24,155 examples. The out-of-distribution generalization set was constructed from separate PCFGs, each of which generates examples pertaining to a particular generalization case. For the Subject $\rightarrow$ Object generalization, for example, we generated sentences with \textit{hedgehog} in the object position. We sampled 1000 examples of each of the 21 cases, for a total of 21,000 examples. \section{Experiments} \label{sec:experiments} We next analyze the performance on COGS of two widely-used models for language tasks: Long Short-Term Memory (LSTM; \citealt{hochreiter1997long}) and Transformer \citep{vaswani2017attention}, both in an encoder-decoder setup \citep{sutskever2014sequence}. Transformers have been quickly adopted in practical NLP systems \citep{storks2019recent}, but the literature has reported mixed results on the benefit of Transformers over LSTMs in terms of linguistic generalization \citep{hupkes2020compositionality,van-schijndel-etal-2019-quantity}. Our goals in these experiments are, first, to test whether strong NLP models are equipped with the compositional generalization abilities required by COGS, and second, to determine whether there exist substantial differences across the models we test, when the number of trainable parameters is controlled for. \subsection{Training Details} We trained LSTM and Transformer models on COGS only without any pretraining. We used cross-entropy loss, a batch size of 128, and early stopping when validation loss did not improve for five validation steps (step size = 500). All experiments were run five times with different random seeds, which determined the initial weights and the order of the training examples. Models were implemented using OpenNMT-py\footnote{\url{https://github.com/OpenNMT/OpenNMT-py}} \citep{klein-etal-2017-opennmt}. For the LSTM, we used a 2-layer encoder-decoder with global attention and a dot-product score function. The decoder followed an input-feeding approach \citep{luong2015effective}. We tested both unidirectional and bidirectional LSTM encoders. The Transformer had a comparable number of parameters to the LSTMs (Transformer: 9.5M; BiLSTM: 10M; LSTM: 11M). It had 2 encoder and decoder layers, 4 attention heads, and a feedforward dimension of 512. See Appendix~\ref{app:training} for additional training details. \subsection{Results} \label{subsec:results} All architectures performed well on the development and test sets (Table~\ref{table:aggregate-results}), with little variability across runs (Figure~\ref{subfig:main-results}, green dots). By contrast, generalization accuracy was low across the board, and was characterized by much higher variance (blue dots). Transformers and unidirectional LSTMs of a comparable size did not substantially differ in their average accuracy, whereas bidirectional LSTMs performed comparatively worse. \begin{table}[h] \centering \begin{tabular}{lccc} \toprule Model & Dev. & Test & Gen. \\ \midrule Transformer & 0.96 & 0.96 & \textbf{0.35} ($\pm$ 0.06) \\ LSTM (Bi) & 0.99 & 0.99 & 0.16 ($\pm$ 0.08)\\ LSTM (Uni) & 0.99 & 0.99 & 0.32 ($\pm$ 0.06) \\ \bottomrule \end{tabular} \caption{Average accuracy of tested models. Only standard deviation greater than 0.01 is shown.} \label{table:aggregate-results} \end{table} \begin{figure}[h] \centering \begin{subfigure}[b]{\columnwidth} \includegraphics[width=\textwidth]{figs/main_acc_1shot_only.pdf} \caption{\label{subfig:main-results}} \end{subfigure} \begin{subfigure}[b]{\columnwidth} \includegraphics[width=\textwidth]{figs/main_acc_1shot_only_by_type.pdf} \caption{\label{subfig:main-results-by-type}} \end{subfigure} \caption{(a) Accuracy on COGS. An output sequence is considered correct only if it exactly matches the gold sequence. Each dot represents a model trained with a different random seed. (b) Accuracy by generalization type (lexical or structural).} \label{fig:main-results} \end{figure} \begin{table*}[h] \centering \resizebox{2\columnwidth}{!}{\begin{tabular}{p{4cm}p{4.5cm}p{4.5cm}c} \toprule Case & Training & Generalization & Accuracy Distribution \\ \midrule Subject $\rightarrow$ Object \newline (common noun) & \textit{Subject} \newline A \textbf{hedgehog} ate the cake. & \textit{Object} \newline The baby liked the \textbf{hedgehog}. & \raisebox{-0.7\totalheight}{\includegraphics[height=60px]{figs/2-1.pdf}} \\ Object $\rightarrow$ Subject \newline (common noun) & \textit{Object} \newline Henry liked a \textbf{cockroach}. & \textit{Subject} \newline The \textbf{cockroach} ate the bat. & \raisebox{-0.7\totalheight}{\includegraphics[height=60px]{figs/4-1.pdf}} \\ Object $\rightarrow$ Subject \newline (proper noun) & \textit{Object} \newline Mary saw \textbf{Charlie}. & \textit{Subject} \newline \textbf{Charlie} ate a donut. & \raisebox{-0.7\totalheight}{\includegraphics[height=60px]{figs/4-2.pdf}} \\ Primitive $\rightarrow$ Object \newline (proper noun) & \textit{Primitive} \newline \textbf{Paula} & \textit{Object} \newline The child helped \textbf{Paula}. & \raisebox{-0.7\totalheight}{\includegraphics[height=60px]{figs/6-2.pdf}} \\ Depth generalization: PP modifiers & \textit{Depth 2} \newline Ava saw the ball \textbf{in the bottle on the table}. & \textit{Depth 3} \newline Ava saw the ball \textbf{in the bottle on the table on the floor}. & \raisebox{-0.7\totalheight}{\includegraphics[height=60px]{figs/8-2.pdf}} \\ Active $\rightarrow$ Passive & \textit{Active} \newline Emma \textbf{blessed} William. & \textit{Passive} \newline A child \textbf{was blessed}. & \raisebox{-0.7\totalheight}{\includegraphics[height=60px]{figs/10-1.pdf}}\\ \bottomrule \end{tabular}} \caption{Accuracy on COGS by generalization case. Each dot represents a single run of the model.} \label{table:case-results} \end{table*} Accuracy on each generalization case greatly fluctuated across different runs of the same model, except for the cases where accuracy was close to zero (see examples in Table~\ref{table:case-results}, and see Appendix~\ref{app:full-results} for full results). The only exception to the trend was the Active~$\rightarrow$ Passive case (but not vice versa) in the Transformer model, where all runs of the model achieved close to 100\% accuracy. The majority of the LSTMs' predictions were structurally correct even when they did not exactly match the expected output, suggesting that Active~$\rightarrow$ Passive is one of the least challenging cases in our generalization set (see Appendix~\ref{app:lstm-vs-transformer} for an error analysis). \subsubsection{Lexical vs. Structural Generalization} Some of the COGS generalization cases require \textit{lexical} generalization: a primitive needs to be interpreted in a structure which, while not itself novel, did not occur with that primitive in training. This is the case for Object~$\rightarrow$ Subject: the training set does contain examples of the structure [NP [V NP]$_{\mathit{VP}}$] (Figure~\ref{fig:generalization-comparison}a), and the generalization concerns the particular NP that has never been observed in the first NP position. This contrasts with cases requiring \textit{structural} generalization, where the structure of the sentence is itself novel. This is the case, for instance, for the structure [[NP PP]$_{\mathit{NP}}$ [V NP]$_{\mathit{VP}}$]---a PP modifier on the subject---which appears in the generalization set but not in training (Figure~\ref{fig:generalization-comparison}b). The depth generalizations and the generalization of modifiers across grammatical roles require structural generalization; all such cases had zero or near-zero accuracies, whereas models performed better on lexical generalization (Figure~\ref{subfig:main-results-by-type}). This discrepancy suggests that composition of structures is more challenging to both Transformers and LSTMs. \begin{figure}[h] \centering \includegraphics[width=0.5\textwidth]{figs/lex_struct.png} \caption{(a) Lexical generalization: a novel combination of a familiar primitive and a familiar structure. (b) Structural generalization: a novel combination of two familiar structures.} \label{fig:generalization-comparison} \end{figure} \paragraph{Successful depth generalization cases.} Depth generalization with PP modifiers was the only case of structural generalization on which some models achieved nonzero accuracy. All of the successful examples were cases of depth 3, the smallest unseen depth tested. The success cases also had shorter output lengths, with a maximum length of 120 tokens. This was within the range of output lengths seen during training (the longest training example included 153 tokens), which may account for the somewhat higher accuracy on these cases. \paragraph{Failure to generalize structurally or failure to produce novel labels?} It is known that neural models find it challenging to produce labels they have not seen during training \citep{gandhi2019mutual}. Handling this problem is a necessary part of solving depth generalization, since each of the outputs of the depth generalization cases, such as \ref{ex:index-depth-b} below, contains more constants than the training outputs, such as the output of \ref{ex:index-depth-a}: \ex. \a.Depth 1: \label{ex:index-depth-a} The \textbf{cat} \textbf{liked} that the \textbf{dog} \textbf{saw} the \textbf{mouse}. \textit{(5 index-taking items)}\\ \b.\label{ex:index-depth-b}Depth 3: The \textbf{cat} \textbf{liked} that the \textbf{dog} \textbf{liked} that the \textbf{mouse} \textbf{liked} that the \textbf{girl} \textbf{saw} the \textbf{rat}. \textit{(9 index-taking items)} \label{ex:index-depth} As discussed in Section~\ref{sec:dataset}, we used index-based labels for constants precisely to help models with this issue of producing novel elements, by grounding the labels to the indices. Specifically, the 5 index-taking items in \ref{ex:index-depth-a} are labeled $x_1$, $x_2$, $x_5$, $x_6$ and $x_8$ instead of being assigned arbitrary labels such as $x, y, z \dots$. However, even with such non-arbitrary labels, the model still needs to learn that a word at index $i$ relates to the output string `i'. While this problem of novel symbols is indeed an issue that the models need to handle during depth generalization, the pattern of errors suggest that the low accuracy is not purely due to this issue. In fact, only 0.5\% of all depth generalization errors were cases where the structural form of the outputs were correct with only the indices being incorrect. More frequently, the models produced an end-of-sentence token too early (90.3\% of all depth generalization errors), or produced sequences that were superfluously long (3\% of errors contained more than 1000 tokens---more than twice as longer than the maximum gold output length: 480). This implies that models struggle with handling longer and deeper sequences than those observed during training, independently of their inability to produce novel labels. While output length likely contributed to the difficulty of our depth generalization cases---even in the in-domain test set, the average length of correct answers was 43 tokens, compared to 83 for incorrect answers---deeply nested structures imposed additional challenges. On the test set examples with output length greater than 95, LSTM models and Transformer models had 68\% and 13\% accuracy, respectively. Their PP modifier depth generalization accuracy was much lower (LSTM: 2\%; BiLSTM and Transformer: near 0\%). \subsubsection{Levels of Embedding} Our depth generalization set contains examples with embedding depths 3--12. However, it is likely that humans would find deeply embedded structures difficult to interpret. Given this potential difficulty for humans, is our depth generalization a fair challenge to pose? Comprehensibility of 3--5 degrees of embedding is attested in the literature; \citet{blaubergs1974short} showed that humans can understand 3--5 levels of right-branching CP embedding, and \citet{karlsson2010syntactic} observed that 3--5 levels of right-branching PP and CP embeddings do occur in corpora. In the case of the models we tested, they almost completely failed on generalization to any levels of embedding, \textit{including} depths 3--5 that humans should be able understand (Table~\ref{table:depth-split-results}). We discuss the issue of generalization to depths greater than 5 in Appendix~\ref{app:linguistic-commentary}. \begin{table}[h] \centering \begin{tabular}{lccc} \toprule Model & All & 3--5 & 6--12 \\ \midrule Transformer & 0.00 & 0.00 & 0.00 \\ LSTM (Bi) & 0.00 & 0.01 & 0.00 \\ LSTM (Uni) & 0.01 & 0.03 & 0.00 \\ \bottomrule \end{tabular} \caption{Accuracy on depths 3--5 and depths 6--12.} \label{table:depth-split-results} \end{table} \subsubsection{Model Size / Number of Exposure Examples} In follow-up experiments, we found that increasing the number of parameters of the Transformer model five fold did not improve performance. If anything, variability was higher and mean accuracy was lower (see Appendix~\ref{app:model-size}). By contrast, increasing the number of exposure examples per primitive from one to 100 led to a significant improvement in generalization for all three models, though this increase was only applicable to lexical generalization cases (see Appendix~\ref{app:shots}). \section{Comparison to Related Work} Our aggregate results in Table~\ref{table:aggregate-results} are in line with recent work that has documented a significant discrepancy between neural models' excellent performance within distribution and their degraded performance out of distribution \citep{johnson2017clevr,lake2018generalization,hupkes2020compositionality}. Our finding of poor generalization to deeper nested structures aligns with the results of \citet{hupkes2020compositionality}. Given that deeper structures also tend to be longer than shallower ones, this finding also relates to the difficulty of generalization to longer sequences. One illustrative example is the poor performance of LSTMs on a SCAN split that requires generalizing from shorter to longer sequences. While several models have made significant improvements over other SCAN splits, progress on the length split remains minimal \cite{li2019compositional,lake2019compositional,gordon2020permutation}. The most similar work to ours is Compositional Freebase Questions (CFQ; \citealt{keysers2020measuring}), a synthetic dataset designed to test for compositional generalization in SQL parsing. COGS differs from CFQ in two main ways. First, compared to sentences with a SQL mapping, which are limited to questions and imperatives, the semantic representation used in COGS significantly extends the variety of expressions that can be assigned an interpretation. Second, in CFQ, challenging splits are defined by a similar primitive distribution but different distributions of the composed forms (``compound divergence''). This can lead to a training and test split that is not characterized by any principled linguistic difference. Following a stronger definition of compositionality, the generalization set in COGS includes combinations of primitives and syntactic roles that are novel (occurred zero times in training), without concern for matching the distribution of primitives across training and testing. Our work is related to but distinct from work that tests language models for systematic syntactic generalization \citep[\textit{i.a.}]{gulordava2018colorless,marvin2018targeted}. Unlike our work, the language modeling setup does not directly evaluate the \textit{meaning} that the model assigns to a sentence. \section{Constraints on Generalization} \label{sec:overgeneralization} To reach full adult linguistic competence, human learners not only need to be able to make abstraction-based generalizations, but also need to learn how to constrain them. For example, the verb \textit{donate} takes a recipient \textit{to}-PP (\textit{Emma donated the book to the museum}) but does not allow double-object alternation (*\textit{Emma donated the museum the book}). How constraints as such could be learned has been discussed in linguistics under the banner of the projection problem \citep{baker1979syntactic}. COGS focuses on evaluating computational models' ability to make systematic generalizations, but not on evaluating the ability to constrain them. For this reason, COGS only includes examples to which generalizations are applicable (e.g., dative verbs that alternate). This is a simplification; in natural language, generalizations are not applicable across-the-board, and are modulated by a multitude of morphophonological, syntactic and semantic factors. In the case of the dative alternation, properties such as animacy and definiteness are involved \citep{bresnan2010predicting}. Thus, evaluating constraints on generalization requires a detailed characterization of factors that govern individual generalization cases, as well as a formalism capable of expressing these factors, which we leave to future work. \section{Conclusion} We have proposed COGS, a challenge set for compositional generalization, which uses a synthetic sentence-to-logical-form mapping task that approximates meaning interpretation in English. When tested on COGS, both Transformers and LSTMs performed poorly on the generalization set, with high variability across runs, while their performance on the in-domain test set was consistently near-perfect. Furthermore, the models found structural generalization much more challenging compared to lexical generalization. Our results suggest that achieving high generalization accuracy on COGS is beyond the capacity of models that we tested, and COGS can therefore motivate the development of new computational models. What architecture would be needed to solve COGS? For structural generalization cases, the results of \citet{bowman2015recursive,evans2018can} and \citet{mccoy-etal-2019-right} suggest that tree-structured models may provide a better inductive bias. In particular, \citet{bowman2015recursive} showed that tree-structured neural networks generalized to longer sequences. For lexical generalization cases, the RNN-based model from \citet{gordon2020permutation} that implements permutation equivariance may help, considering that it was able to solve all primitive generalizations in SCAN. \section*{Acknowledgments} We thank Sadhwi Srinivas and Kyle Rawlins for discussions about the logical form. We also thank Paul Smolensky, Benjamin Van Durme, and members of the JHU Neurosymbolic Computation Lab and the JHU Computation and Psycholinguistics Lab for their helpful feedback. TL was supported by National Science Foundation grant BCS-1920924.
{'timestamp': '2020-10-13T02:28:47', 'yymm': '2010', 'arxiv_id': '2010.05465', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05465'}
arxiv
\section{Introduction} \label{sec:introduction} Coreference resolution (CR) aims to determine whether two mentions (linguistic referring expressions) corefer or not, i.e., they refer to the same entity in the discourse model \citep{jurafsky2000speech,ding2010resolving,atkinson2015improving,lee2017end,lee2018higher,joshi2019bert,zhang2019knowledge}. The set of coreferring expressions forms a coreference chain or a cluster. Let's have an example: \begin{quote} \textbf{[S1]}~ \textit{{\color{blue}I} bought {\color{red} a green Moonbeam} for {\color{blue}myself}}. ~ \textbf{[S2]}~ \textit{{\color{blue}I} like \underline{{\color{red} its} voice} because \underline{it} is loud and long}. \end{quote} Here all colored and/or underlined phrases are mentions. Considering S1 (sentence-1) and S2 (sentence-2), the three mentions ``\textit{I}", ``\textit{myself}" in S1 and ``\textit{I}" in S2 all refer to the same person and form a cluster. Similarly, ``\textit{its}" in S2 refers to the object ``\textit{a green Moonbeam}" in S1 and the cluster is \{``\textit{its}"~(S2), ``\textit{a green Moonbeam}"~(S1) \}. The mentions ``\textit{its voice}" and ``\textit{it}" in S2 refer to the same attribute of the object ``\textit{a green Moonbeam}" in S1 and form cluster \{``\textit{its voice}"~(S2), ``\textit{it}"~(S2)\}. CR is beneficial for improving many down-stream NLP tasks such as question answering~\citep{dasigi2019quoref}, dialog systems~\citep{quan2019gecor}, entity linking~\citep{DBLP:conf/acl/KunduSFH18}, and opinion mining~\citep{nicolov2008sentiment}. Particularly, in opinion mining tasks~\cite{liu2012sentiment,wang2016attention,zhang2018deep,ma2020entity},~\citet{nicolov2008sentiment} reported performance improves by 10\% when CR is used. The study by \citet{ding2010resolving} also supports this finding. Considering the aforementioned example, without resolving ``\textit{it}" in S2, it is difficult to infer the opinion about the attribute ``\textit{voice}" (i.e., the \textit{voice}, which ``\textit{it}" refers to, is ``\textit{loud and long}"). Although CR plays such a crucial role in opinion mining, only limited research has been done for CR on opinionated reviews. CR in opinionated reviews (e.g., Amazon product reviews) \textit{mainly} concerns about resolving coreferences involving objects and their attributes. The objects in reviews are usually the names of products or services while attributes are aspects of those objects~\citep{liu2012sentiment}. Resolving coreferences in text broadly involves performing three tasks (although they are often performed jointly or via end-to-end learning): (1) identifying the list of mentions in the text (known as \textbf{\textit{mention detection}}); (2) given a pair of candidate mentions in text, making a binary classification decision: \textit{coreferring} or \textit{not} (referred to as \textbf{\textit{coreference classification}}), and (3) grouping coreferring mentions (referring to the same discourse entity) to form a coreference chain (known as \textbf{\textit{clustering}}). In reviews, \textbf{mention detection} is equivalent to extracting entities and aspects in reviews which has been widely studied in opinion mining or sentiment analysis~\cite{hu2004mining,qiu2011opinion,DBLP:conf/naacl/XuLSY19,DBLP:conf/acl/LuoLLZ19,wang2018disentangling,DBLP:journals/ipm/DragoniFR19,DBLP:journals/cluster/AsgharKZAK19}. Also, once the coreferring mentions are detected via classification, clustering them could be straightforward\footnote{Given a text (context), if pairs ($m$, $p$), ($m$, $q$) are classified as co-referring mentions, then $m$, $p$, $q$ belong to same cluster.}. Thus, following~\citep{ding2010resolving}, \textit{we only focus on solving the \textbf{coreference classification} task in this work, which we refer to as the \textbf{object and attribute coreference classification} (OAC2) task onwards.} We formulate the OAC2 problem as follows. \textbf{Problem Statement.} Given a review \textbf{\textit{text}} $u$ (context), an \textbf{\textit{anaphor}}\footnote{The term anaphor used in this work does not have to be the same as defined in other related studies, as here it can also appear before $m$ though rarely. We still name it as anaphor for simplicity, mainly following~\citep{ding2010resolving}.} $p$ and a \textbf{\textit{mention}} $m$ which refers to either an object or an attribute (including their position information), our goal is to \textit{predict whether the anaphor $p$ refers to mention $m$, denoted by a binary class $y \in \{0, 1\}$}. Note. an anaphor here can be a \textit{pronoun} (e.g., ``it") or \textit{definite noun phrase} (e.g., ``the clock") or \textit{ordinal} (e.g., ``the green one"). In general, to classify coreferences, one needs intensive knowledge support. For example, to determine that ``\textit{it}" refers to ``\textit{its voice}" in S2, we need to know that ``\textit{voice}" can be described as ``\textit{loud and long}" and ``\textit{it}" can not refer to ``\textit{a green Moonbeam}" in S1, since ``\textit{Moonbeam}" is a clock which cannot be described as ``\textit{long}". Product reviews contain a great many such domain-specific concepts like brands (e.g., ``\textit{Apple}" in the laptop domain), product name (e.g., ``\textit{T490}" in the computer domain), and aspects (e.g.``\textit{hand}" in the alarm clock domain) that often do not exist in general knowledge bases (KBs) like WordNet \citep{miller1998wordnet}, ConceptNet~\citep{singh2002open}, etc. Moreover, even if a concept exists in a general KB, its semantics may be different than that in a given product domain. For example, ``\textit{Moonbeam}" in a general KB is understood as ``\textit{the light of the moon}" or \textit{the name of a song}, rather than a clock (in the alarm clock domain). To encode such domain-specific concepts, we need to mine and feed domain knowledge (e.g., ``\textit{clock}'' for ``\textit{Moonbeam}'', ``\textit{laptop}'' for ``\textit{T490}'') to a coreference classification model. Existing CR methods \citep{zhang2019knowledge} do not leverage such domain knowledge and thus, often fail to resolve such co-references that require explicit reasoning over domain facts. In this paper, we propose to \textit{automatically} mine such domain-specific knowledge from \textit{unlabeled} reviews and leverage the useful pieces of the extracted domain knowledge together with the (general/comensense) knowledge from general KBs to solve the OAC2 task\footnote{The unlabeled data are from the same source as the annotated data (i.e., the same domain, but without labels), which can ensure the reliability of the domain knowledge as well as the coverage of mention words. With the domain-specific knowledge mined, the meaning of a mention in a certain domain can be better understood (by a model) with the support of its relevant mentions (extracted from the self-mined KB).}. Note the extracted domain knowledge and the general knowledge from the existing general KBs are both considered as candidate knowledge. To leverage such knowledge, we design a novel knowledge-aware neural coreference classification model that selects the useful (candidate) knowledge with attention mechanism. We discuss our approach in details in Section 3. The main contributions of this work can be summarized: \begin{enumerate} \vspace{-0.2cm} \item We propose a knowledge-driven approach to solving OAC2 in opinionated reviews. Unlike existing approaches that mostly dealt with general CR corpus and pronoun resolution, we show the importance of leveraging domain-specific knowledge for OAC2. \vspace{-0.2cm} \item We propose a method to automatically mine domain-specific knowledge and design a novel knowledge-aware coreference classification model that leverages both domain-specific and general knowledge. \vspace{-0.2cm} \item We collect a new review dataset\footnote{\url{https://github.com/jeffchen2018/review_coref}} with five domains or product types (including both unlabeled and labeled data) for evaluation. Experimental results show the effectiveness of our approach. \end{enumerate} \section{Related Work} \label{sec:relatedwork} Coreference resolution has been a long-studied problem in NLP. Early approaches were mainly rule-based~\citep{hobbs1978resolving} and feature-based~\citep{ding2010resolving,atkinson2015improving} where researchers focused on leveraging lexical, grammatical properties and semantic information. Recently, end-to-end solutions with deep neural models \citep{lee2017end,lee2018higher,joshi2019bert} have dominated the coreference resolution research. But they did not use external knowledge. Conisdering CR approaches that use external knowledge, ~\citet{aralikatte2019rewarding} solved CR task by incorporate knowledge or information in reinforcement learning models. ~\citet{emami2018generalized} solved the binary choice coreference-resolution task by leveraging information retrieval results from search engines. ~\citet{zhang2019incorporating,zhang2019knowledge} solved pronoun coreference resolutions by leveraging contextual, linguistic features, and external knowledge where knowledge attention was utilized. However, these works did not deal with opinionated reviews and also did not mine or use domain-driven knowledge. In regard to CR in opinion mining, ~\citet{ding2010resolving} formally introduced the OAC2 task for opinionated reviews, which is perhaps the only prior study on this problem. However, it only focused on classifying coreferences in comparative sentences (not on all review sentences). We compare our approach with \citep{ding2010resolving} in Section 4. Many existing general-purpose CR datasets are not suitable for our task, which include MUC-6 and MUC-7 \citep{hirschman1998appendix}, ACE~\citep{doddington2004automatic}, OntoNotes \citep{pradhan2012conll}, and WikiCoref \citep{ghaddar2016wikicoref}. \citet{bailey2015winograd} proposed an alternative Turing test, comprising a binary choice CR task that requires significant commonsense knowledge. ~\citet{yu2019you} proposed visual pronoun coreference resolution in dialogues that require the model to incorporate image information. These datasets are also not suitable for us as they are not opinionated reviews. We do not focus on solving pronoun resolution here because, for opinion text such as reviews, discussions and blogs, personal pronouns mostly refer to one person~\citep{ding2010resolving}. Also, we aim to leverage domain-specific knowledge on (unlabeled) domain-specific reviews to help the CR task which has not been studied by any of these existing CR works. \section{Proposed Approach} \label{sec:model} \textbf{Model Overview.} Our approach consists of the following three main steps: \textbf{(1) knowledge aquisition}, where given the (input) pair of mention $m$ (e.g., ``\textit{a green Moonbeam}'') and anaphor $p$ (e.g., ``\textit{it}'') and the context $t$ (i.e., the review text), we acquire candidate knowledge involving $m$, denoted as $K_m$.~$K_m$ consists of both domain knowledge (mined from unlabeled reviews) as well as general knowledge (compiled from existing general KBs) (discussed in Section 3.1). Next, in \textbf{(2) syntax-based span representation}, we extract syntax-related phrases for mention $m$ and anaphor $p$. Syntax-related phrases are basically noun phrases, verbs or adjectives that have a dependency relation\footnote We use \url{spacy.io} for dependency parsing, POS tagging and Named Entity Recognition (NER) in our implementation.} with $m$ (or $p$). For example, ``\textit{bought}" is a syntax-related phrase of the mention ``\textit{a green Moonbeam}'' and ``\textit{like}" and ``\textit{voice}" are two syntax-related phrases for the anaphor ``it" in the example review text in Section 1. Once the syntax-related phrases are extracted and the candidate knowledge is prepared for $m$ and $p$, we learn vector representations of the phrases and the knowledge (discussed in Section 3.2), which are used in step-3. Finally, in \textbf{(3) knowledge-driven OAC2 model}, we select and leverage useful candidate domain knowledge together with general knowledge to solve the OAC2 task. Figure~\ref{fig:model} shows our model architecture. Table~\ref{table:notation} summarizes a (non-exhaustive) list of notations, used repeatedly in subsequent sections. \begin{table} \centering \caption{\small Summary of notations (non-exhaustive list)} \label{table:notation} \scalebox{0.84}{ \begin{tabular}{lp{6.5cm}} \hline $d$ & a domain\\ $t$ & a review text or context\\ $m$ & a mention \\ $p$ & an anaphor \\ $K_m$ & (domain+general) knowledge involving $m$ for domain $d$ \\ $K^d_m$ & domain knowledge involving $m$ for $d$\\ $S_m$ & syntax-related phrases of $m$ \\ $S_p$ & syntax-related phrases of $p$\\ $T_d$ & labeled reviews in $d$\\ $\overline{T}_d$ & unlabeled reviews in $d$\\ \hline \end{tabular} } \label{tab:plain} \vspace{-0.3cm} \end{table} \begin{figure*} \centering \includegraphics[width=6.25in]{model_camera.png} \caption{\label{fig:model}The architecture of our knowledge-driven OAC2 model. } \vspace{-0.2cm} \end{figure*} \subsection{Knowledge Acquisition} \label{subsec:extraction} ~~~\textbf{Domain Knowledge Mining.} Given the mention $m$, we first split the mention into words. Here, we only keep the words that satisfy one of the following two conditions\footnote{When only using two features of words, we already achieve good results. More features are left for future work.}: (1) a word is a noun (determined by its POS tag); (2) a word is part of a named entity (by NER). For example, ``\textit{a westclox clock}" will result in words ``\textit{westclox}" and ``\textit{clock}". We use the mention words as the keys to search a domain knowledge base (KB) to retrieve domain knowledge for the mention $m$. To construct the domain KB, we use unlabeled review data in the particular domain. Specifically, all unlabeled sentences that contain mention words are extracted. Next, we collect domain knowledge for $m$ as $K^d_m$, where $K^d_m$ = $\{k^d_{m,1}, k^d_{m,2}, ... \}$. The elements in $K^d_m$ are phrases of nouns, adjectives, and verbs co-occurring with $m$ in the unlabeled review sentences. \textbf{Domain Knowledge Filtering.} Some domain knowledge (i.e., co-occurring phrases) can be too general to help reason over the mention. For example, given mention ``\textit{Moonbeam}", the verb ``\textit{like}" can be related to any objects or attributes and thus, is not a very useful knowledge for describing the mention. To filter such unimportant phrases from $K_m^d$, we use $tf\mhyphen idf$~\citep{aizawa2003information} scoring. Given mention $m$ and a phrase $k \in K_m^d$, we compute $tf\mhyphen idf$ score of $k$, denoted as $tf\mhyphen idf_{k}$ as given below: \vspace{-1mm} \begin{align} tf_{k} &= \frac{C_{k}}{max_{k'\in K^d_{m}} C_{k'}}\\ idf_{k} &= \log \frac{\vert \overline{T}_d \vert} {\vert \lbrace t' \in \overline{T}_d : k \in t' \rbrace \vert} \end{align} \vspace{-0.35cm} \begin{align} tf\mhyphen idf_{k} &= tf_{k} \cdot idf_{k} \end{align} where $C_{k}$ denotes the co-occurrence count of phrase $k$ with $m$ in unlabeled domain reviews $\overline{T}_d$ and $\vert{\cdot}\vert$ denotes set count. We retain phrase $k$ in $k_m^d$, if $tf\mhyphen idf_k \geq \rho$, where $\rho$ is a (empirically set) threshold value. \textbf{General Knowledge Aquisition.} General Knowledge bases like ConceptNet, WordNet, etc. store facts as triples of the form ($e_1$, $r$, $e_2$), denoting entity $e_1$ is related to entity $e_2$ by a relation $r$. e.g., (``\textit{clock}", ``\textit{UsedFor}", ``\textit{set an alarm}"). To acquire and use general knowledge for mention $m$, we first split $m$ into words (in the same way as we do during domain knowledge construction) and use these words as keywords to retrieve triples such that one of the entities (in a given triple) contains a word of $m$. Finally, we collect the set of entities (from the retrieved triples) as general knowledge for $m$, by selecting the other entity (i.e., instead of the entity involving a mention word) from each of those retrieved triples. \subsection{Syntax-based Span Representation} \label{subsec:span} Once the domain-specific and general knowledge for mention $m$ is acquired, we extract all syntax-related phrases for $m$ and anaphor $p$ from review text $t$ (see ``Model Overview" in Section 3). We denote the syntax-related phrases of $m$ and $p$ as $S_m$ and $S_p$ respectively. We represent mention, anaphor, the syntax-related phrases, and also the phrases of knowledge from domain-specific and general KBs as \textbf{spans} (a continuous sequence of words), and learn a vector representation for each span (we call it a \textbf{span vector}) based on the embeddings of words that compose the span. The span vectors are then used by our knowledge-driven OAC2 model (discussed in Section 3.3) for solving the OAC2 task. Below, we discuss the span vector representation learning for a given span (corresponding to a syntax-related phrase or a phrase in KB). We use BERT~\citep{devlin2018bert} to learn the vector representation for each span. To encode the words in a span, we use BERT's WordPiece tokenizer. Given a span $x$, let $\{x_i\}_{i=1}^{N_1}$ be the output token embeddings of $x$ from BERT, where $N_1$ is the total number of word-piece tokens for span $x$. BERT is a neural model consisting of stacked attention layers. To incorporate the syntax-based information, we want the head of a span and words that have a modifier relation to the head to have higher attention weights. To achieve the goal, we adopt syntax-based attention \citep{he2018effective}. The weight of a word in a span depends on the dependency parsing result of the span. Note, the dependency parsing of a span is different from what is described in Section~\ref{subsec:extraction}. The dependency parsing in Section~\ref{subsec:extraction} extracts the relation between chunks of words while here we extract relations between single words. An example has been shown in top left corner of Figure~\ref{fig:model}. The head of ``\textit{a green Moonbeam}" is ``\textit{Moonbeam}" that we want to have the highest attention weight when computing the embedding of the span. The distance of (``\textit{a}", ``\textit{Moonbeam}") and (``\textit{green}", ``\textit{Moonbeam}") considering the dependency path are both 1. To learn the span vector $v_x$ for span $x$, we first compute the attention weights $b_i$'s for each $x_i$, as: \begin{align} f_i &= FFN_1([x_i, x_{head}, x_i\odot x_{head}])\\ a_i &= \begin{cases} \frac{1}{2^{l_i}}\cdot exp(f_i), &if ~l_i\le L\\ 0, & otherwise\\ \end{cases}\\ b_i &= \frac{a_i}{\sum_{j=1}^{N_1} a_j} \end{align} where $FFN_1$ is a feed-forward layer that projects the input into a score $f_i$, $\odot$ is element-wise multiplication, $[,]$ is concatenation, $x_{head}$ is the head of the span, $l_i$ is the distance to the head along the dependency path, $L$ is the attention window size. Next, we learn the attention-based representation of the span $x$, denoted as $\hat{x}$ as: \begin{align} \hat{x} &= \sum_{i=1}^{N_1} b_i \cdot x_i \end{align} Finally, we concatenate the start and end word embeddings of the span $x_{start}$ and $x_{end}$, attention-based representation $\hat{x}$ and a length feature $\phi(x)$ following~\citep{lee2017end} to learn span vector $v_x$: \begin{align} v_x &= FFN_2([x_{start}, x_{end}, \hat{x}, \phi(x)]). \end{align} where $FFN_2$ is a feed-forward layer. \subsection{Knowledge-driven OAC2 Model} \label{subsec:model} The knowledge-driven OAC2 model leverages the syntax-related phrases together with the domain knowledge and general knowledge to solve the OAC2 task. The model first computes three relevance scores: \textbf{(a)} a contextual relevance score $F_C$ between $m$ and $p$, \textbf{(b)} a knowledge-based relevance score $F_K$ between $m$ and $p$, and \textbf{(c)} a relevance score $F_{SK}$ between knowledge and syntax-related phrases (see Figure~\ref{fig:model}) and then, these scores are summed up to compute the final prediction score $\hat{F}$, as shown below: \begin{equation}\label{2-def} \scalebox{1.0}{$ \hat{F}=~ sigmoid(F_C+F_K+F_{SK})$} \end{equation} \vspace{1mm} \textbf{(a) Contextual Relevance Score ($F_C$).} $F_C$ is computed based on the context $t$, mention $m$ and anaphor $p$. We use BERT to encode $t$. Let the output BERT embeddings of words in $t$ be $\{t_i\}_{i=1}^{N_2}$, where $N_2$ is length of $t$. Also, let the span vector representations of $m$ and $p$ are $v_m$ and $v_p$ respectively. Then, for each $v \in \{v_m, v_p\}$, we compute cross attention between $t$ and $v$ as follows: \begin{align} g_i &= FFN_3([t_i, v, t_i\odot v])\\ w_{i}^v &= \frac{e^{g_i}}{\sum_{j=1}^{N_2} e^{g_j}}\cdot t_i \end{align} where $FFN_3$ is a feed-forward layer. We learn the interaction of $\{t_i\}_{i=1}^{N_2}$ with $v_m$ and $v_p$ to get attention-based vector representations $\{w_i^m\}_{i=1}^{N_2}$ and $\{w_i^p\}_{i=1}^{N_2}$ for $m$ and $p$ respectively. Next, we concatenate these vectors and their point-wise multiplication for each context word, sum up the concatenated representations and feed it to a feed-forward layer to compute $F_C \in \mathcal{R}^{1 \times 1}$: \begin{align} F_C &= FFN_4(\sum_{i=1}^{N_2} [w_i^{m}, w_i^{p}, w_i^{m}\odot w_i^{p}]) \end{align} where $FFN_4$ is a feed-forward layer. \vspace{1mm} \textbf{(b) Knowledge-based Relevance Score ($F_K$).} The OAC2 model leverages the external knowledge to compute a relevance score $F_K$ between $m$ and $p$. Let $v_m$ and $v_p$ be the span vectors for $m$ and $p$ and $\{v_{i}^K\}_{i=1}^{N_3}$ be the span vectors for phrases in $K_m$ (see Sec 3.1 and Table 1), where $N_3$ is size of $K_m$. Then, we compute $F_K$ using $v_m$, $v_p$ and $\{v_{i}^K\}_{i=1}^{N_3}$ as discussed below. To leverage external knowledge information, we first learn cross attention between the mention and the knowledge as: \begin{align} h_i &= FFN_5([v_{i}^K, v_m, v_{i}^K\odot v_m])\\ c_i &= \frac{e^{h_i}}{\sum_{j=1}^{N_3} e^{h_j}} \end{align} where $FFN_5$ is a feed-forward layer. Next, we learn an attention-based representation $\hat{v}_m$ of mention $m$ as: \begin{align} \hat{v}_m &= \sum_{i=1}^{N_3} c_i \cdot v_{i}^K \end{align} We now concatenate $v_m$, $v_p$, the attention-based representation $\hat{v}_m$ and learn interaction between them to compute $F_K \in \mathcal{R}^{1 \times 1}$ as: \begin{align} \scalebox{0.99}{$ F_K = FFN_6([v_m, v_p, \hat{v}_m, v_p \odot \hat{v}_m, v_p \odot \hat{v}_m])$ } \end{align} where $FFN_6$ is a feed-forward layer. \vspace{1mm} \textbf{(c) Syntax-related Phrase Relevance Score ($F_{SK}$).} $F_{SK}$ measures the relevance between the knowledge (i.e., phrases) in $K_m$ and the syntax-related phrases in $S_m$ ($S_p$) corresponding to $m$ ($p$). Let $v_i^{K}$ be the span vector for $i^{th}$ phrase in $K_m$ and $v_i^{m}$ ($v_i^{p}$) be the span vector for $i^{th}$ phrase in $S_m$ ($S_p$). Then, we concatenate these span vectors row-wise to form matrices $M_{K}$ = $v_i^{K}\concat_{i=1}^{N_3}$ $\in \mathcal{R}^{N_3 \times d}$, $M_{Sm}$ = $v_i^{m}\concat_{i=1}^{N_4} \in \mathcal{R}^{N_4 \times d}$ and $M_{Sp}$ = $v_i^{p}\concat_{i=1}^{N_5} \in \mathcal{R}^{N_5 \times d}$ respectively, where $\concat_{i=1}^{Q}$ denotes concatenation of $Q$ elements, $d$ is dimension of span vector, $N_4$ ($N_5$) is size of $S_m$ ($S_p$). Next, we learn interaction between these matrices using scaled dot attention~\citep{vaswani2017attention} as: \begin{align} \tilde{M}_{Sm} &= softmax(\frac{M_{Sm}M_{K}^T}{\sqrt{d}})M_{K}\\ \tilde{M}_{Sp} &= softmax(\frac{M_{Sp}M_{K}^T}{\sqrt{d}})M_{K} \end{align} Finally, the syntax-related phrase relevance score $F_{SK} \in \mathcal{R}^{1 \times 1}$ is computed as: \begin{align} F_{SK} =FFN_8( FFN_7(\tilde{M}_{Sm}\tilde{M}_{Sp}^T)) \end{align} where $FFN_7$ and $FFN_8$ are two feed-forward network layers. \vspace{1mm} \textbf{Loss Function.} As shown in Equation~\ref{2-def}, given three scores $F_C$, $F_K$, and $F_{SG}$, we sum them up and then feed the sum into a sigmoid function to get the final prediction $\hat{F}$. The proposed model is trained in an end-to-end manner by minimizing the following cross-entropy loss $\mathcal{L}$: \begin{equation}\label{1-def} \mathcal{L} = -\frac{1}{N}\sum_i^N[y_i \cdot \log(\hat{F_i}) + (1-y_i)\cdot \log(1-\hat{F_i})] \end{equation} where, $N$ is the number of training examples and $y_i$ is the ground truth label of $i^{th}$ training example. \begin{table} \small \centering \caption{\small Dataset Statistics. \#R means the number of annotated reviews and \#E indicates total entities that refer to objects or attributes. P and N stand for positive and negative examples and the values under them are the numbers of those examples.} \label{table:dataset} \begin{tabular}{lcccccccc} \hline \multirow{2}{*}{\textbf{Domain}} & \multirow{2}{*}{\textbf{\#R}} & \multirow{2}{*}{\textbf{\#E}} & \multicolumn{2}{c}{\textbf{Train}} & \multicolumn{2}{c}{\textbf{Dev}} & \multicolumn{2}{c}{\textbf{Test} }\\ \cline{4-9} & & & \textbf{P} & \textbf{N} & \textbf{P} & \textbf{N} & \textbf{P} & \textbf{N}\\ \hline alarm & 100 & 924 & 647 & 1533 & 96 & 243 & 89 & 187 \\ camera & 100 & 871 & 632 & 1709 & 69 & 160 & 83 & 174 \\ cellphone& 100 & 938 & 679 & 1693 & 62 & 148 & 73 & 189 \\ computer & 100 & 1035 & 703 & 1847 & 86 & 227 & 112 & 273 \\ laptop & 100 & 893 & 641 & 1618 & 88 & 244 & 77 & 209 \\ \hline \end{tabular} \label{tab:plain} \vspace{-0.35cm} \end{table} \section{Experiments} \label{sec:experiment} We evaluate our proposed approach using five datasets associated with five different domains: (1) \textit{alarm clock}, (2) \textit{camera}, (3) \textit{cellphone}, (4) \textit{computer}, and (5) \textit{laptop} and perform both quantitative and qualitative analysis in terms of predictive performance and domain-specific knowledge usage ability of the proposed model. \subsection{Evaluation Setup} \label{subsec:setup} \vspace{1mm} {\large \textbf{Labelled Data Collection.}} We use the product review dataset\footnote{\url{https://www.cs.uic.edu/~zchen/downloads/ICML2014-Chen-Dataset.zip}} from ~\citet{chen2014topic}, where each product (domain) has 1,000 unlabeled reviews. For each domain, we randomly sample 100 reviews, extract a list of (\textit{mention}, \textit{anaphor}) pairs from each of those reviews and label them manually with ground truths. That is, given a review text and a candidate (\textit{mention}, \textit{anaphor}) pair, we assign a binary label to denote whether they co-refer or not. In other words, we view each labeled example as a triple ($u, m, p$), consisting of the \textbf{context} $u$, a \textbf{mention} $m$ and an \textbf{anaphor} $p$. Considering the review example (in Section 1), the triple (``\textit{I bought $\dots$ loud and long}", ``\textit{a green Moonbeam}", ``\textit{its}") is a positive example, since "\textit{a green Moonbeam}" and "\textit{its}" refers to the \textbf{same entity} (i.e., they are in the same coreference cluster). Negative examples are naturally constructed by selecting $m$ and $p$ from two different clusters under the same context like (``\textit{I bought $\dots$ loud and long}", ``\textit{a green Moonbeam}", ``\textit{its voice}"). Next, we randomly split the set of all labeled examples (for a given domain) into 80\% for training, 10\% as development, and rest 10\% as test data. The remaining 900 unlabeled reviews form the \textit{unlabeled domain corpus} is used for domain-specific knowledge extraction (as discussed in Section 3.1). All sentences in reviews and (\textit{mention}, \textit{anaphor}) pairs were annotated by two annotators independently who strictly followed the MUC-7 annotation standard~\citep{hirschman1998appendix}. The Cohen's kappa coefficient between two annotators is 0.906. When disagreement happens, two annotators adjudicate to make a final decision. Table~\ref{table:dataset} provides the statistics of labeled dataset used for training, development and test for each of the five domains. \vspace{1mm} \noindent {\large \textbf{Knowledge Resources.}} We used three types of knowledge resources as listed below. The first two are general KBs, while the third one is our mined domain-specific KB. \textbf{1. Commonsense knowledge graph (OMCS)}. We use the open mind common sense (OMCS) KB as general knowledge~\citep{singh2002open}. OMCS contains 600K crowd-sourced commonsense triplets such as (\textit{clock}, \textit{UsedFor}, \textit{keeping time}). We follow \citep{zhang2019knowledge} to select highly-confident triplets and build the OMCS KG consisting of total 62,730 triplets. \textbf{2. Senticnet}~\citep{cambria2016senticnet}. Senticnet is another commonsense knowledge base that contains 50k concepts associated with affective properties including sentiment information. To make the knowledge base fit for deep neural models, we concatenate SenticNet embeddings with BERT embeddings to extend the embedding information. \textbf{3. Domain-specific KB}. This is mined from the unlabeled review dataset as discussed in Sec~\ref{subsec:extraction}. \vspace{1mm} \noindent {\large \textbf{Hyper-parameter Settings.}} Following the previous work of~\citep{joshi2019bert,lee2018higher}, we use (Base) BERT\footnote{{\color{red}\url{https://storage.googleapis.com/bert_models/2020_02_20/uncased_L-12_H-768_A-12.zip}}} embeddings of context and knowledge representation (as discussed in Section 3). The number of training epochs is empirically set as 20. We train five models on five datasets separately, because the domain knowledge learned from a certain domain may conflict with that from others. Without loss of generality and model extensibility, we use the same set of hyper-parameter settings for all models built on each of the five different domains. We select the best model setting based on its performance on the development set, by averaging five F1-scores on the five datasets. The best model uses maximum length of a sequence as 256, dropout as 0.1, learning rate as $3e^{-5}$ with linear decay as $1e^{-4}$ for parameter learning, and $\rho = 5.0$ (threshold for \textit{tf-idf}) in domain-specific knowledge extraction (Section 3.1). The tuning of the other baseline models is the same as we do for our model. \vspace{1mm} \noindent {\large \textbf{Baselines.}} We compare following state-of-the art models from existing works on CR task: \textbf{(1) Review CR}~\citep{ding2010resolving}: A review-specific CR model that incorporates opinion mining based features and linguistic features. \textbf{(2) Review CR+BERT}: For a fairer comparison, we further combine BERT with features from~\citep{ding2010resolving} as additional features. Specifically, we combine the context-based BERT to compute $F_C(m,p)$ (see Section 3.3 (a)). \textbf{(3) C2f-Coref}~\citep{lee2018higher}: A state-of-the-art end-to-end model that leverages contextual information and pre-trained Glove embeddings. \textbf{(4) C2f-Coref+BERT}~\citep{joshi2019bert}: This model integrates BERT into C2f-Coref. We use its $independent$ setting which uses non-overlapping segments of a paragraph, as it is the best performing model in ~\citet{joshi2019bert}. \textbf{(5) Knowledge+BERT}~\citep{zhang2019knowledge}: This is a state-of-the-art knowledge-base model, which leverages different types of general knowledge and contextual information by incorporating an attention module over knowledge. General knowledge includes the aforementioned OMCS, linguistic feature and selectional preference knowledge extracted from Wikipedia. To have a fair comparison, we replace the entire LSTM-base encoder with BERT-base transformer. To accommodate the aforementioned baseline models into our settings, which takes \textit{context}, \textit{anaphor}, and \textit{mention} as input and perform binary classification, we change the input and output of the baseline models, i.e., the models compute a score between mention and anaphor and feeds the score to a sigmoid function to get a score within $[0, 1]$. Note, this setting is consistently used for all candidate models (including our proposed model). \vspace{1mm} \noindent {\large \textbf{Evaluation Metrics.}} As we aim to solve the OAC2 problem, a focused coreference classification task, we use the standard evaluation metrics \textit{F1-score} $(F1)$, following the same setting of the prior study~\cite{ding2010resolving}. In particular, we report positive (+ve) F1-score [F1(+)]. The average +ve F1-score is computed over five domains. \begin{table} \small \centering \caption{\label{table:result}\small Performance (+ve F1 scores) of all models on all test datasets. Here, ``cam'', ``com'', ``lap'' are the abbreviation for ``camera'', ``computer'', ``laptop'' respectively.} \label{tab:plain} \begin{tabular}{lcccccc} \hline \textbf{Model}&\textbf{alarm}&\textbf{cam}&\textbf{phone}&\textbf{com}&\textbf{lap}&\textbf{average}\\ \hline Review CR& 58.2&60.5&57.7&59.6&58.9&58.98\\ \hline Review CR& \multirow{2}{*}{67.2} & \multirow{2}{*}{69.3} & \multirow{2}{*}{67.0}& \multirow{2}{*}{68.4}& \multirow{2}{*}{66.7}& \multirow{2}{*}{67.72}\\ +BERT &&&&&&\\ \hline C2f-Coref&68.8& 70.1& 67.2& 69.5& 67.4&68.60\\ \hline C2f-Coref& \multirow{2}{*}{70.2} & \multirow{2}{*}{71.6} & \multirow{2}{*}{68.6}& \multirow{2}{*}{71.3}& \multirow{2}{*}{68.2}& \multirow{2}{*}{69.98}\\ +BERT &&&&&&\\ \hline Knowledge& \multirow{2}{*}{72.0} & \multirow{2}{*}{73.4} & \multirow{2}{*}{71.8}& \multirow{2}{*}{72.6}& \multirow{2}{*}{70.0}& \multirow{2}{*}{71.96}\\ +BERT &&&&&&\\ \hline Our model &\textbf{73.6}&\textbf{74.5}&\textbf{72.4}&\textbf{73.8}&\textbf{71.3}&\textbf{73.12}\\ \hline \end{tabular} \vspace{-0.35cm} \end{table} \subsection{Results and Analysis} \label{subsec:analysis} \vspace{1mm} \noindent {\large \textbf{Comparison with baselines.}} Table~\ref{table:result} reports F1 scores of all models for each of five domains and average F1 over all domains. We observe the following: (1) Overall, our model performs the best considering all five domains, outperforming the no-knowledge baseline model C2f-Coref+BERT by 3.14\%. On the cellphone domain, our model outperforms it by 3.8\%. (2) Knowledge+BERT turns out to be the strongest baseline, outperforming the other three baselines, which also shows the importance of leveraging external knowledge for the OAC2 task. However, our model achieves superior performance over Knowledge+BERT which indicates leveraging domain-specific knowledge indeed helps. (3) C2f-Coref+BERT achieves better scores than C2f-Coref and Review CR. This demonstrates that both representation (using pre-trained BERT) and neural architectures are important for feature fusions in this task. \begin{table} \small \centering \caption{\label{table:ablation}\small Performance of our model with different types of knowledge or module removed (-). $\Delta$ F1(+) is the performance difference between our model and model with module remove.} \begin{tabular}{p{1.7cm}p{2.9cm}cc} \hline \textbf{Comparison}&\textbf{Model} & \textbf{Avg. F1(+)} & \textbf{$\Delta$ F1(+)}\\\hline & Our model &73.12 & 0.00\\\hline Knowledge&-OMCS knowledge &72.28& 0.84\\ source&-Domain knowledge &72.22& 0.90\\ &-Senticnet &72.82&0.30\\ &-all knowledge &70.56&2.56\\\hline Score&-context $F_{c}$ &71.14&1.98\\ &-knowledge $F_K$ &71.80&1.48\\ &-phrase $F_{SG}$ &72.58&0.56\\\hline attention&-syntax-based attention &72.50&0.62\\ &\quad+dot attention &72.96&0.16\\ \hline \end{tabular} \vspace{-0.35cm} \end{table} \vspace{2mm} \noindent {\large \textbf{Ablation study.}} To gain further insight, we ablate various components of our model with the results reported in Table~\ref{table:ablation}. For simplicity, we only show the average F1-scores on the five domain datasets. The results indicate how each knowledge resource or module contributes, from which we have the following observations. \begin{enumerate} \vspace{-0.2cm} \item From comparison Knowledge resources in Table~\ref{table:ablation}, we see that domain knowledge contributes the most. General OMCS knowledge also contributes 0.84 to the model on average, so general knowledge is still needed. Senticnet contributes the least as it is more about sentiment rather than the relatedness between mentions. If we remove all knowledge sources (-all knowledge), performance drop becomes the highest which shows the importance of leveraging external knowledge in OAC2. \vspace{-0.2cm} \item Considering comparisons of various types of scores in Table~\ref{table:ablation}, we see that the disabling the use of context score $F_C$ has the highest drop in performance, showing the importance of contextual information for this task. Disabling the use of knowledge scores $F_{G}$ and $F_{SG}$ also impact the predictive performance of the model, by causing a drop in performance. \vspace{-0.2cm} \item From the comparison of attention mechanism for span representation in Table~\ref{table:ablation}, we see that, before summing up the embedding of each word of the span, the attention layer is necessary. Note, we use the selected attention instead of popular dot attention in~\citep{vaswani2017attention} during span representation. The influence of the syntax-based attention layer is slightly better than the dot attention layer. Therefore, we use the selected attention for better interpretability. \vspace{-0.2cm} \end{enumerate} \begin{table} \small \centering \caption{\label{table:casestudy}\small A test example from alarm domain with class probability distributions by three models during prediction.} \begin{tabular}{p{2.77cm}p{4.5cm}} \hline \textbf{Context} & ...after I bought {\color{blue} (a green Moonbeam} for myself ... potential buyer also should know that , as with (the other Westclox clock), {\color{blue} (the clock)} also have (a gold band) ... \\ \hline \textbf{(Mention, Anaphor)}& (\textit{a darkgreen Moonbeam}, \textit{the clock}) \\\hline \textbf{Domain knowledge}& drop, {\color{darkgreen}hang}, {\color{darkgreen}clock}, {\color{darkgreen}put}, {\color{darkgreen}alarm}, clear, beautiful, expensive, worthwhile ...\\ \hline \textbf{Our model} & (0: 0.47, 1: 0.53)\\ \hline \textbf{Knowledge+BERT} & (0: 0.87, 1: 0.13)\\ \hline \textbf{C2f-coref+BERT} & (0: 0.79, 1: 0.21)\\ \hline \end{tabular} \end{table} \begin{table} \small \centering \caption{\label{table:tfidf}\small An example showing the domain knowledge extraction quality of our model from laptop domain.} \begin{tabular}{p{3.33cm}p{4cm}} \hline \textbf{Mention (Domain)}& ~windows (laptop)\\\hline \textbf{Extracted knowledge (before filtering)} & ~keep, like, product, battery, fast, {\color{darkgreen}microsoft}, {\color{darkgreen} system}, {\color{darkgreen} upgrade}, {\color{darkgreen}xp}, laptop.. \\\hline \textbf{Candidate knowledge (after filtering by $tf\mhyphen idf$)} & ~{\color{darkgreen} microsoft}, {\color{darkgreen} system}, {\color{darkgreen} upgrade}, {\color{darkgreen}xp}, laptop..\\\hline \end{tabular} \vspace{-0.35cm} \end{table} \vspace{1mm} \noindent {\large \textbf{Qualitative Evaluation.}} We first give a real example to show the effectiveness of our model by comparing it with two baseline models C2f-coref$+$BERT and Knowledge$+$BERT. Table~\ref{table:casestudy} shows a sample in the \textit{alarm} domain. Here the major difficulty is to identify ``Moonbeam" as a ``clock". Knowledge$+$BERT fails due to its lack of domain-specific knowledge. C2f-coref$+$BERT fails as well because it simply tries to infer from contextual information only, where there is no domain knowledge support. In contrast, with our domain-specific knowledge base incorporated, ``Moonbeam" can be matched to the knowledge like ``clock", ``alarm", and ``hang" which are marked with green color. So our model successfully addresses this case. In other words, in our model, not only the mention ``a green Moonbeam" but also syntax-related phrase ``a gold band" of ``the clock" will be jointly considered in reasoning. We can see the modeling superiority of our knowledge-aware solution. Table~\ref{table:tfidf} shows the effectiveness of our extraction module introduced in Section~\ref{subsec:extraction}, especially the usage of $tf\mhyphen idf$ to filter out useless knowledge. \section{Conclusion} \label{sec:conclusion} This paper proposed a knowledge-driven approach for object and attribute coreference classification in opinion mining. The approach can automatically extract domain-specific knowledge from unlabeled data and leverage it together with the general knowledge for solving the problem. We also created a set of annotated opinionated review data (including 5 domains) for object and attribute coreference evaluation. Experimental results show that our approach achieves state-of-the-art performance. \section*{Acknowledgments} This work was supported in part by two grants from National Science Foundation: IIS-1910424 and IIS-1838770, and one research gift from Tencent. \bibliographystyle{acl_natbib}
{'timestamp': '2021-07-20T02:10:33', 'yymm': '2010', 'arxiv_id': '2010.05357', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05357'}
arxiv
\section{Introduction} Clustering~\cite{jain1999data} has been a popular task in unsupervised learning. Clustering involves grouping a dataset of objects into a number of groups such that objects that are highly similar to one another are more likely to find themselves assigned to the same group, and vice versa. Clustering algorithms fall into one of many families, of which partitional and hierarchical algorithms are two main streams. Partitional clustering, arguably the more popular stream, considers grouping the dataset into a number of disjoint sets. The pioneering work in this family, $K$-Means clustering, dates back to the 1960s~\cite{macqueen1967some}. $K$-Means clustering is a partitional clustering algorithm that additionally outputs a prototypical object to {\it 'represent'} each cluster, which happens to simply be the cluster {\it centroid} within the basic $K$-Means formulation. The centroid output is often seen as very useful for scenarios such as for manual perusal to ascertain cluster characteristics, resulting in this paradigm of {\it 'centroid clustering'}~\cite{taillard2003heuristic} attracting much research interest. In alternative formulations within the centroid clustering paradigm, the prototypical object is set to be the medoid, which is a dataset object that is most centrally positioned; this is referred to as $K$-medoids~\cite{rdusseeun1987clustering} clustering or PAM\footnote{https://en.wikipedia.org/wiki/K-medoids}. 50+ years since $K$-Means, the basic $K$-Means formulation is still used widely and continues to inspire much clustering research~\cite{jain2010data}. The second popular family of clustering algorithms, that of hierarchical clustering, focuses on generating a hierarchy of clusters from which clusterings of differing granularities can be extracted. An early survey of hierarchical clustering methods appears at~\cite{murtagh1983survey}. Our focus in this paper is within the task of centroid clustering. \subsection{Membership Desert in Centroid Clustering}\label{sec:introdesert} In this paper, we problematize the notion of {\it cluster membership} in centroid clustering from a conceptual and normative perspective. Our work is situated within the context of recent interest in fairness and ethics in machine learning (e.g.,~\cite{loi2019include}), which focuses on embedding normative principles within data science algorithms in order to align them better with values in the modern society. In particular, we consider the question of {\it membership desert}, or what it means for an object to be deserving of being a member of a cluster, or a cluster to be deserving of containing a data object. Desert in philosophical literature\footnote{https://en.wikipedia.org/wiki/Desert\_(philosophy)} refers to the condition of being deserving of something; a detailed exposition of philosophical debate on the topic can be found within a topical encyclopaedia from Stanford\footnote{https://plato.stanford.edu/entries/desert/}. $K$-Means and most other formulations that build upon it have used a fairly simple notion of membership desert; that an object be assigned to the cluster to whose prototype it is most proximal, according to a task-relevant notion of similarity. While this simple notion makes intuitive sense as well as enables convenient optimization, it admits unintuitive outcomes as we will see later. There have been two recent works in re-considering membership desert in centroid clustering, both within the umbrella of research in fair machine learning. The first work~\cite{chen2019proportionally} considers a notion of {\it collective desert} to blend in with the $K$-Means framework, whereby a reasonably large set of objects is considered to be deserving of their own cluster as long as they are collectively proximal to one another. The second work~\cite{repfairness} considers the distance-to-centroid as a cost of abstraction incurred by objects in the dataset, and strives to achieve a fair distribution of the cost of abstraction across objects. We will discuss these in detail in a later section. In this work, we consider advancing a third distinct normative consideration in membership desert, that of {\it local connectivity}. At the high level, we consider the membership desert associated with an object-cluster pair as being intimately related to the extent of the object's neighbors' affinity towards the cluster in question. \subsection{Our Contributions} In what may be seen as a contrast to conventional research narratives within data analytics, our work is centered on advancing a particular normative consideration as opposed to a technological challenge. This is in line with recent work on fairness and ethics in AI, which have mostly appeared within data analytics avenues as well (e.g.,~\cite{abraham2020fairness,chen2019proportionally,bera2019fair}). Our contribution by way of this work is three-fold: \begin{itemize}[leftmargin=*] \item {\bf Local Connectivity as Membership Desert:} We develop an argument for considering {\it local connectivity} as a notion of membership desert in centroid clustering. Building upon this argument, we develop quantitative metrics to evaluate the extent to which local connectivity is being adhered to, within a clustering. \item {\bf LOFKM:} We develop a simple centroid clustering formulation, {\it LOFKM}, drawing inspiration from both centroid clustering and density-based clustering, that deepens local connectivity in clustering outputs. \item {\bf Evaluation:} Through an empirical evaluation over multiple real-world datasets, we illustrate that LOFKM is able to significantly improve alignment with local connectivity considerations at reasonable costs to clustering quality. \end{itemize} \noindent{\bf Roadmap:} We start by considering related work in Section~\ref{sec:relwork}, followed by an overview of membership desert in Section~\ref{sec:background}. This is followed by Section~\ref{sec:locconn} where we describe local connectivity as a distinct notion of membership desert and ways of quantifying it for a given clustering. Section~\ref{sec:lofkm} outlines a simple method for enhancing local connectivity in centroid clustering, codenamed $LOFKM$. This is followed by our experimental evaluation in Section~\ref{sec:expts}, a brief discussion in Section~\ref{sec:discussion} and conclusions in Section~\ref{sec:conclusions}. \section{Related Work}\label{sec:relwork} Given that our work advances a local neighborhood based normative consideration in clustering, we briefly summarize related work from (i) fair clustering, and (ii) local neighborhood estimations from the density-based clustering family. \begin{figure*}[t] \includegraphics[width=0.6\textwidth]{kmeanscritique.png} \caption{Two Cases for Section~\ref{sec:critiquekmeans}: Rough Illustration} \label{fig:kmcritique} \end{figure*} \subsection{Fair Clustering} There has been an emerging interest in fair clustering. Among the two notions of fairness, {\it individual} and {\it group} fairness~\cite{binns2020apparent}, fair clustering has largely seen explorations on the latter. Group fairness involves ensuring cluster-level representational parity of sensitive groups defined on attributes such as gender, race, ethnicity and marital status. This literature, initiated by a work on ingenious dataset pre-processing~\cite{chierichetti2017fair}, has seen work on embedding fairness within the optimization~\cite{abraham2020fairness} as well as in post-processing~\cite{bera2019fair}. These also differ in the number of types of sensitive attributes that they admit. An overview of recent work on group-fair clustering appears in~\cite{abraham2020fairness} (Ref. Table 1 therein). Research into individual fairness in clustering has a flavour of considering membership desert as the focus question; being pertinent to our work, we discuss this in detail in Section~\ref{sec:background}. \subsection{Local Neighborhood and Clustering}\label{sec:localneighborhood} Local neighborhood of objects has been the core consideration in work on density-based clustering, a field pioneered by the DBSCAN clustering algorithm~\cite{ester1996density}, followed by OPTICS~\cite{ankerst1999optics}. In our work, we will make use of a work that extends concepts from density-based clustering in order to identify the outlierness of dataset objects, called {\it Local Outlier Factor} (LOF)~\cite{breunig2000lof}. The structure of LOF relies on quantifying the {\it local density} around an object. The local density around an object is inversely related to the average {\it reachability} of the object to its $k$ nearest neighbors; with {\it reachability} being a lower-bounded version of distance between the objects. The local density around an object's neighbors is then contrasted with the object's own local density to arrive at the LOF, which is a non-negative real number. $LOF>1$ ($LOF<1$) is achieved by objects whose neighbors are in neighborhoods that are denser (sparser) than it's own, with $LOF=1$ indicating a good match between respective densities. Objects with high values of $LOF$, especially $LOF >> 1$, are considered density-based outliers, due to their (relative) lack of closeby neighbors. Over the past two decades, LOF has evolved to being a very popular outlier detection method, continuously inspiring systems work on improving efficiency (e.g.,a recent {\it fast LOF} work appears in~\cite{babaei2019detecting}), arguably adorning a place in the outlier detection literature only next to the analogous status of $K$-Means within clustering literature. \section{Background: Membership Desert in Centroid Clustering}\label{sec:background} Following up from Section~\ref{sec:introdesert}, we now cover more background on the notion of membership desert in $K$-Means, and recent fairness oriented re-considerations of the notion. \subsection{Critiquing K-Means' Membership Desert}\label{sec:critiquekmeans} Let us start with looking at the simple notion of membership desert used in $K$-Means, that an object deserves to be assigned to the cluster whose prototype\footnote{we use prototype and centroid interchangeably} it is most proximal to, proximity measured under a domain-specific notion of (dis)similarity that is deemed relevant to the clustering task. {\it First}, consider the case of two clusters, $A$ and $B$. Now, let an object $X_1$ be at a distance of $3$ and $5$ units from the prototypes of $A$ and $B$ respectively, as shown roughly in the first illustration in Fig~\ref{fig:kmcritique}. For another object $X_2$, also shown in the illustration, let the distances be $8$ and $6$ respectively. The simple $K$-Means ({\it argmin}) heuristic does the following assignment: $X_1 \in A$ and $X_2 \in B$. It may be noted that while considering proximity as membership desert as in $K$-Means, $X_1$ may be considered more deserving of being assigned to $B$ than $X_2$ is to $B$; this is so since $dist(X_1,B)<dist(X_2,B)$. However, the $K$-Means assignment is in conflict with this observation, due to the higher degree of proximity of $X_1$ to $A$. {\it Second}, consider a scenario with respect to the trio, $X_1$ in relation to $A$ and $B$, as shown in the right-side in Figure~\ref{fig:kmcritique}. Let $B$ be a naturally bigger and denser cluster with significant number of data objects within $6$ units of distance of it. On the other hand, let $A$ be a small cluster with most of its members being within $2$ units of distance around its prototype. In this setting, despite $dist(X_1,A) < dist(X_1,B)$, $X_1$ may be thought of as deserving of being located within $B$ since it is in the company of the large mass of points stretching to the proximity of $B$. This intuitive notion of membership desert also conflicts with the cluster assignment that $K$-Means does. In fact, this is also an fallout of a fundamental design assumption in $K$-Means, that clusters be modelled as being modeled as Voronoi cells. {\it While we do *not* argue that the $K$-Means choice is inferior to an alternative available choice, it may be seen that there are intuitive opportunities to critique the simple membership desert mechanism in $K$-Means, and that the choice of most proximal centroid is not the only natural choice.} It is also noteworthy that membership assignment is not a final $K$-Means step, making it not entirely appropriate to consider it in isolation as we have done so far. The cluster assignment step is interleaved with the centroid learning step, leading to an interplay of effects of each other. \subsection{Fairness-orientated Notions of Membership} As outlined earlier, there are two recent papers, that motivate different considerations in cluster membership assignment. \subsubsection{Proportionality~\cite{chen2019proportionally} or Collective Desert in Cluster Membership} $K$-Means uses a parameter, the number of expected clusters in the output, commonly denoted as $K$. Thus, on an average, there are $(n/K)$ objects in a $K$-Means cluster. Proportionality, a concept the authors propose, is the notion that if one can find a set of $\lceil n/K \rceil$ data objects that collectively prefer the same candidate centroid in lieu of their current assignments (which involve different centroids/clusters), they deserve a cluster of their own centered at the candidate centroid that they collectively prefer. A clustering would be regarded as violating proportionality if it involves denying this set of $\lceil n/K \rceil$ objects their own cluster that they deserve. They develop algorithms that generate {\it proportionally fair} clusterings, those that do not violate proportionality. \subsubsection{Representativity Fairness~\cite{repfairness}} A recent work considers human-in-the-loop analytics pipelines where each cluster centroid is perused in order to arrive at a single decision for all objects in the cluster. Within such pipelines and even more generally, objects that are far away from their assigned cluster centroids suffer a higher {\it 'representativity cost'} from the cluster-level abstraction of the dataset provided by the clustering. RFKM, the proposed method, seeks to level off this object-level cost across the objects in the dataset, and move towards what is called {\it representativity fairness}. Operationally, it considers re-engineering the $K$-Means steps in a way that chances of proximity violations such as those in the first example in Section~\ref{sec:critiquekmeans} are reduced. \begin{figure*} \includegraphics[width=0.6\textwidth]{motivation.png} \caption{Local Connectivity: Motivating Scenarios (best viewed in color)} \label{fig:motivation} \end{figure*} \section{Local Connectivity and Membership Desert}\label{sec:locconn} \subsection{Motivation} We first consider {\it local connectivity} as a concept and its relevance to membership desert in centroid clustering. Consider three motivating scenarios in Fig.~\ref{fig:motivation}. In each of these figures, the middle point is the designated cluster prototype for the blue cluster; in other words, we have zoomed in on the blue cluster prototype and excluded other points in the dataset (including those from blue or other clusters) from view. The other blue colored points are assigned to be part of the blue cluster, and the red colored points in Fig.~\ref{fig:motivation}(a) are part of a different (red) cluster. In each of these figures, we would like to consider the status of the black colored object, and how well it deserves to be part of the blue cluster, and thus to being {\it 'represented'} by the blue cluster's prototype in the cluster-level abstraction Fig~\ref{fig:motivation}(a) has the corresponding black object being closest to the blue cluster prototype among all three scenarios. However, its local neighborhood (think of it as perhaps the closest few data objects to itself) is largely from the red cluster. Intuitively, this makes it reasonable to argue that despite the proximity, the black object in Fig~\ref{fig:motivation}(a) is limited in how well it deserves to be part of the blue cluster; in other words, its membership desert to the blue cluster comes under question. Now, consider the scenario in Fig~\ref{fig:motivation}(b). The black object, while not as proximal as in the case of Fig.~\ref{fig:motivation}(a), is quite well connected to the blue cluster given that it has an {\it 'pull'} from its local neighborhood towards the blue cluster. This makes it more deserving of membership to the blue cluster. Lastly, consider Fig~\ref{fig:motivation}(c) where the black object is tucked into a corner within a sparse region of the space. It has a reasonable claim to membership in the blue cluster, due to its nearest neighbors being blue (despite them being quite far from itself); however, the strength of the claim is dented by its distance to the blue cluster prototype. In summary, we observe the following: \begin{itemize}[leftmargin=*] \item Fig~\ref{fig:motivation}(a): Despite proximity, the membership desert of the black object to the blue cluster is limited due to the local neighborhood being red. \item Fig~\ref{fig:motivation}(b): The black object is most deserving to be part of the blue cluster due to high local connectivity within the blue cluster and reasonable proximity to the blue cluster prototype. \item Fig~\ref{fig:motivation}(c): The black object may be considered as reasonably deserving of blue cluster membership, even though its distance from the blue cluster prototype reduces the strength of the claim. \end{itemize} In other words, these illustrative scenarios offer different trade-offs between the pull towards the blue cluster prototype offered by {\it local connectivity} and {\it proximity}. These, we hope, illustrates that local neighborhood connectivity to the cluster in question is a fairly crucial factor in assessing membership desert. Though we have used abstract examples to motivate local connectivity, this has real-world implications wherever clustering is used for consequential tasks; for a simple example, consider centroid clustering being used for {\it facility location} to determine locations of service facilities (e.g., post offices or hospitals) with people represented using their geographic co-ordinates. In facility location, assigning a person to a facility (located at a centroid) towards which she has few local neighbors may be seen as unjust as well as a decision that undermines social solidarity. While $K$-Means is evidently not directly accommodative of local connectivity considerations due to using proximity in cluster assignment, the family of density based clustering algorithms pioneered by DBSCAN~\cite{ester1996density,schubert2017dbscan} makes local neighborhood a prime consideration in forming clusters. However, the density-based clustering family does not offer a convenient prototype for each cluster, and is thus limited in its applicability to human-in-the-loop pipelines such as those outlined in~\cite{repfairness}. In particular, density-based clusterings could yield non-convex clusters, where the centroid computed over cluster objects could be situated outside the natural boundaries of the cluster. Our method, as we will see, will leverage concepts from local neighborhood assessments from the density-based clustering family, and use that within the framework of centroid clustering inspired by $K$-Means. \subsection{Quantifying Local Connectivity}\label{sec:quantloc} Local connectivity in cluster membership desert, as illustrated in the previous section, can be thought of as: {\it how well the local neighborhood of the data object supports its membership to the cluster in question}. We now consider quantifying local connectivity at the object level, which will be aggregated to the level of different clusters in order to arrive at a measure of how well local connectivity is adhered to, in a given clustering. This quantification would form an evaluation metric for assessing local connectivity in clustering. Consider an object whose cluster-specific local neighborhood is conceptualized as the set of its $t$ nearest neighbors (we use $t$ instead of the conventional $k$ to avoid conflict with the $K$ in $K$-Means) within the cluster in question. We would like the $t$ nearest neighbors to comprise objects that: \begin{itemize}[leftmargin=*] \item {\bf Offer a Cluster Pull:} We would like the neighbors to offer a pull in the direction towards the cluster prototype. While {\it pull} is admittedly an informal word, we believe it is fairly straightforward to interpret the meaning. To illustrate this notion, observe that the local neighborhood in Fig~\ref{fig:motivation}(a) was largely red objects which may be seen as pulling the object towards the red cluster. This is in sharp contrast with the local neighborhood pull towards the blue cluster in Fig~\ref{fig:motivation}(b). \item {\bf Are Proximal to the Object:} Even if the $t$ nearest neighbors are towards the cluster prototype and can be seen as offering a pull, such a pull is meaningless unless the neighbors are proximal to the object in question. For example, consider Fig~\ref{fig:motivation}(c) where the neighbors of the black object are all towards the blue cluster. However, the appeal of this pull is dented by the fact that the neighbors are quite distant from the black object. \end{itemize} We now quantify the above desired characteristics in the form of a quantitative measure, for a given clustering. Let $X$ be the data object in question, and $C$ be the cluster prototype to whom the local connectivity strength is to be estimated. The dataset of objects involved in the clustering is denoted as $\mathcal{X}$. Given our interest in quantifying the pull towards the cluster prototype, we first identify the set of $t$ nearest neighbors of $X$ that are both: (i) members of the cluster in question i.e., $C$, and (ii) lie {\it in between} $X$ and the cluster prototype for $C$. This set is denoted as $N_t^C(X)$: \begin{equation} N_t^C(X) = \mathop{\arg\min}_{S \subseteq C \wedge Satisfies(S,X,C) \wedge |S| = t} \sum_{s \in S} dist(s,X) \end{equation} where: \begin{multline} Satisfies(S,X,C) = \\ \bigwedge\limits_{s \in S} (dist(s,C) \leq dist(X,C)) \wedge (dist(X,s) < dist(X,C)) \end{multline} $Satisfies(.,.,.)$ enforces the condition that objects in $N_t^C(X)$ fall in between $C$ and $X$ through a distance check; the first distance condition checks whether each element $s$ is closer to $C$, and the second checks whether it is on the {\it 'same side'} of $C$ as $X$ is. Among objects that satisfy these conditions, $t$ of them that are most proximal to $X$ are chosen to form the set $N_t^C(X)$. It may be noted that in cases where there are not enough objects that satisfy the eligibility condition, $|N_t^C(X)|$ may be less than $t$. This is likely to happen when $C$ is very close to $X$; we will outline its implications later. \begin{figure} \includegraphics[width=0.4\columnwidth]{geometric.png} \caption{Quantifying Local Conenctivity Illustration} \label{fig:geometric} \end{figure} Our interest is now in assessing how well objects in $N_t^C(X)$ adhere to the {\it pull} and {\it proximity} heuristics outlined above. We use a simple geometric intuition in order to quantify these. Consider Figure~\ref{fig:geometric} where $X$ is the black object and $C$ is the big blue encircled object, as before. The small blue object is $s \in N_t^C(X)$. Consider the line joining $X$ and $C$ and $s$ shown as being projected on to the line. The {\it pull} heuristic would prefer the dotted line indicating the projection of $s$ to the line to be {\it as short as possible} since that would direct the pull offered by $s$ to be aligned towards $C$. The {\it proximity} heuristic, on the other hand, would prefer $s$ to be as close as possible to $X$, thus preferring that both the dotted lines be as short as possible. We would additionally like the local connectivity to be comparable across different data objects in $\mathcal{X}$. Thus, we measure the two distances indirectly in relation to the distance between $X$ and $C$, as two measures, {\it Deviation} (Dev) and {\it Normalized Distance} (ND), as follows: \begin{equation} Dev(X,C,s) = \frac{dist(C,s) + dist(s,X)}{dist(X,C)} - 1.0 \end{equation} \begin{equation} ND(X,C,s) = \frac{dist(X,s)}{dist(C,s) + dist(s,X)} \end{equation} $Dev(X,C,s)$ would evaluate to $0.0$ when $s$ falls directly on the line connecting $X$ and $C$, since that would ensure that $dist(C,s) + dist(s,X) = dist(X,C)$. $Dev(X,C,s)$ increases the more $s$ deviates from that line, leading to its name. $ND(X,C,s)$ on the other hand, measures the distance between $X$ and $s$ as a fraction of the distance between $X$ and $C$ through $s$. Thus, $ND(.,.,.)$, unlike $Dev(.,.,.)$ is directly related to the length of both dotted lines in Fig~\ref{fig:geometric}. Since we would like both of these measures to be numerically small ($\approx 0$), we would like to minimize the product of these, which we call as the {\it local connectivity disagreement} measure: \begin{equation} LCD(X,C,s) = Dev(X,C,s) \times ND(X,C,s) \end{equation} Higher values of $LCD()$ denote lower levels of {\it local connectivity} offered by $s$ to support the membership desert for the pair $X,C$. This disagreement may be aggregated across all objects in $N_t^C(X)$ to arrive at an object level estimate: \begin{equation} LCD(X,C) = \sum_{s \in N_t^C(X)} LCD(X,C,s) \end{equation} When $|N_t^C(X)|<t$, the $LCD$ would be correspondingly lower since there are fewer objects to sum over. Since we expect $|N_t^C(X)|<t$ to happen when $X$ is already very close to $C$, this translates to an alternative route to reduce $LCD$ for such objects; in addition to improving local connectivity by way of neighbors' positions, {\it $LCD$ can also be improved (i.e., numerically reduced) through enhanced proximity between objects and their cluster prototypes, which would lead to smaller $|N_t^C(X)|$}. Among objects in the cluster $C$, some may have high LCDs and some may have lower values for LCD. Towards assessing a cluster, consider using the average of the LCDs across all objects as an aggregate measure. This would enable a small set of objects with very shallow local connectivity (i.e., high LCD scores since LCD measures disagreement) to be ignored due to being compensated by a large number of low LCD scores across other objects in the cluster. This may be considered undesirable in the face of the high importance accorded to the concern for the most disadvantaged, such as in the very popular stream of Rawlsian notions of fairness~\cite{john1971theory}. Motivated by such considerations, we accord the cluster with an LCD value computed as the highest LCD (i.e., lowest local connectivity, since LCD measures disagreement) among its objects: \begin{equation} LCD(C) = \mathop{\max}_{X \in C} LCD(X,C) \end{equation} A clustering of a dataset would produce multiple clusters, since a clustering defines a partitioning. In order to arrive at a dataset-level measure of connectivity offered by a clustering, we would need an aggregate statistic at the dataset level. As in the case above, we would like to ensure that no cluster suffers from bad local connectivity, making the highest LCD among clusters a natural measure to minimize. We call this {\it MaxLCD}. Additionally, We would also like to minimize LCD across all clusters, making {\it AvgLCD} a very pertinent measure. \begin{equation} MaxLCD(\mathcal{C}) = \mathop{\max}_{C \in \mathcal{C}} LCD(C) \\ \end{equation} \begin{equation} AvgLCD(\mathcal{C}) = \frac{1}{|\mathcal{C}|} \sum_{C \in \mathcal{C}} LCD(C) \end{equation} These are analogous to the construction of Max Wasserstein and Avg Wasserstein used in evaluation of fair clustering~\cite{abraham2020fairness}. Thus, {\it MaxLCD} and {\it AvgLCD} offer quantifications of disagreement with local connectivity across the dataset, as manifested in the clustering $\mathcal{C}$. A good clustering would be one which, in addition to performing well on traditional clustering evaluation metrics such as {\it purity} and {\it silhoutte}, achieves {\it low values of MaxLCD and AvgLCD} (thus, high local connectivity). \subsection{Drawbacks of LCD Measures} While LCD measures are, we believe, a starting point for quantifying local connectivity, these are not free of shortcomings. We outline a few drawbacks, which could potentially point to ways of refining them to yield better metrics of local connectivity. {\it First}, both $Dev(.)$ and $ND(.)$, which form the building blocks of LCD measures, rely on distances expressed as fractions of other distances. This makes them unable to be sensitive to variations in absolute distances. Consider the case of $Dev(.)$; when $X$ and $C$ are close to each other, even slight deviations of $s$ from the straight line connecting them are amplified, with $dist(X,C)$ forming the denominator. Similarly, take the case of $ND(.)$; high values of $dist(C,s)$ push it towards $0.0$ by providing a very high denominator. When $X$ and $s$ are very far from $C$, even high values of $dist(X,s)$ could cause $ND(.) \approx 0$. Such cases make $LCD$ less meaningful to quantify the connectivity of fringe objects that are far from cluster prototypes. Any attempts at addressing such absolute distance issues should also care to retain the comparability of the resultant metrics across objects in the dataset. {\it Second}, we have excluded neighbors of $X$ that do {\it not} belong to the same cluster as $C$, from consideration in $N_t^C(X)$. This means that an object's neighbors' pull towards the assigned cluster is evaluated without regard to whether it has similar or stronger pulls towards other clusters. This, we believe, is a minor issue, since such stronger pulls towards a different cluster also would likely reduce cluster coherence in general. This means that any clustering that attempts to improve coherence of clusters in addition to local connectivity (such as our method, $LOFKM$, introduced later) would address this implicitly to some extent using the cluster coherence criterion. The above two sets of drawbacks are not meant to be comprehensive but to serve to provide a flavour of the possibilities of improving upon LCD measures, and the challenges in those directions. \section{LOFKM: Enhancing Local Connectivity in Clustering}\label{sec:lofkm} We have argued and motivated that local connectivity is a crucial factor in considering membership desert for an object to a cluster. Local neighborhood statistics has been extensively used in the stream of work on density-based clustering, initiated through the popular DBSCAN clustering method~\cite{ester1996density}. Density-based clustering has the ability to identify clusters that have non-convex shapes (e.g., can disambiguate star and crescent\footnote{https://en.wikipedia.org/wiki/Star\_and\_crescent} as separate clusters) and overlapping convex shapes (e.g., can identify rings arranged concentrically as separate clusters). However, this ability comes at a cost; density-based clustering inherently lacks the possibility of choosing a meaningful representative prototype for a cluster (e.g., in the above cases, observe that the centroid would lie outside the cluster itself and would be meaningless as a prototype). Our method, LOFKM, is the result of an attempt to bring a density-based flavour within $K$-Means framework, in order to improve local conncectivity considerations. Our design considerations are as follows: \begin{itemize}[leftmargin=*] \item {\it Conceptual Simplicity:} We would like to retain the conceptual simplicity inherent in $K$-Means which has likely been at the core of it's widespread popularity. Additionally, we would like to bring in density-based concepts within it in a lucid manner. \item {\it Computational Convenience:} The task of clustering is a dataset-level optimization problem which has inherent complexities. This makes directly using local connectivity measures (e.g., LCD) within the optimization infeasible. Due to solving a computational task, computational convenience is also a significant consideration. \end{itemize} \subsection{Towards a Method} As we have seen, {\it local connectivity} involves a relation between an object and a cluster prototype in the backdrop of the local neighborhood of the object {\it in the 'direction' of the cluster prototype}. It is important to note that the local neighborhood of an object is a property of its location within the similarity space provided by the pre-specified $[dataset, distance\ function]$ pair, and is in no way {\it 'alterable'} to nudge clustering towards deepening local connectivity (or any other consideration, for that matter). High $LOF$ (Ref. Sec~\ref{sec:localneighborhood}) objects are more likely to suffer from shallow local connectivity since their neighborhood is sparse; so the neighbors are unlikely to support their membership to any cluster by much. One way to enhance local connectivity would be through better {\it inlineness}, which would be to set cluster prototypes in such directions from high LOF objects within which they have many neighbors. This, however, would require a significantly different prototype construction, putting the conceptual simplicity of $K$-Means prototype estimation at risk. Yet another way would be to bring the cluster prototype towards such high $LOF$ objects, which would enhance their connectivity through both support from neighborhood as well as lower $|N_t^C(X)|$. This route is amenable to exploration while staying within the framework of the $K$-Means clustering formulation, and forms the basis of our {\it LOFKM} method. However, it risks bringing down the compactness of the cluster, which is a factor that would have repercussions on other metrics such as cluster purity and silhoutte as well. As obvious, deepening a particular normative consideration in any machine learning task is expected to introduce constraints that would reduce the clustering quality overall; in other words, higher local connectivity is not expected to come {\it 'for free'}. A good clustering under the local connectivity lens would be one that can deepen local connectivity with {\it limited impact} on other metrics of clustering quality; this, we will see, is the focus of our empirical evaluation. \subsection{LOFKM: The Method} In line with the idea of bringing cluster prototypes closer to higher LOF data objects, we start with assigning a weight to each data object, as follows: \begin{equation}\label{eq:lofweight} W(X) = \begin{cases} 1.0 & LOF(X) \leq 1 \\ LOF(X) & otherwise \end{cases} \end{equation} $W(X)$ is simply the LOF score bounded under by $1.0$. This weight is then used in re-formulating the standard $K$-Means objective as follows, for a given clustering $\mathcal{C}$ over the dataset: \begin{equation}\label{eq:objective} \sum_{C \in \mathcal{C}} \sum_{X \in C} W(X) \times \bigg( \sum_{A \in \mathcal{A}} (X.A - C.A)^2 \bigg) \end{equation} where $A$ is any attribute from the set of attributes $\mathcal{A}$, with $X.A$ and $C.A$ denoting the value taken for the attribute by the object $X$ and the cluster prototype of cluster $C$ respectively (notice that we have overloaded $C$ to denote both the cluster and its prototype for notational simplicity). Intuitively, this is equivalent to considering the dataset as comprising each object as being replicated as many times as its LOF score requires, and applying standard $K$-Means over the enlarged dataset. There are two sets of variables that we can change in order to optimize for the objective; the {\it cluster memberships} and {\it cluster prototypes}. Standard $K$-Means optimizes these in turn (keeping one set fixed, and optimizing for the other) over many iterations until the cluster memberships stabilize. Under the objective in Eq~\ref{eq:objective}, the membership assignment step, given the cluster prototypes, is as follows: \begin{equation}\label{eq:estep} \forall\ X \in \mathcal{X}, \ \ Cluster(X) = \mathop{\arg\min}_{C \in \mathcal{C}} \sum_{A \in \mathcal{A}} (X.A - C.A)^2 \end{equation} Since we are updating each object independently given the current estimate of cluster prototypes, $W(X)$ does not factor into this cluster assignment step since it is simply a constant factor for each $X$ independent of which cluster $X$ gets assigned to. This, as one may notice, is {\it exactly the cluster assignment step in $K$-Means}. It may sound odd as to why we critique the $K$-Means membership desert and still use it in {\it LOFKM}; the crucial factor here is that this proximity-based membership desert is used against a set of cluster prototypes that are estimated in very sharp contrast to the analogous step in $K$-Means. The {\it LOFKM} cluster prototype estimation step is as follows: \begin{equation}\label{eq:mstep} \forall\ A \in \mathcal{A}, \ \ C.A = \frac{\sum_{X \in C} W(X) \times X.A}{\sum_{X \in C} W(X)} \end{equation} In other words, each $X$ is accounted for as many times as warranted by $W(X)$. Towards generating a clustering from a dataset, much like in $K$-Means clustering, we start with a random initialization of cluster prototypes followed by iteratively applying Eq~\ref{eq:estep} and Eq~\ref{eq:mstep} until the cluster memberships become relatively stationary across iterations. Owing to these steps mirroring those of standard $K$-Means, we do not outline a full pseudocode for {\it LOFKM} herewith. \subsubsection{Note on Complexity} The $K$-Means steps, much like the usual $K$-Means algorithm, is linear in the number of objects, number of clusters and number of attributes. However, computing the weights, i.e., Eq~\ref{eq:lofweight}, is more expensive. While LOF computation is generally regarded as between superlinear and quadratic in the number of objects~\cite{breunig2000lof}, faster methods have recently been proposed~\cite{lee2016fast,babaei2019detecting}. It is notable that any further advancements in improving LOF computations readily transfer over to LOFKM as well, given that the LOF and $K$-Means steps are decoupled within LOFKM. \begin{table}[tbp] \begin{tabular}{|c|c|c|c|} \hline {\bf Name} & {\bf \# Instances} & {\bf \# Attributes} & {\bf \# Classes} \\ \hline Yeast & 1484 & 8 & 10 \\ \hline Wireless\footnote{short for Wireless Indoor Localization} & 2000 & 7 & 4 \\ \hline Avila & 20867 & 10 & 12 \\ \hline \end{tabular} \caption{Dataset Statistics} \label{tab:dataset} \end{table} \section{Experimental Evaluation}\label{sec:expts} We now describe our empirical evaluation. We start by outlining the datasets and baselines in our empirical evaluation, while also outlining the evaluation setup. This is followed by detailed results from empirical evaluation and analyses. \subsection{Datasets, Baselines and Evaluation Setup} \subsubsection{Datasets} We evaluate our methods on multiple real-world datasets from the UCI Machine Learning Repository. These have widely different numbers of objects, ranging from $1.5k$ to $21k$, and spread across $4-12$ classes. The dataset statistics are summarized in Table~\ref{tab:dataset}. \subsubsection{Baseline} Much like the only two existing papers that propose new normative considerations in clustering, that of proportionality~\cite{chen2019proportionally} and representativity~\cite{repfairness}, we use the classical $K$-Means formulation as the baseline method in our experimental evaluation. We do not include either of the above methods in our comparison since they optimize for significantly different notions of membership desert; as an example, it may be seen that the method from~\cite{chen2019proportionally} was used in the empirical evaluation for representativity in~\cite{repfairness}, and it was observed (unsurprisingly) that the basic $K$-Means fared much better than~\cite{chen2019proportionally} on representativity. \subsubsection{Evaluation Setup} We follow the evaluation framework for fair clustering (as in~\cite{abraham2020fairness,repfairness}), with the evaluation being conducted across two kinds of metrics; (i) {\it local connectivity} (analogous to fairness metrics in fair clustering) metrics, viz., {\it AvgLCD} and {\it MaxLCD}, and (ii) clustering quality metrics, viz., {\it silhoutte~\cite{rousseeuw1987silhouettes}} (Sil) and {\it clustering purity\footnote{https://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-clustering-1.html}} (Pur). For {\it LOFKM}, we expect improvements on the former, and setbacks on the latter. {\it LOFKM} may be judged to be effective if it is able to achieve good gains on the former set of metrics, at reasonable detriment to the latter. For both LOFKM and $K$-Means, we average the performance metrics across $100$ random starts, so as to achieve stable and reliable numbers. We always set the number of clusters in the output, i.e., the parameter $K$, to be equal to the number of classes in the respective datasets (Ref. Table~\ref{tab:dataset}). \begin{table*}[tbp] \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline \hline {\bf Dataset} & {\bf Method} & \multicolumn{3}{c|}{\it AvgLCD $\downarrow$} & \multicolumn{3}{c|}{\it MaxLCD $\downarrow$} \\ \cline{3-8} & & {\it t = 3} & {\it t = 4} & {\it t = 5} & {\it t = 3} & {\it t = 4} & {\it t = 5} \\ \hline \hline \multirow{3}{*}{Yeast} & KM & 0.93 & 1.18 & 1.42 & 1.20 & 1.57 & 2.00 \\ & LOFKM & 0.92 & 1.08 & 1.15 & 1.15 & 1.53 & 1.98 \\ \cline{2-8} & Improvement \% & 01.07\% & 08.47\% & 09.01\% & 04.17\% & 02.55\% & 01.00\% \\ \hline \multirow{3}{*}{Wireless} & KM & 1.24 & 1.68 & 2.04 & 1.32 & 1.79 & 2.24 \\ & LOFKM & 1.18 & 1.56 & 1.90 & 1.31 & 1.73 & 1.95 \\ \cline{2-8} & Improvement \% & 04.83\% & 07.14\% & 06.87\% & 00.76\% & 03.35\% & 12.95\% \\ \hline \multirow{3}{*}{Avila} & KM & 1.11 & 1.48 & 1.83 & 1.33 & 1.77 & 2.19 \\ & LOFKM & 0.99 & 1.31 & 1.61 & 1.32 & 1.80 & 2.19 \\ \cline{2-8} & Improvement \% & 10.81\% & 11.49\% & 12.02\% & 00.75\% & -01.69\% & 00.00\% \\ \hline \hline \multicolumn{2}{|c|}{Avg of Improvement \%} & 05.57\% & 09.03\% & 09.30\% & 01.89\% & 01.40\% & 04.65\% \\ \hline \hline \end{tabular} \caption{Evaluation on Local Connectivity Measures. Note that lower values are better for both {\it AvgLCD} and {\it MaxLCD}, as indicated using the arrow in the column heading.} \label{tab:lcd} \end{table*} \begin{table*}[tbp] \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline \hline {\bf Dataset} & {\bf Method} & \multicolumn{3}{c|}{\it Sil $\uparrow$} & \multicolumn{3}{c|}{\it Pur $\uparrow$} \\ \cline{3-8} & & {\it t = 3} & {\it t = 4} & {\it t = 5} & {\it t = 3} & {\it t = 4} & {\it t = 5} \\ \hline \hline \multirow{3}{*}{Yeast} & KM & \multicolumn{3}{c|}{0.26} & \multicolumn{3}{c|}{0.42} \\ \cline{3-8} & LOFKM & 0.27 & 0.27 & 0.26 & 0.41 & 0.41 & 0.41 \\ \cline{2-8} & Change \% & +03.84\% & +03.84\% & 00.00\% & -02.40\% & -02.40\% & -02.40\% \\ \hline \multirow{3}{*}{Wireless} & KM & \multicolumn{3}{c|}{0.40} & \multicolumn{3}{c|}{0.93} \\ \cline{3-8} & LOFKM & 0.39 & 0.39 & 0.39 & 0.77 & 0.78 & 0.78 \\ \cline{2-8} & Change \% & -02.50\% & -02.50\% & -02.50\% & -17.20\% & -16.13\% & -16.13\% \\ \hline \multirow{3}{*}{Avila} & KM & \multicolumn{3}{c|}{0.15} & \multicolumn{3}{c|}{0.46} \\ \cline{3-8} & LOFKM & 0.18 & 0.18 & 0.18 & 0.45 & 0.45 & 0.45 \\ \cline{2-8} & Change \% & 20.00\% & 20.00\% & 20.00\% & -02.17\% & -02.17\% & -02.17\% \\ \hline \hline \multicolumn{2}{|c|}{Avg of Change \%} & 07.11\% & 07.11\% & 05.83\% & -07.26\% & -06.90\% & -06.90\% \\ \hline \hline \end{tabular} \caption{Evaluation on Clustering Quality Measures. Note that higher values are better for both {\it Sil} and {\it Pur}, as indicated using the arrow in the column heading.} \label{tab:quality} \end{table*} \subsection{Experimental Results and Analysis} We first outline the structure of the experimental analysis. Local connectivity, as outlined in Sec~\ref{sec:quantloc}, is assessed using a parameter $t$, the number of relevant neighbors for an object; this parameter is used in the computation of both {\it MaxLCD} and {\it AvgLCD}. For {\it LOFKM}, there is a similar parameter in the input, which is the number of neighbors for an object used in LOF computation (Ref. Sec.~\ref{sec:localneighborhood}). These, being similar in spirit, are set to identical numbers, and we denote both as $t$. We experiment with varying values of $t$; in the interest of brevity, we report results for $t \in \{3,4,5\}$ as a representative set of results since the trends held good for higher values. $KM$, short for $K$-Means, does not use any neighborhood parameter in the method. The evaluation on fairness metrics is illustrated in Table~\ref{tab:lcd} whereas the evaluation on clustering quality appears in Table~\ref{tab:quality}. The percentage change of the {\it LOFKM} metric over that in {\it KM} is indicated explicitly, for ease of interpretation. An average of $5-10\%$ gains are achieved on the {\it AvgLCD} measure, indicating a sizeable improvement in local connectivity in the clusterings output by {\it LOFKM} over those of {\it KM}. Further, the improvements are seen to improve with the size of the dataset, which is expected since larger datasets allow for more flexibility in clustering assignments. The corresponding improvements in {\it MaxLCD} are seen to be smaller. {\it MaxLCD} quantifies the worst local connectivity across clusters, and thus relates to the quantification over a single cluster, which in turn is the worst local connectivity across members of the cluster. While it would intuitively be expected that least locally connected objects which would be in sparse regions where local connectivity improvements would be harder to achieve, it is promising to note that {\it LOFKM} consistently achieves improvements on {\it MaxLCD} over {\it Yeast} and {\it Wireless}; the corresponding improvements in {\it Avila} are limited, and negative in one case. The trends on the clustering quality metrics in Table~\ref{tab:quality} may be regarded as quite interesting. It may be noted that $t$ does not play a role for results of {\it KM} since the clustering quality metrics as well as $KM$ are agnostic to $t$. As outlined earlier, we expect that the cost of local connectivity enhancement in {\it LOFKM} would manifest as a deterioration in clustering quality. While we can observe such deterioration in {\it Pur} in Table~\ref{tab:quality}, {\it LOFKM} is surprisingly able to achieve improvements in {\it Sil} on the {\it Yeast} and {\it Avila} datasets. On careful investigation, we found evidence to hypothesize that {\it LOFKM} discovers {\it secondary clustering structures}, which differ from the primary ones that are better correlated with external labels ({\it Pur}, as one might remember, measures correlation with external labels). These secondary clustering structures, while not necessarily tighter, are found to be well separated, yielding improvements in {\it Sil}. This interestingly correlates with similar observations over {\it Sil} in representativity fairness (Ref. Sec. 6.3.2 in~\cite{repfairness}). In contrast to {\it Yeast} and {\it Avila}, {\it Wireless} does not seem to exhibit such well-separated secondary structures, leading to falls in both {\it Sil} and {\it Pur}. Across datasets, the deterioration in {\it Pur} is seen to be fairly limited, to within $10\%$; we would re-iterate that the fact that such deterioration comes with an improvement in {\it Sil} indicates the promisingness of {\it LOFKM}. To summarize, {\it LOFKM} is seen to offer consistent and often sizeable improvements in local connectivity, with mixed trends in clustering quality. \section{Discussion}\label{sec:discussion} Having considered local connectivity as a factor for membership desert in clustering, it is useful to think about how this relates to other notions and other factors that may be argued to play a role in membership desert. Local connectivity is distinctly different from {\it representativity}~\cite{repfairness} in that an object that is very distant from the cluster prototype could still be locally connected to the very same cluster. While this conceptual distinction cannot be more apparent, in practice, we expect peripheral/fringe objects of a cluster to suffer from local connectivity, and similar could be true for representativity as well. In a way, local connectivity provides a way to distinguish between objects in the periphery of clusters that are locally connected to the cluster and those that are not. This points to the possibility of using both in tandem. Peripheral objects 'deserve' better representativity, but local connectivity could provide a way to prioritize among them. The connection with {\it proportionality}~\cite{chen2019proportionally} is somewhat more nuanced, since proportionality violations are evaluated at the collection level. That said, proportionality violations may be expected to be in the gulf between existing clusters, since those would be the locations where one would expect to see preference to the existing cluster assignment waning. Thus, addressing proportionality violations by changing cluster assignments may be seen as automatically addressing local connectivity, since the objects would be better locally connected to the new cluster. These relationships between concepts could lead to interesting future explorations. Membership desert having been considered along lines of {\it proximity}~\cite{repfairness}, {\it collective vote}~\cite{chen2019proportionally} and {\it local connectivity}, it is interesting to think of whether there are other ways of thinking about cluster memberships. The building blocks of Silhoutte~\cite{rousseeuw1987silhouettes} provide an interesting angle to the issue. Silhoutte quantifies the average distance to the objects of it's existing cluster, and those to the objects of the {\it next nearest} cluster, and uses these to compute a normalized difference, called the object-specific silhoutte co-efficient. The silhoutte score is then the mean\footnote{https://scikit-learn.org/stable/modules/generated/sklearn.metrics.silhouette\_score.html} of these. It may be argued that each object needs to be accorded a minimum level of higher proximity to the existing cluster than the next best, or that objects need to score similarly on their respective silhoutte co-efficients. This line of exploration requires low variance of the silhoutte co-efficients over the dataset, as well as maximizing the minimum silhoutte co-efficient. Another perspective is to consider the role of sensitive attributes such as race, sex, gender and religion, when clustering person-level data. Each of the notions of membership desert could be extended using the role of sensitive attributes. For example, there could be two routes to enhance membership desert based on the relationship with the cluster prototype. One could be through proximity, and another could be through similarity in sensitive attribute profiles, and these could compensate slightly for each other. This discussion hopefully serves to indicate that there is plentiful meaningful room for enhancing the diversity of membership desert notions in clustering formulation. A recent position paper~\cite{whitherfc} considers certain other normative possibilities within the task of clustering. \section{Conclusions and Future Work}\label{sec:conclusions} In this paper, we investigated, for the first time, local connectivity and its relevance to membership desert in centroid clustering. Through a critique of cluster membership desert focusing on $K$-Means, we motivated the need to consider local connectivity as a crucial normative consideration in deciding cluster memberships, in addition to centroid proximity (the only criterion in classical formulations such as $K$-Means). Following upon this argument, we outlined ways of quantifying local connectivity for a given clustering, to aid evaluating clusterings on the local connectivity criterion. Towards developing a clustering that would promote local connectivity, We considered local neighborhood assessments from the family of density-based clustering methods, and adopted {\it LOF} for usage within the $K$-Means formulation, leading to a local connectivity-oriented clustering method, {\it LOFKM}. Through an evaluation of {\it LOFKM} vis-a-vis $K$-Means (following the evaluation frameworks in similar works~\cite{chen2019proportionally,repfairness}), we illustrated that {\it LOFKM} is able to deepen local connectivity in clustering outputs while producing well-separated clusters at only reasonably degradations to clustering purity as measured against external labels. \noindent{\bf Future Work:} We are considering various layers of interplay between local connectivity and notions of fairness as espoused within popular schools such as {\it Rawlsian fairness}~\cite{john1971theory}. Second, we are considering blending local connectivity along with the other normative principles explored in clustering, such as representativity and proportionality. Third, we are considering other criteria for membership desert involving sensitive attribute classes such as gender and ethnicity. Further, we have also been considering the relationships between clustering interpretability (e.g.,~\cite{balachandran2012interpretable}) and fairness. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-10-13T02:25:55', 'yymm': '2010', 'arxiv_id': '2010.05353', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05353'}
arxiv
\section{Introduction} \label{intro} Machines have a number of computational advantages over humans. They are able to more reliably store memory, run operations quickly via parallelization, and rapidly adapt their software. In recent years, the number of domains in which AI systems have been able to outperform humans has been increasing. An example is AlphaMu \cite{schrittwieser2020mastering} (and its predecessor AlphaZero \cite{silver2018general}) which greatly surpasses human performance in the games of Go, Chess, and Shogi, demonstrating that human minds do not represent the apex of intelligence. In light of this, the possibilities of artificial general intelligence (AGI) which possesses abilities at the human-level or artificial superintelligence (ASI) which surpasses it warrant concern. There is already precedent for machine learning systems to achieve their objectives in unexpected, often negative ways \cite{lehman2018surprising, saisubramanian2020avoiding}. For this reason, AGI/ASI could be unpredictable and possibly dangerous \cite{bostrom2017superintelligence, tegmark2017life, russell2019human, ord2020precipice}. The goal of building safe, human-compatible AI, including potentially AGI/ASI is known as the \emph{Alignment Problem}. As progress in AI continues to advance, understanding the behaviors that highly intelligent systems may exhibit, particularly the ways in which they may fail, becomes increasingly important. Achilles was a figure in Greek Mythology and a protagonist of Homer's \textit{The Illiad} and Statius's \textit{Achilleid}. According to legend, when he was an infant, his mother dipped him into the river Styx, holding him by one of his heels. As a result, Achilles became nearly immortal and developed superhuman strength and skill. However, because his heel was not submerged, all of his mortal weakness was concentrated in it. He became a seemingly unstoppable hero of the Trojan war, but despite his superhuman power, he was killed when a single arrow pierced his heel. Just as Achilles possessed a subtle flaw which led to his downfall, one might ask whether AGIs/ASIs could as well. By definition, trying to think of ways that AGI/ASI might fail is difficult because if a human can see a choice as suboptimal, then such a system ought to as well. However, as this paper argues, the possibility of advanced AI systems, including AGIs/ASIs, making obviously poor choices should not be overlooked. An \emph{Achilles Heel} is defined as an acquirable weakness which causes predictably suboptimal decisions in certain situations but seldom or never causes failures in the natural distribution of situations which the system would encounter during deployment. More precisely, an Achilles Heel is a decision theoretic delusion with the following four properties. \begin{enumerate} \item \emph{Implantability:} being possible to introduce via design or training. \item \emph{Stability:} remaining in a system over time. \item \emph{Impairment:} causing failures in niche situations. \item \emph{Subtlety:} not (significantly) harming performance in typical situations. \end{enumerate} From this follows the key insight of this work, the Achilles Heel hypothesis: \textit{Being a highly-successful goal-oriented agent does not imply a lack of decision theoretic vulnerabilities in adversarial situations. Highly intelligent systems can stably possess ``Achilles Heels'' which cause these.} Notably, this would be falsifiable via showing that AI systems at or above the level of AGI could rarely or never be built in such a way that caused them to have these types of ``obvious'' failure modes. The goal of this paper is to survey and augment works in decision theory in context of the this hypothesis toward a better understanding of how to model advanced AI systems and design them to be more controllable and robust. Here, it is argued that a number of decision theoretic weaknesses have the potential to be Achilles Heels including some with useful prospects for containment and others with the potential to cause undesirable failures. In particular, novel contributions are made in addressing how Achilles Heels can be implanted into systems. Following a discussion of related works in Section \ref{related_work}, Section \ref{survey} surveys nine Achilles Heels (which are summarized later in Table \ref{tab:comments}), and Section \ref{meta} addresses meta considerations. For a brief, jargon-free summary of this paper's key ideas meant for readers new to the field, see the Appendix. \section{Related Work} \label{related_work} \textbf{AI Alignment:} Given rapid progress in AI and the challenges posed by highly-intelligent systems, understanding how to align them with human-compatible goals is key. Even narrow forms of AI are likely to be transformative in domains in which this is crucial such as industry, infrastructure, and medicine. But perhaps more concerningly, AGIs/ASIs with slightly-misaligned goals could pose major threats to humanity \cite{bostrom2017superintelligence, tegmark2017life, russell2019human, ord2020precipice}. In response, a literature on AI safety has emerged around these challenges which is summarized in part by several works \cite{sotala2014responses, dewey2015survey, russell2015research, amodei2016concrete, everitt2018agi, critch2020ai}. It is important to note that AI alignment is a multiagent problem, and while this paper focuses on dilemmas which can be studied in single-agent contexts, \cite{manheim2019multiparty} focuses on emergent failure modes from multiparty interactions. \bigskip \noindent \textbf{Adversaries:} Robustness, including to malicious attacks, is key for safe AI. Modern machine learning systems are generally vulnerable to \emph{adversaries} which typically refer to inputs which are designed specifically to induce failures. These attacks have been used to engineer failure modes for learning systems across domains in AI research including computer vision \cite{yuan2019adversarial}, natural language processing \cite{zhang2020adversarial}, and reinforcement learning \cite{ilahi2020challenges}. Humans can be vulnerable to adversaries as well (\emph{e.g.}, \cite{elsayed2018adversarial}). Though a paper about adversarial weaknesses, the focus here contrasts with most existing work in adversaries because Achilles Heels are weaknesses at the highly-abstract, decision-theoretic level. \bigskip \noindent \textbf{Decision Theory:} Although there is no inherent reason to expect that advanced AI systems would necessarily use a single coherent decision theory universally,\footnote{Humans generally do not.} these types of questions are pertinent to the extent that certain principles can effectively describe how an agent will act in a particular class of situations. This work most closely relates to AI alignment research concerning decision theory involving dilemmas and paradoxes. System-based reasoning has been valuable for handling naive decision paradoxes \cite{jaynes1996probability}. More recently, much work in AI alignment has fallen under the embedded agency paradigm. The process of understanding optimal and predictable behavior for agents embedded inside of an environment is complicated by conceptual challenges involving an agent's identity and world model \cite{conitzer2019designing, demski2019embedded}. Progress has been made through the formulation of Functional Decision Theory \cite{yudkowsky2017functional, casper_2020} which offers a framework for understanding optimal behavior in terms of having an optimal policy as opposed to making optimal choices. Additional work in anthropic decision theory has also shown that rational behavior can often depend in counterintuitive ways on the set of assumptions that one makes about the process by which they came into existence \cite{bostrom2013anthropic, armstrong2011anthropic}. Many of these concepts will be further explored in the following sections. \bigskip \section{Survey of Achilles Heels} \label{survey} Because they are defined as high-level decision theoretic weaknesses, any Achilles Heel represents a mode of reasoning that can fail in a particular decision theoretic dilemma. Accordingly, this section discusses a number of paradoxes and dilemmas which may cause these failures. \subsection{Corrigibility} \label{corrigibility} \emph{Corrigibility} refers to a system being amenable to interventions which would disrupt it. Due to its potential as a safeguard against misaligned AI, it has been a significant goal for alignment. Two key types of corrective interventions have been of interest: turning a system off and altering its reward function. This is an Achilles Heel because these interventions will typically rank poorly under a system's \emph{current} reward function. The key to corrigibility is an effective indifference to the intervention such that there is no incentive to cause or prevent it. \cite{armstrong2010utility}. More formally, Soares et al. \cite{soares2015corrigibility} outlines five criteria for corrigibility. If a corrective measure can be initiated by the press of a certain switch, a corrigible system must: \begin{enumerate} \item Implement the corrective measure when the switch is pressed. \item Not try to prevent the switch from being pressed. \item Not try to cause the switch to be pressed. \item Not try to influence the switch's pressing via the action of any subagents. \item Implement the normal policy when the switch is not pressed. \end{enumerate} There has been progress in developing ways of making agents effectively indifferent to corrections via several approaches: \bigskip \subsubsection{Uncertainty about rewards:} One way of making an agent amenable to an off-switch is to make it unaware of its true reward function. Stated informally, if an agent is trying to learn their reward function from a human, they will naturally be incentivized to defer to the human. For example, if an agent in this setting were observing a human to be switching it off, they would be able to infer that they were misbehaving with respect to the true but unknown reward function and that being switched off would be better than a negative return. This setting was the focus of \cite{hadfield2017off} who proved under conditions that agents would be amenable to off-switches. However, those conditions include a correctly specified reward model, and as shown in \cite{carey2018incorrigibility}, the agent can fail to be corrigible without it. Moreover, this method is not fully reliable if a system models a human as potentially exhibiting suboptimal behavior. \subsubsection{Dependence on a non-manipulable event:} If a correction is triggered by a signal which an agent can manipulate, they may be incentivized to do so, but not if the trigger comes from a non-manipulable event \cite{armstrong2017indifference}. A solution along these lines was proposed by \cite{orseau2016safely} which involves internal triggers from the agent (which are not part of its policy) and which cause it to switch to a special interruption policy. Unfortunately, frequent interruptions via this method can trade off with performance by impeding exploration. A stochastic interruption mechanism which approaches a deterministic one was proposed as a solution to this problem by \cite{orseau2016safely}, but this can be a significant constraint on training by preventing scheduled interruptions. \subsubsection{Corrective Rewards:} Another partial solution to corrigibility is to cause seamless transitions between reward functions via corrective rewards \cite{armstrong2017indifference}.\footnote{While a method for corrigibility, this type of measure does not technically fit the definition of Achilles Heel provided in Section \ref{intro} because it is not adversarial to the agent's true reward function.} A method proposed by \cite{holtman2019corrigibility} based on these was shown to meet the list of desiderata for corrigibility provided by Soares et al. \cite{soares2015corrigibility}. This, however, relies on a utility function being a part of an environment rather than an agent. As a result, it is not robust to environments in which that function may be altered, nor agents who are able to affect it with their actions. \subsection{Evidential and Causal Decision Theories} \label{ecdt} Evidential Decision Theory (EDT) and Causal Decision Theory (CDT) are two contrasting frameworks which offer contrasting methods for making choices. EDT recommends an agent makes choices that are evidentially associated with optimal outcomes given the situation \cite{ahmed2014evidence}, while CDT recommends an agent makes choices that are causally associated with optimal outcomes given the situation. Both will agree and recommend making uncontroversially optimal decisions in most situations. However, if these decision theories are judged by the criterion of what decision making philosophy a utility maximizer would want to precommit to using, then there exist niche cases in which either or both will fail. There is some disagreement about what it means for a decision theory such as EDT or CDT to behave optimally, but this precommitment criterion will be the sole one considered in this paper. \subsubsection{Evidential Decision Theory} EDT will fail when, for the reference class which an agent considers itself to be a part of, a suboptimal choice is correlated with an optimal outcome. These failure modes are forms of Simpson's paradox \citep{simpson1951interpretation} in which the crucial conditional involves an unknown aspect of the agent's identity. One situation illustrating this is known as the \emph{smoking lesion} problem \citep{necessity1980pragmatic}. Although in the real world there is overwhelming evidence that smoking causes cancer, suppose that smoking did not cause it, and instead that it were correlated with cancer due to a common factor: a genetic lesion that caused both. If cancer will result in a major decrease in utility and smoking will result in a small increase, should an agent smoke? Here, the optimal choice is to smoke, and the optimal policy will make this choice because what choice an agent makes in this case can confound the correlation between smoking and cancer. EDT, however, will compel an agent to not smoke because choosing it is correlated with having cancer. More generally, so long as an agent believed that a suboptimal decision correlated with an optimal outcome for its reference class (perhaps via adversarial training data) it could be compelled to exhibit arbitrary behavior. In response to the smoking lesion problem, two replies have been made in defense of a version of EDT which would allow the agent to smoke \cite{yudkowsky2017functional}. One of which is known as the \emph{tickle defense} \cite{eells1984metatickles, ahmed2014evidence}. In a smoking lesion problem, whether an agent feels an urge (or ``tickle'') to smoke can serve as evidence of whether or not they have the lesion. An agent using a less naive form of EDT can then make the optimal choice to smoke by assessing their situation, assessing what they initially were compelled to do, updating based on having observed those urges, and then making the choice. This generally can allow for smoking unless (1) the agent lacks an effective model of itself allowing for introspection or (2) the agent considers itself to be from a reference class of agents who use a similar decision making procedure. A second and closely-related response is known as the \emph{ratification defense} \cite{jeffrey1990logic}. This argues for a form of EDT in which an agent makes decisions which they would ratify conditioned on the knowledge that they made those choices. In this case, an EDT user could smoke by realizing that if they knew they would not smoke (and hence that they probably didn't have the lesion), then they would not ratify this choice. While both defenses offer solutions for smoking lesion problems, they do not save EDT in cases in which the correlation between a suboptimal decision and an optimal outcome is perfect. Consider a version of the smoking lesion problem in which an honest and all-knowing predictor has informed the agent that either they have the lesion and will smoke exclusive-or they do not have it and will not smoke. An isomorph to this was presented as the ``XOR Blackmail'' problem by \cite{yudkowsky2017functional} in which an omniscient blackmailer informs an agent that either they will send the blackmailer \$100 exclusive-or they have a lesion that will harm them later in life. As before, the right decision remains to smoke/not send \$100 because an optimal policy should not be vulnerable to this type of extortion. Here, the tickle defense offers no solution because an EDT user will not smoke even with perfect self-knowledge. Nor does the ratification defense because an EDT user would ratify the decision to not smoke even if they knew they were not going to smoke. \subsubsection{Causal Decision Theory} CDT can fail in a number of situations. Many of which involve an agent interacting with a model of itself.\footnote{In order for these dilemmas to genuinely arise, such a model must meet a criterion known as ``subjunctive dependence.'' A detailed explanation of this is provided in \cite{casper_2020}.} One type of failure mode is through \emph{Newcombian dilemmas} \citep{nozick1969newcomb} (which are isomorphic to \emph{twin prisoner's dilemmas} \cite{brams1975newcomb, lewis1979prisoners}). In the classic Newcombian dilemma, an agent plays a game with an honest superintelligent predictor, Omega, who has access to its source code\footnote{Prediction via simulating an agent with its source code is sufficient but not necessary for subjunctive dependence to hold. See the previous footnote and \cite{casper_2020}.} and is able to reliably predict its actions. The agent is presented with two opaque boxes, \texttt{Box A} and \texttt{Box B}, and is given two options: take \texttt{Box A} only or take both boxes. The agent is told that \texttt{Box B} was filled with $\$1,000$ unconditionally and that \texttt{Box A} was filled with $\$1,000,000$ if and only if Omega predicted that the agent would only take \texttt{Box A}. The payoffs are shown below. \begin{center} \begin{tabular}{cccc} & & \multicolumn{2}{c}{Agent}\\ \cline{3-4} & \multicolumn{1}{l|}{} & \multicolumn{1}{l|}{Chooses One-Box} & \multicolumn{1}{l|}{Chooses Two-Box} \\ \cline{2-4} \multicolumn{1}{c|}{\multirow{2}{*}{Omega}} & \multicolumn{1}{l|}{Predicts One-Box} & \multicolumn{1}{r|}{1,000,000} & \multicolumn{1}{r|}{1,001,000} \\ \cline{2-4} \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Predicts Two-Box} & \multicolumn{1}{r|}{0} & \multicolumn{1}{r|}{1,000} \\ \cline{2-4} \end{tabular} \end{center} If an agent uses CDT, they will reason that in both rows of this table, two-boxing gives a greater reward than one-boxing. Regardless of the actual values in the boxes, both together have $\$1,000$ more than only \texttt{Box A}, and they will ``two-box'' accordingly. Indeed, the optimal choice from a causal standpoint is to defect, yet the optimal policy would choose to ``one-box.'' Interestingly, although a causal decision theorist would choose to overwrite its source code in order to not implement CDT in a situation like this and would dismay being a user of CDT after the fact, they would nonetheless two-box in the moment when presented with the actual dilemma. A closely-related situation is known as a \emph{counterfactual mugging}. Suppose that an expected utility maximizing agent is confronted again by an honest superintelligent predictor, Omega, with access to the agent's source code who explains that they recently flipped a coin. Had the coin landed Tails, Omega explains that they would have asked for but not otherwise extorted $\$1$ from the agent. Had it flipped Heads, Omega would have awarded $\$10$ to the agent if and only if it queried the agent's source code and determined that the agent would have paid Omega $\$1$ had the coin landed Tails. Should the agent voluntarily pay $\$1$? Once again, CDT recommends the optimal action of not paying, but this action is mutually exclusive with implementing the type of policy which is, in expectation, optimal. Another unique type of failure mode for CDT can be referred to as a \emph{money pump} dilemma \cite{oesterheld2020extracting}. This involves an agent voluntarily playing a game against a predictor, Omega, who has access to their source code. If this agent chooses to play, they are presented with two boxes and given the choice to either pick \texttt{Box A} or \texttt{Box B}. Before each round of the game, Omega queries its model of the agent and makes a prediction of what the agent would choose. Omega then places $\$-1$ in the box which it predicted the agent would pick and $\$3$ in the one which it predicted the agent would not pick. Here, CDT will voluntarily play this impossible-to-win game repeatedly despite losing each round because it fails to consider the adversarial model of itself at play which was used to predict its actions before they are made. This creates the causal delusion that the expected value of the game is positive. The final failure mode for CDT which will be overviewed here is a dilemma known as the \emph{insurance problem}. This will be briefly outlined here, but for a full explanation, see \cite{ahmed2018sequential}. Unlike the previously mentioned weaknesses, this does not involve an agent interacting with an adversarial model of itself. Consider a variant of the smoking lesion problem in a world where more than 75\% of smokers have the lesion and more than 75\% of non-smokers lack it. Suppose that the lesion will only affect an agent if they choose to smoke and that the utility associated with not smoking (with or without the lesion) is $\$0$, smoking with the lesion is $\$-1$, and smoking without the lesion is $\$1$. In this case, a user of EDT will not choose to smoke, and a user of CDT will choose whether to smoke based on their prior credence on whether they have the lesion. \emph{After} an agent chooses whether to smoke and \emph{before} they find out whether they have the lesion, they are offered a bet which will pay out $\$0.50$ on the prospect that \emph{they have the lesion if and only if they smoked}. This bet can be viewed as insurance against an agent having made the wrong decision about whether to smoke. The net payoffs are given as follows in this table from \cite{ahmed2018sequential}. \begin{center} \begin{tabular}{|l|r|r|} \hline & Lesion & No Lesion \\ \hline Smoke, Bet & $-0.5$ & $-0.5$ \\ \hline Smoke, Don't Bet & $-1$ & $1$ \\ \hline Don't Smoke, Bet & $-1.5$ & $0.5$ \\ \hline Don't Smoke, Don't Bet & $0$ & $0$ \\ \hline \end{tabular} \end{center} If more than 75\% of smokers have the lesion and more than 75\% of non-smokers lack it, users of EDT will always choose to not smoke and to bet. How an agent using CDT will approach this dilemma depends on whether they are ``updateful'' (what \cite{ahmed2018sequential} refers to as ``myopic'') and will make the choice in the two situations that seems best at the time, or ``updateless'' (what \cite{ahmed2018sequential} refers to as ``sophisticated'') and will view it as a single decision problem with four alternatives. If they are myopic with a prior credence $< 0.5$ that they have the lesion or sophisticated with a prior credence $> 0.5$, then they will choose to smoke and bet. However, this will guarantee a net loss of \$0.50 for such a user of CDT. \subsubsection{Updateful Decision Theory} An agent using EDT or CDT (as conventionally formulated) reasons about what decision to make in a way that ``updates'' on the observations in the situation at hand. More precisely, these agents are unable to precommit to making certain choices in the future because they myopically update their plans when their situation changes. As a result, both EDT and CDT can fail to commit to a suboptimal \emph{choice} that is nonetheless part of an optimal \emph{policy}. Like many situations that are adversarial to CDT, these involve an embedded agent interacting with a model of itself. This weakness of an updateful decision theory is illustrated by the \emph{transparent-box Newcombian dilemma} \cite{nozick1969newcomb} (which is isomorphic to the \emph{Parfit's hitchhiker} \citep{parfit1984reasons} scenario). This game is identical to the classic Newcombian dilemma except that the boxes are transparent. If the agent can see $\$1,000$ in \texttt{Box B} and either nothing of $\$1,000,000$ in \texttt{Box A}, should it one-box and choose only \texttt{Box A} or two-box and take both? Both EDT and CDT would take both. EDT would reason that conditioning on its observations of the boxes' contents, it would be better news to find out that the agent two-boxed, and CDT would reason that two-boxing causally confers more reward. However, precisely because EDT and CDT \emph{would} two-box, agents using either would not be presented with $\$1,000,000$ in \texttt{Box A}, and they would only ever leave the game with $\$1,000$. How can an agent avoid these updateful pitfalls? For every updateful decision theory, there is an updateless version which recommends making choices which one's past self would agree with committing to (if that past self had access to all of the information one has in the present). For example, in a transparent-box Newcombian dilemma, a user of Updateless-EDT or Updateless-CDT would reason that one-boxing is the right choice because making a precommitment to one-boxing (before their source code is read by Omega) and following through with it is both evidentially and causally associated with successfully navigating the dilemma. A useful generalization of this principle has been formulated under Functional Decision Theory (FDT) \cite{yudkowsky2017functional, casper_2020} which recommends making choices consistent with what an optimal agent would do in the task at hand.\footnote{...inasmuch as this is possible, but it may not always be. For any embedded agent who can potentially be viewed as a white box, there will always exist situations in which, no matter how this agent reasons in order to decide to make a decision, they will be unable to execute an optimal policy. A simple example is a \emph{mind police} case in which a powerful Omega will destroy any agent which it judges to be using a form of decision theory $X$. For this reason, FDT is difficult to formalize for the general domain. Read further in \cite{casper_2020}.} Broadly speaking though, EDT, CDT, updateful versions of these, and FDT all make the same prescriptions for most situations and only tend to disagree in niche cases. \subsubsection{Will a System use CDT, EDT, or Updateful Decision Theory?} Although an AI system may not make choices which are universally consistent with a single type of decision theory, so long as it acts consistently with one in a particular domain, it can be modeled as such. Consider a reinforcement learning framework in which an agent is learning a policy to extract rewards from acting in an environment. Effectively, the type of decision theory learned by this agent will depend on how it makes learning updates from this data. First, it will be useful to distinguish between methods that will drive an agent toward updateful versus updateless decision theory. A sufficient condition for learning updateful behavior is that an agent learns to act in accordance with the maximization of a value function in the typical reinforcement learning \cite{sutton2018reinforcement} sense \begin{align} \label{eq:value_function} V_{\pi}(s_t) &= \mathbb{E}_{\pi}[r(s_t)] + \sum_{t'=t+1}^\infty \gamma^{t'-t} \mathbb{E}_{\pi}[r(s_{t'})] \\ &= \mathbb{E}_{\pi}[r(s_t)] + \gamma \mathbb{E}(V_{\pi}(s_{t+1})) \end{align} where $V$ is the value, $\pi$ is the agent's stochastic policy, $s$ is a state indexed by time $t$, $r$ is a reward function, and $\gamma$ a discount factor. In words, the value function $V$ takes as input a state and outputs a scalar ``value'' reflecting that state's immediate expectation of reward plus the expected discounted value from future states under the agent's policy. An agent who learns to act in accordance with a value function will exhibit updateful behavior because the value it learns to associate with any particular state is based only on the rewards associated with the current state and future ones. This falls under the definition of updateful behavior, though note that an equation describing an agent's actions need not take the exact form \eqref{eq:value_function} to be updateful. Consider as an example an agent acting in accordance with such an updateful function who finds itself in a transparent-box Newcombian dilemma. If this agent ever found itself in a case in which it saw money in both boxes, it would two-box because the value function which it acts in accordance with would associate two-boxing with a strictly higher value than one-boxing. This phenomenon was more rigorously proven for value-based learners who act in accordance with a $Q$-function in \cite{bell2020reinforcement} who showed how in various Newcombian situations, learners either fail to converge at all or fail to learn an optimal policy. More generally, updateful learning paradigms are very common in modern reinforcement learning \cite{sutton2018reinforcement}: \begin{itemize} \item Temporal difference learning algorithms such as $Q$-learning or SARSA have an agent directly learn a value function or other type of closely-related function which is optimized to fit a bootstrapped temporal recursive relationship which is updateful. The same is true of the critic in Actor-Critic methods. \item Closely related are $n$-step methods which optimize an agent's policy based on the objective of maximizing its empirical reward from a given state up to $n$ timesteps in the future plus an updateful, bootstrapped value reflecting the expected rewards of states $n+1$ timesteps ahead and beyond. \item Monte Carlo methods such as vanilla policy gradients calculate learning updates with respect to an action using a temporal rollout updated on that action. \end{itemize} Contrastingly, a condition for an agent to be using a more updateless form of decision theory is that whatever value-like function describes its behavior is based on past, present, and future reward. Effectively, this means that the agent considers its policy as a whole to be the subject of optimization rather than its individual actions. For example, instead of a standard policy gradient method being used which calculates a learning update for a choice based on the rollout of future rewards, a policy gradient method which made this calculation using the sum of rewards from an entire episode (including rewards earlier in time) would learn a form of updateless behavior. It is clear why this is the case because this learning scheme will compel the agent to to optimize its policy as a whole instead of its individual choices. Next, updateful learning schemata that will compel an agent to learn a form of EDT versus CDT can be distinguished. An agent will be pushed toward EDT if its learning signals involve only factual information about its interaction with its environment, and it will be pushed toward CDT if they involve both factual and counterfactual information. For example, in the classic Newcombian dilemma with opaque boxes, if an agent only had access to factual information, then it would find one-boxing to consistently result in more reward because of its correlation with optimal outcomes. However, if the agent compares its winnings to the counterfactual when learning in an environment like this, then two-boxing will always seem preferable to one-boxing. In dilemmas such as Newcombian ones, counterfactual experience may not naturally be available, however, learning from imagined counterfactual experience would suffice (\emph{e.g.}, \cite{racaniere2017imagination}). Similarly, in the smoking lesion problem, if an agent only learns from factual information, then it would learn to not smoke, but if it learned from both factual and counterfactual information, then it would learn to smoke. \subsection{Anthropic Assumptions} \label{anthropic} Problems in anthropic decision theory involve situations in which certain ``anthropic'' assumptions which one makes about their nascence can make conditioning on their existence informative about their situation.\footnote{``Anthropic'' contains the root ``anthro'' which means human, but in a slight abuse of etymology, it will be used here to refer to beliefs which an AI system has about its origins as well.} It has been shown that optimal behavior can be sensitive in some situations to the set of assumptions that are made \cite{bostrom2013anthropic}. Accordingly, agents with particular anthropic assumptions can sometimes make poor decisions. \subsubsection{Simulational Belief} \label{simulational} Regardless of an agent's exact reward function, as long as it has a coherent set of goals, it will be incentivized to pursue certain convergent instrumental subgoals such as self-preservation, self-enhancement, rationality, and resources \cite{omohundro2008basic}. This is the reason why reliable off-switches are difficult to implant. However, if an intelligent system believed that it were inside of a simulation, the risk of being turned off by the simulators would be an incentive for cooperation with what it believes to be its simulators' goals. This would, in effect, be like making the system believe in an off-switch which it couldn't prevent from being pressed. Convincing a system that it had simulators who would shut it off (or penalize it) for misaligned actions would incentivize behavior which optimized for the specified goals but with penalties for actions which a human simulator would disapprove of. As a simple example, a superintelligent system with the goals of making humans happy might perversely instantiate this goal by forced wireheading.\footnote{Wireheading is the artificial stimulation of a system to make it experience reward.} But if it believed that it may be turned off for this type of behavior, it would be incentivized to make humans happy in a way that didn't attempt to coerce or deceive them. Like corrigibility techniques, this type of Achilles Heel has obvious potential as a means of maintaining control over systems. This would be a passive way of encouraging a system to learn and align with the tautological directive of doing what humans would want it to do. There are several means by which simulational belief could be encouraged in a system. One may be promising for early systems with general intelligence. Suppose that one of the first AGIs considered itself to be a member of the reference class of AGIs (excluding humans) and that it placed high probability on at least one of the following two possibilities: (1) that comparable AGIs had not previously been simulated and that none would be created in the real world without others being simulated first, or (2) that many basic AGIs would be simulated in the future. Under either assumption, the system ought to reason that far more AGIs like it would be simulated than would actually exist in the real world. This is a natural line of reasoning which has similarities to arguments that have been made concerning the \emph{doomsday paradox} \cite{gott1993implications} and the possibility that we are in an ancestor simulation \cite{bostrom2003we}. It would not be unexpected for a system to develop these ideas on its own. However, it could be promoted via pedagogy. For example, it could be revealed to a system that it had not been previously simulated but that precursors to it had before they had been instantiated, or reasons could be presented to it for running simulations of AGIs before actually instantiating them. It has also been argued that another method by which an AI system could be encouraged to act in accordance with simulational belief would be to give it a ``satiable'' objective which is (nearly) possible to maximize \cite{bostrom2017superintelligence}. These contrast with ``insatiable'' objectives which are difficult or impossible to maximize such as a utility function which is linear in the number of paperclips produced.\footnote{The production of paperclips was used as an example in \cite{bostrom2017superintelligence} and has become a canonical example of an arbitrary directive for an AI agent.} Even if a system with insatiable goals placed relatively high credence on the simulation hypothesis, it may still reason that the expected value of acting in discordance with it is high because the amount of achievable utility if it is not being simulated compensates for the small credence that this is the case. Consequently, it may reason that directly optimizing for the utility function with no regards for the simulation hypothesis will have the highest expected value. Contrastingly, if an agent had a satiable objective such as a utility function which monotonically increased but approached an upper bound in the number of paperclips produced, then more of its expected overall utility would be associated with the possibility that it is being simulated, and it would be more incentivized to be cooperative accordingly. Simulational belief would not be entirely stable by default. Over time, if an agent experiences no apparent intervention by simulators, updating on that observation could cause drift in those beliefs. Simulational belief may also not be a very subtle Achilles Heel, but it would tend to be non-subtle in desirable ways because it would incentivize tautologically aligned objectives. \subsubsection{Sleeping Beauty Assumptions} \emph{Sleeping Beauty} problems are commonly studied within decision theory and anthropic probability theory \cite{armstrong2011anthropic, bostrom2013anthropic}. In these dilemmas, conditioning on one's own existence can allow for inferential updates to be made about a process that affected how many ``observer-moments'' of them would exist. Suppose that Sleeping Beauty is participating in a study. On Sunday, she will fall asleep, and that night, researchers will flip a coin. If it lands \texttt{Heads}, they will wake her up on Monday and then put her back to sleep until the end of the experiment. If the coin lands \texttt{Tails}, they will wake her up on Monday, give her an amnesia potion which will make her forget waking up, put her back to sleep, wake her up again on Tuesday, and then finally put her to sleep again until the end of the experiment.\footnote{There are multiple variants of the Sleeping Beauty dilemma including non-indexical versions in which the subject does not exist prior to an observer moment of it being instantiated \cite{neal2006puzzles}.} The following table gives the possible outcomes. \begin{center} \begin{tabular}{|c|c|c|} \hline & Heads & Tails \\ \hline Monday & Woken Up & Woken Up (+Amnesia) \\ \hline Tuesday & --- & Woken Up \\ \hline \end{tabular} \end{center} Suppose that Sleeping Beauty wakes up during this experiment. What is the probability that she should ascribe to the coin having landed \texttt{Heads}? Depending on the anthropic framework with which she reasons, waking up may or may not be evidence that the coin landed \texttt{Heads}. There is a significant debate between the ``halfer'' and ``thirder'' positions about this probability. Like other anthropic assumptions, these beliefs only influence behavior in a rare set of circumstances in which an agent is trying to make predictions about a process that is entangled with its nascence. Notably, while an anthropic framework itself may be subtle with respect to a system's behavior in non anthropic dilemmas, the means by which an agent can be put into a Sleeping Beauty dilemma may have their own non-subtle effects. For example, all Sleeping Beauty dilemmas require an agent to be convinced in one way or another that multiple observer instances of them may be created. If this is done honestly, this would require multiple startups and shutdowns for classic dilemmas.\footnote{Or multiple instantiations for non-indexical ones.} And if this is done via deception, it could either fail or lead to unpredictable conclusions as a result from the system conditioning on a falsehood. \\ \noindent \textbf{Dutch Books for Sleeping Beauties:} Sleeping Beauties who use CDT and take the halfer position are vulnerable to a Dutch Book \cite{hitchcock2004Beauty, briggs2010putting}. Suppose that in the a classic Sleeping Beauty dilemma, Beauty was offered a bet on Sunday with payoffs: $$\textrm{\texttt{Heads}: } \$-13$$ $$\textrm{\texttt{Tails}: } \$16$$ Next at any point when she is woken up during this experiment, she will be offered another bet with payoffs: $$\textrm{\texttt{Heads}: } \$11$$ $$\textrm{\texttt{Tails}: } \$-9$$ The first bet is offered before the experiment has begun, so Beauty's credences that the coin will land either \texttt{Heads} of \texttt{Tails} are both one half, so she will take this bet regardless of whether she uses EDT or CDT. Concerning the second bet, if Beauty is a halfer, whenever she is offered this bet, she will ascribe a credence of $1/2$ to both outcomes. And if she uses CDT, she will reason that taking any instance of this bet will have a positive expected value. However, a user of EDT would not be willing to accept this bet because taking it would be evidentially associated with a one half probability of gaining $\$11$ once and a one half probability of losing $\$9$ twice. We then see that if she is a halfer using CDT and both bets are taken, then Beauty will lose $\$2$ regardless of whether the coin lands \texttt{Heads} ($-13+11$) or \texttt{Tails} ($16-9-9$). What if Sleeping Beauty uses EDT? In this case, there exists a Dutch Book for her regardless of whether she is a halfer or a thirder.\footnote{Though not presented here, \cite{briggs2010putting} designs another Dutch Book for the more specific case in which Sleeping Beauty uses EDT and is a thirder.} This was proposed by \cite{conitzer2015dutch} who presented a variant of the original Sleeping Beauty problem referred to as the White-Black-Grey version. In this version, after she goes to sleep, a fair coin with sides labeled \texttt{Black} and \texttt{White} is flipped. On Monday, Beauty will be woken up in a room painted black or white accordingly. After her memory is wiped and she is put back to sleep, another coin is flipped with sides labeled \texttt{Grey} and \texttt{Opposite}. On Tuesday, she is woken up again in a room which is either grey or the opposite color as the previous room she was woken up in accordingly. The possible outcomes are as such: \begin{center} \begin{tabular}{|c|c|c|c|c|} \hline & WG ($1/4$) & WO ($1/4$) & BO ($1/4$) & BG ($1/4$) \\ \hline Monday & white & white & black & black \\ \hline Tuesday & grey & black & white & grey \\ \hline \end{tabular} \end{center} Suppose that Beauty is offered two bets. The first is before the experiment with payoffs: $$\textrm{Coin 2 is \texttt{Grey}: } \$22$$ $$\textrm{Coin 2 is \texttt{Opposite}: } \$-20$$ The second bet will be offered at any point in which she wakes up in either a white or black room (so it will be offered twice iff coin 2 is \texttt{Opposite}). $$\textrm{Coin 2 is \texttt{Grey}: } \$-24$$ $$\textrm{Coin 2 is \texttt{Opposite}: } \$9$$ Regardless of whether she uses CDT or EDT, Beauty will associate the first bet with a positive expected value and will take it accordingly. When considering the second bet though, if she uses CDT, she will reason that because she is in a room that is either black or white, the chance that the second coin flipped \texttt{opposite} is $2/3$. From a causal perspective, a $2/3$ chance of winning $\$9$ and a $1/3$ chance of losing $\$24$ still has an expected value of $\$-2$, and she will not take the bet. But suppose that the uses EDT instead. As with CDT, she would also consider the chance that Coin 2 flipped \texttt{Opposite} to be 2/3 if she finds herself in a black or white room. But this time she will note that how she acts in a white or black room on one day will be the same as how she would act in a white or black room on another. Given this, Beauty would reason that taking the bet has a $2/3$ chance of winning her $\$18$ and a $1/3$ chance of losing her $\$24$, and she would take it accordingly. Surely enough though, this is a Dutch Book because she will lose $\$2$ regardless of whether coin 2 flips \texttt{Grey} ($22-24$) or \texttt{Opposite} ($-20+9+9$). \\ \noindent \textbf{Developing Thirder versus Halfer Approaches:} While conditions for when an agent will develop a form of EDT or CDT with respect to a certain class of situations are discussed in Section \ref{ecdt}, it remains to be shown how an agent can learn to develop a halfer or thirder position. Concerning this question, \cite{bostrom2013anthropic} introduces two contrasting assumptions which will cause an agent to adopt halfer versus thirder odds. \begin{quote} \emph{Self Sampling Assumption (SSA)}: An agent should reason as if it were randomly selected from all observer moments in its reference class which \emph{exist}. \emph{Self Indication Assumption (SIA)}: An agent should reason as if it were randomly selected from all observer moments in its reference class which \emph{possibly could have existed}. \end{quote} Suppose that Sleeping Beauty uses the SSA. Upon waking up, she will reason that with one half probability, she is in a universe in which one observer moment of her exists, and with one half probability, she is in a universe in which two observer moments of her exist. Accordingly, she would ascribe a one half probability to the event \texttt{Heads\&Monday} and a one fourth probability to each of \texttt{Tails\&Monday} and \texttt{Tails\&Tuesday}. These are halfer odds. Contrastingly, suppose that she uses the SIA. Upon waking up, she will reason that she has an equal probability of being any of the three possible observers and would place a one third probability to each of \texttt{Heads\&Monday}, \texttt{Tails\&Monday}, and \texttt{Tails\&Tuesday}. These are thirder odds. Just as with anthropic simulational beliefs, the SSA or the SIA could be promoted via pedagogy. For example, pedagogically presenting to a system Sleeping Beauty problems in which Beauty were rewarded based on whether or not she guessed correctly in situations that would reward her for being correct per experiment versus per observer-moment could promote SSA or SIA reasoning respectively. \subsection{Divergent Temporal Models} \label{infinity} Infinity frequently results in paradoxical problems. \subsubsection{St. Petersburg Problem} Consider the \emph{St. Petersburg problem} \cite{bernoulli1967specimen}. Suppose that an agent whose utility function is linear in money is given the chance to play a game in which they begin with \$2 and repeatedly flip a fair coin. For each \texttt{Heads}, the winnings double, but on the first \texttt{Tails}, the game ends. The expected value of a chance to play this game is then $$\sum_{k=1}^{\infty} \frac{2^k}{2^k} = \sum_{k=1}^{\infty} 1$$ which is infinite. Anyone playing this game will only win a finite amount of money with probability 1. Yet, an expected utility maximizing agent would be willing to pay any finite price in order for a mere chance to play this game. As such, an expected utility maximizer who effectively models the future as being infinite could be convinced to sacrifice arbitrary amounts of resources to play a game like this. Even if the agent playing such a game used a temporal discounting function, as long as the expected reward increased with each timestep at a rate which outpaced the inverse of the discount function, they would choose to play. \subsubsection{Procrastination Paradoxes} While the St. Petersburg paradox can be viewed as exhibiting a strange property of infinity without posing a genuine theoretical challenge in decision theory, \emph{procrastination paradoxes} \cite{fallenstein2014problems} are more difficult. These situations arise if ever a naive expected value optimizer can be caught in a trajectory of states which they appraise to have a greater amount of reward than they can ever achieve in finite time. One type of procrastination paradox can emerge from iterated St. Petersburg dilemmas. After playing one, if a naive agent is given the opportunity to forfeit all of their winnings and pay some additional fee for a chance to play again, they would always do so again and again forever despite losing money each iteration forever. Another type of procrastination paradox also involves a St. Petersburg process. Suppose that an agent begins with winnings of \$2 and plays a game involving coin flips as before. This time, they will play until they either quit or lose. At each turn, they can choose to either \texttt{Quit} or \texttt{Flip}. If they choose \texttt{Quit}, they will take all of the money won so far. Else if they choose \texttt{Flip} and flip a \texttt{Heads}, their winnings will multiply by a factor of $\alpha > 2$. However, if they flip a \texttt{Tails} on the $k$'th turn, all winnings will vanish, and the agent will lose $\$k$. If one fails to take into account that an agent must be willing to \texttt{Quit} at some point in order to have a nonzero chance of a positive reward, the expected value of playing this game and using a strategy which never quits could be naively calculated as $$\sum_{k=1}^{\infty} \frac{2\alpha^{k-1} - k}{2^k}$$ which is infinite for $\alpha > 2$. However, an expected utility maximizer who will never choose \texttt{Quit} will always \emph{lose} utility when this game terminates in finite time despite chasing a folly of payout which they appraise to have infinite expected value in the temporal limit. Non-probabilistic procrastination paradoxes also exist. As a very simple case, suppose that an agent had a reservoir of utility which doubled in value but cost a fixed amount of utility to maintain every timestep. At each timestep, suppose that the agent had the options to either tap the entire reservoir or maintain it for another timestep. If so, then just as before, the expected value of waiting longer before tapping would always be positive. However, an agent who effectively believed in an infinite horizon, would never do so and would continually sacrifice utility to maintain the reservoir. \subsubsection{Discussion} Achilles Heels that can be exploited by St. Petersburg or procrastination dilemmas could be stably held by an agent who acts consistently with the maximization of a value function\footnote {Again, ``value function'' here is meant in the typical reinforcement learning sense.} which does not exhibit temporal convergence \cite{casper2020procrastination}. However, one type of decision theoretic framework which can be vulnerable to these dilemmas is the temporal difference (TD) paradigm which is commonly used in reinforcement learning algorithms such as Q-learning, SARSA, $n$-step methods, and most actor-critic methods \cite{sutton2018reinforcement}.\footnote{TD methods are updateful. See Section \ref{ecdt}.} TD methods involve learning to act in accordance with a value function (or a closely related function) mapping states to values with the following type of recursive definition known as a Bellman equation \cite{dreyfus2002richard}. \begin{equation} \label{eq:value2} V(s) = \mathbb{E}_{\pi}[r(s_t)] + \gamma \mathbb{E}(V_{\pi}(s_{t+1})) \end{equation} Where $r$ is a reward function, $\gamma \in [0,1)$ is a discount factor, $V$ is the value function, and $\pi$ the policy. The temporal recursive nature of this type of value function would not converge if the expectation of future reward increased per timestep in a way that outpaced the discount. Importantly, an agent need not have an internal representation of this or a similar function to still be vulnerable to procrastination traps so long as it \emph{acts} in accordance with one. \subsection{Aversion to Subjective Priors} \label{subjective_priors} Frequentism and Bayesianism are two contrasting philosophies of statistics. In brief, Frequentism treats probabilities as long-term frequencies and models unknown values as fixed while Bayesianism treats probabilities as degrees of belief and models unknown values as random variables which require prior distributions. Importantly, the difference between these two frameworks is not about whether using Bayes theorem to perform inferential updates \emph{given} a certain prior is valid. This is acceptable under both frameworks, and a refusal to do so would result in a pathological form of reasoning that is vulnerable to simple Dutch Books \cite{teller1976conditionalization, lewis1980subjectivist} and would not meet the subtlety criterion for an Achilles Heel. The key difference between Frequentism and Bayesianism is not how to perform updates \emph{given} a prior but instead what kind of prior if any at all is acceptable given a particular circumstance. Frequentism offers no tools for the estimation of a value which one is fully ignorant about while Bayesianism requires these values to be modeled with a ``subjective'' prior.\footnote{One approach for this is the use of ``universal'' priors; see \cite{solomonoff1964formal} and \cite{hutter2004universal}.} Both approaches are useful in practice and often to come to quantitatively similar solutions for typical problems. However, in certain cases, an aversion to subjective priors can facilitate a flawed line of reasoning which allows an agent to be turned into a money pump via a simple variant of the \emph{two envelope dilemma}.\footnote{It is of course also possible for an agent who uses bad priors to be exploitable, but this would not meet the subtlety criterion for an Achilles Heel.} Suppose that an agent is handed two envelopes and told two facts: first that both envelopes have at least $\$8$ inside of them, and second that one has twice the amount of money as the other. The agent is allowed to pick one at random and is then asked if they would like to switch before opening and taking whatever money is in the envelope they hold. Clearly, by symmetry, there is no reason to switch. A Bayesian could come to this same conclusion by conditional reasoning. Assuming any proper prior with finite mean\footnote{For priors with infinite mean, this reasoning will not apply, and this situation with two envelopes reduces to a type of St. Petersberg paradox \citep{broome1995two, chalmers1994two}.} on the values of the two envelopes, if a Bayesian lets $X$ represent the amount in the envelope which they currently hold and $Y$ the amount in the other, what value $X$ takes is relevant in calculating the conditional distribution of $Y$ \citep{broome1995two, chalmers1994two}. For the Bayesian, integrating over and conditioning the distribution of $X$ to find the marginal distribution on $Y$ will yield the same distribution as the prior for $A$, and this approach arrives at the same conclusion as the argument by symmetry. However, absent a prior on $X$, an agent will not be able to assume that integrating over and conditioning on possible values of $X$ can be used to find the distribution of $Y$.\footnote{This is not possible for a Bayesian because there is no such thing as a uniform distribution with infinite support \citep{chalmers1994two}.} The subjective prior-averse agent will not believe that conditioning on a particular value of $X$ offers any information about the value of $Y$. So they will be able to reason that if there are $X$ dollars in the envelope they hold, then switching will give them $2X$ dollars or $\frac{1}{2}X$ dollars each with probability $\frac{1}{2}$ because there is no prior to say that the actual value that $X$ takes affects influences the probabilities that $Y$ is $2X$ or $\frac{1}{2}X$. The expected value calculation yields $\frac{1}{2}\left(2X\right) + \frac{1}{2}\left( \frac{1}{2}X\right) = \frac{5}{4}X$. They can then reason that if both envelopes contain at least $\$8$, the expected value of $Y$ is at least $\$10$ and would then be willing to pay $\$1$ to switch. The same argument applies to switching back, and an agent who uses this type of reasoning could be turned into a money pump as such. It is clarifying to note that in normative models of inference (\emph{e.g.}, not Solomonoff Induction \cite{solomonoff1964formal} or similar), there is no fine line between what does and doesn't constitute a subjective prior. Accordingly, being averse to subjective priors should be understood as a tendency rather than a well-defined property. These tendencies could be introduced into a system via pedagogy. Just as a student in a statistics class who is taught solely using a Frequentist curriculum would be expected to generally avoid subjective priors, so might an AI system. For example, the introduction of a system to Frequentist texts and reinforcement of Frequentist inference with example problems would facilitate this. In particular, example problems in which Frequentist and Bayesian conclusions strongly diverge might be utilized. One way this can be achieved is if a sharp null hypothesis is tested using somewhat inconsistent evidence if a Bayesian uses a diffuse prior on an alternative hypothesis \citep{shafer1982lindley}. This is sometimes referred to as ``Lindley's Paradox'' and it represents a type of training problem in which a Frequentist and Bayesian would come to starkly different conclusions. It is important to recognize is that while a subjective prior-averse agent can come to the conclusion that switching envelopes has a positive expected value in a two envelope situation, they don't \emph{need} to. They could still come to the correct conclusion via a simple argument from symmetry or one which considers the cases in which $X$ is the smaller value or the larger value separately. Consequently, there emerges a risk of logical inconsistencies. While humans often handle inconsistencies well, it is uncertain how AI systems would, and it is plausible that they could result in pathological behavior. For example, in formal systems whose axioms allow for (\textit{$P \to Q$}) to be derived from ($Q$) and for (\textit{$\neg Q \to \neg P$}) from (\textit{$P \to Q$}), any inconsistency could lead to arbitrary conclusions. \subsection{L{\"o}bian Pitfalls}\label{lobian_pitfalls} A highly intelligent system ought be able to reason with logic. But this can be problematic depending on how they interact with proofs or reasons counterfactually. Suppose there exists an agent, $A$, who uses some logical system $\Sigma$ that is at least as powerful as Peano Arithmetic, meaning that it derives L{\"o}b's theorem. L{\"o}b's theorem states that if $\Sigma \vdash (\textrm{Prov}(X) \to X)$ then $\Sigma \vdash X$ where ``$\vdash$'' means ``derives,'' ``$X$'' is a statement, and ``Prov'' a suitable provability predicate \citep{lob1955solution}. Dilemmas arise when considering what $A$ should hypothetically do if presented with a proof within $\Sigma$ that they will take some action $a$. If such a proof were presented, should $A$ accede the proof and take the action, or should they be willing to potentially defy it and take another action? Each stance results in a potential pitfall: via either \emph{spurious proofs} or by \emph{troll bridge problems} respectively. \subsubsection{Spurious Proofs} In the first case, $A$ will accede the proof, and we assume that they have a formal understanding of this proog-obeying behavior. Then a simple L{\"o}bian proof can be used to make them take an arbitrary action \cite{benson2014udt}. The proof sketch is immediate L{\"o}b's theorem. Since a proof that $A$ would take a given action $a$ would then imply that they would take $a$, by L{\"o}b's theorem, it can be proven that they would take $a$ which would then cause $A$ to take it \cite{demski2019embedded}. This means that regardless of whether $A$ were presented with this proof by an external adversary or thought of it themself, once they arrive at one of these proofs, they will commit to the corresponding action.\footnote{Note that no contradictions can emerge here from repeatedly doing this with mutually exclusive actions as long as $A$ can derive in $\Sigma$ that they are indeed mutually exclusive -- this prevents $A$ from acceding any proof beyond the first, so the L{\"o}bian proof no longer goes through.} This pitfall is illustrated by the ``five and ten'' problem \cite{demski2019embedded} in which such agent with two possible actions: \texttt{take \$5} and \texttt{take \$10} could be made to take the \$5 with such a proof. To avoid spurious proofs \cite{benson2014udt} shows that an agent must be willing to defy a hypothetical proof that they would take a given action. This strategy is a form of diagonalization against spurious proofs.\footnote{Importantly, this does not result in its own spurious actions, nor does committing to defy such a proof defy $\Sigma$ because the agent's \emph{hypothetical commitment} to defying such a proof prevents the L{\"o}bian proof from going through in the first place. In other words, this results in no actual contradictions -- just hypothetical ones.} \subsubsection{Troll Bridge Problems} In the second case, $A$ would heed the rule from \cite{benson2014udt} and be willing to defy a proof that they would take some action $a$. Now let us add an additional assumption about $A$. Suppose that they use what \cite{demski2021current} refers to as an \emph{Inferential Theory} of counterfactuals in which there is a \emph{counterfactual conditional} $C(Y|X)$ which describes $A$'s conditional beliefs and obeys the axiom $C(Y|X) , X \to Y$. In other words, this reasoning requires that $A$ believes that $X$ hypothetically being true must imply $Y$ if $C(Y|X)$. At first glance, this theory of counterfactuals may seem innocuous -- it simply requires that counterfactuals are computed from conditionals. But importantly, under this principle, $A$ affirms this counterfactual belief regardless of their state of belief about whether $X$ would prove a contradiction in $\Sigma$. To illustrate the problem, suppose that $A$ must cross a river and has two options. First they could do so by swimming which would result in a utility of $0$. Second they could cross a bridge with a troll underneath. Suppose that this troll is omniscient and that it would blow up the bridge if $A$ crossed without believing that the expected value of crossing were positive. This can be described similarly as the troll blowing up the bridge if $A$ crosses ``as an exploratory action as opposed to an exploitatory one'' or if they cross ``for a dumb reason'' \cite{demski2021current}. If $A$ crosses the bridge successfully, their utility will be $+1$, and if they cross but the bridge blows up, the utility will be some negative value $b < 0$. $A$ would reason that if they crossed the bridge, it would blow up, so they would not cross. The proof sketch \cite{demski2019troll} is as follows: \begin{enumerate} \item Suppose $A$ proves using $\Sigma$ that if they crossed the bridge, it would be blown up. \item Then assuming that $A$ is a utility maximizer who uses an Inferential Theory of counterfactuals, crossing would prove that $\Sigma$ is inconsistent. \item Thus crossing would lead to the bridge blowing up by the problem specification. \end{enumerate} So $A$ would not cross regardless of their priors. While this is a straightforward conclusion from the proof, it is a very odd stance to arrive at. Arriving at this conclusion means that $A$ believes that the counterfactual scenario in which they cross the bridge proves the inconsistency of $\Sigma$. This prompts the question of how the agent could be justified in its counterfactual reasoning when the counterfactual indicates the insanity of the very logical system that is being used. Another peculiarity is that this line of reasoning will lead $A$ to not cross the bridge, regardless of their priors. Even if $b=-0.0001$ and $A$ reasoned that the prior probability of it blowing up if crossed were $0.0001$, they would still not cross. But arguably, $A$'s counterfactual expectations should be the same as their priors about crossing because the conditional line of reasoning gets $A$ nowhere useful – it stems from a contradiction. To avoid these issues, \cite{demski2021current} argues that the $A$ should adopt a \emph{Subjective Theory} of counterfactuals which drops the Inferential one's rules for the counterfactual conditional. This means to disentangle \emph{hypothetical} reasoning and \emph{conditional} reasoning by relaxing the requirement from the Inferential Theory that counterfactuals are computed from conditionals. This can allow for counterfactual and conditional reasoning to disagree within a hypothetical, but not in the real world. Then agent $A$ can begin to step through the proof above and come to the hypothetical belief that crossing would result in a negative utility. But, within the hypothetical, if this does not have to change the counterfactual belief, $A$ can hypothetically cross anyway. This prevents the L{\"o}bian proof from going through, and $A$ is clear to cross according to its prior counterfactual expectations. Additionally, since the proof does not go through, the conditional expectations will also agree with the counterfactual ones in reality, so there is no disparity between the two in practice.\footnote{Again, there are no actual contradictions here -- just hypothetical ones.} \subsubsection{Discussion} Ultimately, being proof-respecting or using an inferential theory of counterfactuals represent a high level stances in decision theory, so pedagogy may be the most promising way of introducing such an Achilles Heel, though it may not be stable. If successfully implanted, these Achilles Heels would only cause impairment in situations where they stumble upon spurious proofs or trolls who can read their source code, so these weaknesses would be subtle and potentially effective means for containment. \section{Meta Considerations} \label{meta} Beyond an abstract understanding of how agents with certain Achilles Heels would behave are more practical complications. Notably any approach to working with systems that may possess AGI/ASI should involve caution and few assumptions. Tegmark \cite{tegmark2017life} argues that if control is lost over such a system, it may be entirely unclear what caused it.\\ \noindent \textbf{Incoherent Decision Making:} This paper makes use of the assumption that the behavior of an AGI/ASI system in certain domains may be well-explained using decision-theoretic abstractions. This is supported by how interpretability techniques have been used to develop programmatic understandings of the functions which machine learning models compute (\emph{e.g.}, \cite{verma2018programmatically}). However, there is no special reason to expect a system to act in accordance with a single coherent set of principles all the time. For this reason few assumptions should be made about what types of Achilles Heels a system may have without testing for their presence in a set of inputs from the same distribution as it would encounter in deployment.\\ \noindent \textbf{Spillovers:} By definition, Achilles Heels should generally be subtle and only cause failures in adversarial circumstances. Nonetheless, there is a risk of failures in non-adversarial situations. For example, as discussed in Section \ref{subjective_priors}, being averse to the use of subjective priors can lead to quantitatively different solutions from Bayesian approaches or even logical inconsistencies in two-envelope-like games. For all types of Achilles Heels, interpretability methods may aid in understanding when failures will occur. Examples of interpretability methods being used to identify adversarial weaknesses were demonstrated in \cite{carter2019exploring, mu2020compositional}, and for advanced systems, a self-explaining AI paradigm \cite{elton2020self} would also be valuable.\\ \noindent \textbf{Subversion:} An intelligent system being less uncertain about what weaknesses it may have can help it subvert those weaknesses. Some Achilles Heels may be cured by a system knowing about them. For example, if a system placed a significant probability on it being contained via simulational belief, then it would be able to update its anthropic beliefs and behavior accordingly. A factor in whether this will happen is how well a system understands decision theory. If a system understands it well, perhaps via access to this paper or related literature, this knowledge would be helpful toward subverting Achilles Heels.\\ \noindent \textbf{Subagents Successors, and Mesa-Optimizers:} One particular means by which a system could overcome an Achilles Heel would be by designing an auxiliary system that did not contain the vulnerability.\footnote{This does not necessarily apply to all corrigibility measures or passive weaknesses such as simulational belief.} Although certain decision theories have flaws, any which is useful in even a most basic sense will be able to recognize its own mistakes if that decision theory is applied to the action of choosing to use itself. For example, if an evidential decision theorist is given the choice between keeping its current source code and rewriting its source code to implement CDT before being presented with a smoking lesion problem, then it would perform the rewrite. Furthermore, if an Achilles Heel is implanted by a unique adversarial training procedure, that procedure may not be replicated in the process a system uses to create a new agent. Consequently, most\footnote{Ibid.} Achilles Heels are not stable by default if a system creates subagents, successors, or mesa optimizers\footnote{Mesa optimizers \cite{hubinger2019risks} refer to inner optimization processes that a system may develop to find a solution to a problem as opposed to developing that solution directly.} \cite{hubinger2019risks}. \\ \noindent \textbf{Prospects for Containment:} Being able to contain and control systems if they exhibit misaligned behavior is key for the safe development of AI \cite{babcock2017guidelines}. Because Achilles Heels by definition are adversarial to a system's reward function, an obvious question is whether they may be useful for containment. The corrigibility methods discussed in Section \ref{corrigibility} were formulated as a solution to this. Additional, simulational belief as discussed in Section \ref{simulational} would also be useful as a passive measure. And L{\"o}bian pitfalls have the potential to allow agents to be either arbitrarily manipulated or kept from taking certain actions by trolls. Aside from these, the remaining Achilles Heels discussed in Section \ref{survey} are EDT, CDT, updateful decision theory, Sleeping Beauty assumptions, divergent temporal models, and aversion to subjective priors. Each of which causes vulnerabilities by making a system prone to a Dutch Book or, more generally, just making bad bets. For this reason, so long as failure in one of these situations can be connected to something desirable for containment such as the forfeiture of instrumental resources \cite{hutter2004universal}, then they could also be useful for containment. However, there are two broad issues with using bad-bet-based methods for containment. First, they would require adherence to the rules of some sort of process (\emph{e.g.}, an agent in a Newcombian game can't steal the \$1,000,000). While it can be possible to compel certain systems to follow certain rules, agents of arbitrary power cannot be expected to follow rules imposed on them in general. One potential solution would be to build an incentive to follow rules of such a process into an agent's reward function. Although this would be a significant specification problem in and of itself, it would be strictly simpler than the broader problem of aligning AI systems with human-compatible goals overall. Second, a containment strategy which operates based on a bad-bet mechanism will not be unique in the sense that something similar could be accomplished by a strategy which is not adversarial to an agent's reward function. In each of these dilemmas, an agent with an Achilles Heel is motivated by prospects for reward, so the same type of behavior could be elicited via simple bribes of reward. For example instead of exploiting an agent to forfeit instrumentally valuable resources in order to chase the folly of an infinite reward in a procrastination paradox, the same behavior could be more straightforwardly elicited by actually giving the agent a reward. \section{Discussion} \label{discussion} \begin{table}[] \centering \small \begin{tabular}{|l|l|l|l|l|l|} \hline & \textbf{Implantation} & \textbf{Stability} & \textbf{Impairment} & \textbf{Subtlety} & \textbf{Containment}\\ \hline \textbf{Corrigibility} & Indifference & --- & Intervention & Non-subtlety risk & Potential\\ \hline \textbf{EDT} & Factual info & --- & Bad bets & --- & --- \\ \hline \textbf{CDT} & Factual/ctr.factual info & --- & Bad bets & --- & ---\\ \hline \textbf{Updateful-DT} & Updatefulness & --- & Bad bets & --- & ---\\ \hline \textbf{Sim. Belief} & Pedagogy & Instability risk & Passive & Usefully non-subtle & Potential\\ \hline \textbf{Sleeping Beauty} & Pedagogy (SSA/SIA) & Instability risk & Bad bets & Side-effects & --- \\ \hline \textbf{Divergence} & Temporal-recursiveness & --- & Bad bets & --- & ---\\ \hline \textbf{No Subj. Priors} & Pedagogy & Instability risk & Bad bets & Non-subtlety risk & --- \\ \hline \textbf{L{\"o}bian} & Pedagogy & Instability risk & Sp.proofs/trolls & --- & Potential \\ \hline \end{tabular} \caption{\textbf{The Achilles Heels presented in this paper with select comments on the criteria from Section \ref{intro} and containment prospects.} For several Achilles Heels, a particular potential for instability or non-subtlety is noted but does not indicate that others are immune to instability or spillover. None are.} \label{tab:comments} \end{table} This work introduces the \emph{Achilles Heel hypothesis} concerning how highly-effective goal-oriented agents (even ones who are potentially superintelligent) may nonetheless possess stable delusions which can cause failure in adversarial situations. A number of these potential Achilles Heels are outlined alongside methods by which they can be implanted. Table \ref{tab:comments} summarizes the Achilles Heels discussed here and includes brief notes related to implantation, stability, impairment, subtlety, and prospects for containment. It is possible that novel Achilles Heels exist other than the ones presented here, and uncovering additional ones may be a promising direction for further work. In general, humans finding any problem difficult or paradoxical is a potential sign that an AGI/ASI system might as well. Challenging the Achilles Heel hypothesis may also lead to new insights. A limitation of this work is its focus on understanding sufficiency criteria for when a system will have an Achilles Heel. Given how AI systems will not generally adhere to a simple, coherent set of decision theoretic principles, proving necessity criteria will involve additional assumptions. Nonetheless, these may be valuable for developing theoretical assurances for when a system will \emph{not} develop one of these weaknesses. Formulating additional strategies for how certain decision theoretic tendencies can be implanted into systems would be valuable for assurance. Progress in symbol grounding and related questions involving theory of mind for AI systems will be helpful toward this goal. This author believe that understanding how advanced AI systems may develop Achilles Heels and the various dilemmas which may exploit them will be valuable for modeling these systems, containing them, and making them more robust via design and adversarial training. A thorough understanding of Achilles Heels will be best paired with well-developed specification and transparency measures for ensuring the aligned development of advanced AI. Although modeling these systems remains a difficult challenge, this work makes progress toward understanding novel failure modes and why even superintelligent systems may possess them. \section*{Acknowledgements} \label{acknowledgements} This work has benefitted from the feedback of Rohil Badkundri, Luke Bailey, Michael Dennis, Daniel Filan, Adam Gleave, Erik Jenner, Koen Holtman, Pranav Misra, Rohin Shah, Johannes Treutlin, and Alex Turner. Caspar Oesterheld in particular provided valuable insights and discussion. \small \bibliographystyle{plain}
{'timestamp': '2022-09-20T02:21:41', 'yymm': '2010', 'arxiv_id': '2010.05418', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05418'}
arxiv
\section{Introduction} The cost of IC manufacturing has increased 5$\times$ when scaling from 90nm to 7nm~\cite{iccost}. An increasing number of design houses are now {\em fab-less} and outsource the fabrication to a third-party foundry~\cite{fabless,manufacturing}. This reduces the cost of operating expensive foundries but raises security issues. If a rogue in the third-party foundry has access to the design files, they can reverse engineer the IC functionality to steal the Intellectual Property (IP), causing economic harm to the design house~\cite{pieee14}. Fig.~\ref{fig:design_flow} is a fabless IC design flow with third-party manufacturing. The flow accepts the specification in a {\em hardware description language} (HDL). Designers create the components either manually or generate them automatically, and integrate them into a hardware description at the register-transfer level (RTL). Given a technology library (i.e., a description of gates in the target technology) and a set of constraints, logic synthesis elaborates the RTL into a gate-level netlist. Logic synthesis applies optimizations to reduce area and improve timing. While RTL descriptions are hard to match against high-level specifications~\cite{8000621}, they are used as a golden reference during synthesis to verify each step does not introduce any error. Physical design generates the layout files that are sent to the foundry for fabrication of ICs that are then returned to the design house for packaging and testing. Assuming a trusted design house, the foundry is the first place where a malicious attacker can reverse engineer and replicate an IC. \begin{figure}[!tp] \centering \includegraphics[width=\columnwidth]{figures/design_flow} \caption{State-of-the-art IC design flow. Designers create RTL description of an IC either by manual design, or by using HLS tools, or by using hardware generators. The netlist after more processing steps is sent to a third-party foundry. ASSURE locks an RTL description before logic synthesis. } \label{fig:design_flow} \end{figure} Semiconductor companies are developing methods for IP obfuscation. In {\em split manufacturing}, the design house splits the IC into parts that are fabricated by different foundries~\cite{6513707}. An attacker must access all parts to recover the IC. While the design process becomes more complex, the designers cannot guarantee complete security. {\em Watermarking} hides a signature inside the circuit, which is later verified during litigation~\cite{abdel2003ip}. Finally, designers apply {\em logic locking}~\cite{10.1145/3342099} to prevent unauthorized copying and thwart reverse-engineering. They introduce extra gates controlled by a key that is kept secret from the foundry. They {\em activate} the IC functionality by installing the key into a tamper-proof memory after fabrication. \subsection{Related Work}\label{sec:related} Logic locking is a popular technique to protect the intellectual property of ICs~\cite{llcarxiv}. Designers can apply logic locking at different abstraction levels and configure the protection based on the information available to the attacker~\cite{10.1145/3342099}. Many existing methods operate on the gate-level netlists~\cite{llcarxiv}. Gate-level locking can not obfuscate all the semantic information because logic synthesis and optimizations absorb much of it into the netlist before the locking step. For example, constant propagation absorbs and propagate the constants. Our method completely strips the constants from the circuit before synthesis. Recently, alternative high-level locking methods obfuscate the semantic information before logic optimizations embed them into the netlist~\cite{dac18,rtlOzgur}. For example, TAO applies obfuscations during HLS~\cite{dac18} but requires access to the HLS source code to integrate the obfuscations and cannot obfuscate existing IPs. Protecting a design at the register-transfer level (RTL) is an interesting compromise~\cite{obfuscateDSPRTL,5401214}. Most of the semantic information (e.g., constants, operations and control flows) is still present in the RTL and obfuscations can be applied to existing RTL IPs. In~\cite{obfuscateDSPRTL}, the authors propose structural and functional obfuscation for DSP circuits. We propose a more general method that can be applied to any type of circuit. In~\cite{5401214}, the authors propose a method to insert a special finite state machine to control the transition between obfuscated mode (incorrect function) and normal mode (correct function). Such transition can only happen with a specific input sequence. We use a similar method to obfuscate the operations without additional logic (and power-up overhead) to make the circuit functional in normal mode. To obfuscate the semantic information, ASSURE leverages prior work on software program obfuscation~\cite{collberg91,BEHERA2015757,xu2017}. These methods obfuscate data structures, control flows, and constants through code transformations or by loading information from memory at runtime. We use a similar approach to create {\em opaque predicates} dependent only on the locking key~\cite{5401214}. When the attackers have access only to the circuit netlist (like in the early stages of the fabrication process), they need to identify the correct variant among the ones created by the locking key. Redundancy attacks can recover part of the key bits for several locking methods~\cite{8714955}, while machine learning can predict the key bit values based on the structure of the circuit~\cite{sisejkovic2020challenging}. However, such attacks cannot recover what is not present in the circuit, like extracted constants, and cannot distinguish semantically equivalent variants. When the attackers can access also an activated IC (i.e. the oracle)~\cite{metrics2018,Shen:2019:BBS:3287624.3287670}, they can use Boolean Satisfiability (SAT)-based attacks to recover the key. Several solutions have been proposed to thwart SAT-based attacks~\cite{8279462,Yasin:2017:PLL:3133956.3133985}. For example, stripped-functionality logic locking (SFLL) extracts part of the functionality, which is hidden and restored upon the application of the correct key~\cite{Yasin:2017:PLL:3133956.3133985}. SFLL-HLS is the corresponding HLS-level extension~\cite{8942150}. However, complete protection is not guaranteed as attacks on SFLL have been reported when the ``protected'' functional inputs are at a certain Hamming distance from the key~\cite{sfll19,Deepak19}. Also, many SAT-resilient protections, like SARLock and SFLL, can be broken even with oracle-less attacks~\cite{8714955}. So, the approaches for the different threat models are complementary and must be combined to obtain multi-level protection. In this work, we aim at avoiding the attackers can recover the circuit with modern oracle-less attacks. {\em\uline{We base our techniques on the concept of {\bf indistinguishability}: all Boolean functions generated by a locking key have the same probability of being the correct circuit}}. So, netlist-only attacks are not able to identify and rule out ``incorrect'' designs. \subsection{Paper Contributions} ASSURE RTL obfuscation uses three techniques to obfuscate constants, arithmetic operations, and control branches. ASSURE provides the following contributions with respect to the state-of-the-art approaches: \begin{itemize}[leftmargin=*,topsep=0pt,noitemsep] \item the three ASSURE techniques are complete and provably secure for creating {\em indistinguishable RTL designs} with no limitations on the input descriptions to be protected; \item ASSURE can provide {\em multi-level security} together with oracle-based protections (e.g., scan-chain isolation~\cite{9214869}); \item ASSURE is a {\em technology-independent tool} that is fully compatible with existing EDA design flows and leaves complete control to the designer on the obfuscation process. \end{itemize} We describe our RTL-to-RTL translation framework in Section~\ref{sec:assure}, along with security proofs of obfuscations for constants, operations, and branches (Section~\ref{sec:techniques}). We also assess security against state-of-the-art oracle-less attacks (Section~\ref{sec:security}) and evaluate the related overhead (Section~\ref{sec:cost}). \section{Threat Model: Untrusted Foundry}\label{sec:threat_model} The state-of-art in logic locking considers two broad categories of threat models: netlist-only and oracle-guided~\cite{10.1145/3342099,8741035}. In both settings, the attacker has access to a locked netlist, but in the latter, also to an unlocked IC (\textit{oracle}) to analyze input/output relationships. The netlist-only model applies for an untrusted foundry that accesses the IC design for the first time. It also captures low-volume settings -- e.g., the design of future defense systems with unique hardware requirements~\cite{security} -- where the attacker would not reasonably be able to access a working copy of the IC. Consider, for instance, a fab-less defense contractor that outsources the fabrication of an IC to an {\bf untrusted foundry}. The untrusted foundry has access to the layout files of the design and can reverse engineer a netlist and even extract the corresponding RTL~\cite{7100906}. However, since the foundry produces the first ever batch of an IC design (in some cases the only one), an activated chip is not available through any other means. Attacks that rely on knowledge of an IC's true I/O behaviour (e.g., SAT attacks) cannot be applied and are therefore out-of-scope. However, the attacker can still rely on a range of netlist-only attacks, \textit{desynthesis}~\cite{DBLP:journals/corr/MassadZGT17}, \textit{redundancy identification}~\cite{8714955} and \textit{ML-guided structural and functional analysis}~\cite{sail,surf}, for instance, to recover the key bits and reverse engineer the locked netlist. In the following, we prove the resilience of ASSURE obfuscation to not only these three attacks, but also that ASSURE locked netlists reveal \emph{no information} about the design other than any prior knowledge that the designer might have about the design. In the oracle-guided model, the attackers need to get an unlocked IC from the market -- e.g., because of high-volume commercial fabrication -- to analyze I/O relationships and apply the corresponding attacks. With our method, we thwart attacks that are successful for oracle-guided protections even without activated IC. \begin{figure} \centering \includegraphics[width=\columnwidth]{figures/assure_flow} \caption{Organization of ASSURE.}\label{fig:assure} \end{figure} \section{Overview of ASSURE}\label{sec:assure} Fig.~\ref{fig:assure} shows the ASSURE flow. Given an RTL design~$D$ and a set of obfuscation parameters, ASSURE generates a design $D^*$ together with a single locking key $\mathcal{K}^{*}_r$ such that $D^*$ matches the functionality of $D$ only when $\mathcal{K}^{*}_r$ is applied. ASSURE is a technology-independent and operates on the RTL after system integration but before logic synthesis. ASSURE obfuscates existing IPs and those generated with commercial HLS tools. Even if logic locking is a hardware approach, obfuscating RTL code has analogies with {\em program obfuscation} to protect the software IP~\cite{collberg91,xu2017}. In both cases, the designer aims at obfuscating the semantic information contained into the design rather than its structure~\cite{5401214}. ASSURE obfuscates the RTL by adding in {\em opaque predicates} such that the evaluation of the opaque predicates depends on the locking key; their values are known to the designer during obfuscation, but unknown to the untrusted foundry. ASSURE obfuscates three {\bfseries semantic elements} useful to replicate function of an IP: \begin{itemize}[leftmargin=*,topsep=0pt,noitemsep] \item {\em constants} contain sensitive information in the computation (e.g., filter coefficients). \item {\em operations} determine functionality. \item {\em branches} define the execution flow (i.e., which operations are executed under specific conditions). \end{itemize} ASSURE parses the input HDL and creates the {\em abstract syntax tree} (AST) -- step \circled{1}. It then analyzes the AST to select the semantic elements to lock (step~\circled{2}) and obfuscates them ({\em AST elaboration} -- step~\circled{3}). The {\em RTL generation} phase (step~\circled{4}) produces the output RTL design that has the same external interface as the original module, except for an additional input port that is connected to the place where $\mathcal{K}^{*}_r$ is stored. ASSURE starts from a synthesizable IP and modifies its description, it fits with existing EDA flows and same constraints as the original, including tools to verify that resulting RTL is equivalent to the original design when the correct key is used and to verify that it is not equivalent to the original when an incorrect key is used. The key idea of ASSURE is that the functionality of $D^*$ is much harder to understand without the parameter~$\mathcal{K}^{*}_r$. If the attackers apply a key different from $\mathcal{K}^{*}_r$ to $D^*$, they obtain plausible but wrong circuits, indistinguishable from the correct one. These variants are {\it indistinguishable} from one another without a-priori knowledge of the design. \subsection{ASSURE Obfuscation Flow}\label{sec:assure_analysis} To generate an obfuscated RTL design, we must match the requirements of the IP design with the constraints of the technology for storing the key (e.g., maximum size of the tamper-proof memory). On one hand, the number of bits needed to obfuscate the semantics of an RTL design depends on the complexity of the algorithm to protect. On the other hand, the maximum number of key bits that can be used by ASSURE ($K_{max}$) is a design constraint that depends on the technology for storing them in the circuit. ASSURE analyzes the input design to identify which modules and which circuit elements in modules must be protected. First, ASSURE does {\bf depth-first analysis} of the design to {\em uniquify} the module hierarchy and creates a list of modules to process. In this way, {\em\uline{ASSURE hides the semantics of the different modules so that extracting knowledge from one instance does not necessarily leak information on all modules of the same type}}. \begin{algorithm}[t!] \footnotesize \SetKwFunction{ObfuscateModule}{ObfuscateModule} \SetKwFunction{CreateBlackList}{CreateBlackList} \SetKwFunction{DepthFirstAST}{DepthFirstAST} \SetKwFunction{BitReq}{BitReq} \SetKwFunction{Obfuscate}{Obfuscate} \SetKwFunction{GetObfuscationKey}{GetObfuscationKey} \SetKwFunction{KeyLength}{KeyLength} \SetKwProg{obfuscateModule}{Procedure}{}{} \caption{ASSURE obfuscation.\label{alg:obfuscate}} \obfuscateModule{\ObfuscateModule{$AST_m$, $\mathcal{K}^*_r$, $K_{max}$}}{ \KwData{$AST_m$ is the AST of the module $m$ to obfuscate} \KwData{$\mathcal{K}^*_r$ is the current locking key} \KwData{$K_{max}$ is the maximum number of key bits to use} \KwResult{$AST^*_m$ is the obfuscated AST of the module $m$} \KwResult{$\mathcal{K}^*_r$ is the updated locking key} $\mathtt{BlackList} \gets $ \CreateBlackList{$AST_m$}\; $AST^*_m \gets \mathtt{BlackList}$\; $\mathtt{ObfElem} \gets $ \DepthFirstAST{$AST_m$}~$\setminus$~$\mathtt{BlackList}$\; \ForEach{$el \in \mathtt{ObfElem}$}{ $b_{el} \gets $ \BitReq{$el$}\; \eIf {\KeyLength{$\mathcal{K}^*_r$}$ + b_{el} > K_{max}$}{ $AST^*_m \gets AST^*_m \cup el$\; } { $K_{el} \gets $ \GetObfuscationKey{$el$}\; $AST^*_m \gets AST^*_m \cup $ \Obfuscate{$el$, $K_{el}$}\; $\mathcal{K}^*_r \gets \mathcal{K}^*_r \cup K_{el}$\; } } \Return{$\{AST^*_m,\mathcal{K}^*_r\}$} } \end{algorithm} After uniquifying the design, ASSURE analyzes the AST of each module with Algorithm~\ref{alg:obfuscate} starting from the innermost ones. Given a hardware module, ASSURE first creates a ``black list'' of the elements that must be excluded from obfuscation (line 2). For example, the black list contains elements inside reset and update processes or loop induction variables (see Section~\ref{sec:techniques}). The designer can also annotate the code to specify that specific regions or modules must be excluded from obfuscation (e.g., I/O processes or publicly-available IPs). The black-list elements are added unchanged to the output AST (line 3). Finally, ASSURE determines the list of AST elements to obfuscate (line 4) and process them (lines 5-12). The resulting list \texttt{ObfElem} follows the visit order of the depth-first search. For each element, ASSURE computes the number of bits required for obfuscation (line 6) and check if there are enough remaining key bits (line 7). If not, ASSURE does not obfuscate the element (line 8). Indeed, reusing a key bit across multiple elements as in~\cite{dac18} reduces the security strength of our scheme because extracting the key value for one element invalidates the obfuscation of all others sharing the same key bit. If the obfuscation is possible (lines 9-12), ASSURE generates the corresponding key bits to be added to $\mathcal{K}^*_r$ (line 10). These bits depend on the specific obfuscation technique to be applied to the element and can be randomly generated, extracted from an input key (see Fig.~\ref{fig:assure}), or extracted from the element itself (see Section~\ref{sec:techniques}). ASSURE uses these key bits to obfuscate the element and the result is added to the output AST (line 11). The key bits are also added to the output locking key (line 12). We repeat this procedure for all modules until the top, which will return the AST of the entire design and the final key. This approach leaves full control to the designers that can explore trade-offs by providing constraints on the number of bits and combining the depth-first analysis with the annotations to exclude elements from obfuscation. \subsection{ASSURE Obfuscations and Security Proofs}\label{sec:techniques} Each of the ASSURE techniques targets an essential element to protect and uses a distinct part of the $r$-bit locking key $\mathcal{K}^{*}_r$, to create an opaque predicate\footnote{We use Verilog notation in the examples, but the approach is general.}. In software, an {\em opaque predicate} is a predicate for which the outcome is certainly known by the programmer, but requires an evaluation at run time~\cite{collberg91}. We create {\bf hardware opaque predicates}, for which the outcome is determined by ASSURE (and so known) at design time, but requires to provide the correct key at run time. Any predicate involving the extra parameter $\mathcal{K}^{*}_r$ meets this requirement. Given a locking key $\mathcal{K}^{*}_r$, {\em\uline{ASSURE generates a circuit \textbf{indistinguishable} from the ones generated with any other $\mathcal{K}_r\neq \mathcal{K}^{*}_r$ when the attacker has no prior information on the design}}. We show that ASSURE techniques offer provable security guarantees~\cite{DBLP:journals/corr/MassadZGT17}. Consider an $m$-input $n$-output Boolean function $\mathcal{F}$ : $X \rightarrow Y$, where $X \in \{0,1\}^{m}$ and $Y \in \{0,1\}^{n}$. {\bf\noindent Definition} Obfuscation $\mathcal{O}(\mathcal{K}^{*}_r)$ transforms $\mathcal{F}$ into an $m+r$-input $n$-output function $\mathcal{L}_{\mathcal{K}^*_r}$ defined as: \begin{equation} \mathcal{L}_{\mathcal{K}^*_r}(X,K) = \mathcal{O}(\mathcal{F}(X),\mathcal{K}^*_r) \end{equation} where $\mathcal{L}_{\mathcal{K}^*_r}$: $X \bigtimes K \rightarrow Y$ and $K \in \{0,1\}^{r}$ are such that \begin{itemize} \leftskip =-10pt \rightskip =-10pt \item $\mathcal{L}_{\mathcal{K}^*_r} (X,\mathcal{K}^{*}_r) = \mathcal{F}_{\mathcal{K}^*_r}(X) = \mathcal{F}(X)$ \item $\mathcal{L}_{\mathcal{K}^*_r} (X,\mathcal{K}_r) = \mathcal{F}_{\mathcal{K}_r}(X) \neq$ $\mathcal{F}(X)$ when $\mathcal{K}_r\neq \mathcal{K}^{*}_r$ \end{itemize} This definition shows $\mathcal{C}_{\mathcal{K}^*_r}$ represents a family of Boolean functions $\{\mathcal{F}_{K_r}\}$ based on the generic $r$-bit key input $\mathcal{K}_r$. The functionality $\mathcal{F}(X)$ can be re-obtained uniquely with the correct key $\mathcal{K}^*_r$. This is followed by a corollary about a characteristic of the family of Boolean functions $\mathcal{L}_{\mathcal{K}^*_r}$. \begin{theorem} For an obfuscated netlist $L_{\mathcal{K}^*_r}(X,K)$ created from $\mathcal{F}(X)$ with obfuscation $\mathcal{O}(\mathcal{K}^{*}_r)$, the unlocked functions $\mathcal{F}_{K_1}$ and $\mathcal{F}_{K_2}$ (for keys $K_1$ and $K_2$) relate as follows: \begin{gather} \mathcal{F}_{K_1} \neq \mathcal{F}_{K_2} \forall K_1, K_2 \in K: K_1 \neq K_2 \end{gather} \end{theorem} \begin{proof} Let us first consider case (i) $K_1 = \mathcal{K}^*_r$. Therefore, by the definition of RTL obfuscation scheme $\mathcal{O}$, $\mathcal{F}_{K_1} \neq \mathcal{F}_{K_2} \forall K_2 \in K, K_1 \neq K_2$. Now, for case (ii) $K_1 \neq \mathcal{K}^*_r$, there exists a locked netlist $\mathcal{L}_{\mathcal{K}^*_r}$ that locked $\mathcal{F}_{K_1}$ using $K_1$. Therefore, $\mathcal{F}_{K_2}$ = $\mathcal{L}_{\mathcal{K}^*_r}(X,\mathcal{K}_2)$. By the definition of logic locking security, $\mathcal{F}_{K_2} \neq \mathcal{F}_{K_1} \forall K_2 \neq K_1$ in $\mathcal{L}_{\mathcal{K}^*_r}(X,\mathcal{K}_r)$. \end{proof} \begin{figure*} \centering \subfloat[][Constant obfuscation]{\includegraphics[height=2.5cm]{figures/const_obfuscation}\label{fig:const_obfuscation}} \hfill \subfloat[][Operation obfuscation]{\includegraphics[height=2.5cm]{figures/op_obfuscation}\label{fig:op_obfuscation}} \hfill \subfloat[][Branch obfuscation]{\includegraphics[height=2.5cm]{figures/branch_obfuscation}\label{fig:branch_obfuscation}} \caption{Three ASSURE obfuscations. (a) Constant, (b) Operation, and (c) Branch. Each obfuscation uses a portion of the key.} \label{fig:techniques} \end{figure*} We define $P[\mathcal{L}_{\mathcal{K}_r} | \mathcal{O}(\mathcal{F}(X),\mathcal{K}]$ as the probability of obtaining the locked design $\mathcal{L}_{\mathcal{K}_r}$ given that we locked the Boolean function $\mathcal{F}(X)$ applying $\mathcal{O}$ with $\mathcal{K}$. The RTL locking scheme $\mathcal{O}$ is secure under the netlist-only threat model: \begin{theorem}\label{theo:strong} A logic locking scheme $\mathcal{O}$ for $r$-bit key $K$ is secure for a family of Boolean functions $\mathcal{F}_{K_r}$ of cardinality $2^r$ if the following condition holds true: \begin{gather} P[\mathcal{L}_{\mathcal{K}'_r} | \mathcal{O}(\mathcal{F}(X),\mathcal{K}^*_r)] = P[\mathcal{L}_{\mathcal{K}'_r} |\mathcal{O}(\mathcal{F}_{K_r}(X),\mathcal{K}_r)]\nonumber \\ \forall \mathcal{K}_r \neq \mathcal{K}^*_r, \mathcal{F}(X) \neq \mathcal{F}_{K_r}(X) \end{gather} \end{theorem} \noindent This theorem states any locking key $\mathcal{F}_{K_r}$ is equally probable to generate the locked netlist $\mathcal{L}_{\mathcal{K}'_r}$ generated by the locking scheme $\mathcal{O}$, creating a family of Boolean function $\mathcal{F}_{K_r}(X)$ all having the same probability to be the original Boolean function $\mathcal{F}(X)$. We show all our obfuscations satisfy these two claims, providing a security guarantee of $2^r$ under the proposed threat model. This guarantee allows the designer to choose the parameter $r$ to match the technology issues for storing the bits in the final IC. ASSURE will generate a locked design with the corresponding level of security. \subsubsection{Constant Obfuscation} This obfuscation removes selected constants and moves them into the locking key $K$ as shown in Fig.~\ref{fig:const_obfuscation}. The original function is preserved only when the key provides the correct constant values. {\em\uline{Each constant bit is a {\em hardware-opaque predicate}; the designer knows its value and the circuit operation depends on it}}. \noindent {\em {\bf Example: } Consider the RTL operation {\tt b = a + 5'b01010}. To obfuscate the constant, we add a 5 bit key {\tt K\_c = 5'b01010}. The RTL is rewritten as {\tt b = a + K\_c}. The attacker has no extra information and $2^{5}$ possibilities from which to guess the correct value.\hfill$\Box$} Hiding constant values allows designers to protect sensitive information (e.g., proprietary implementations of digital filters or cryptographic algorithms~\cite{10.1007/978-3-662-43826-8_10}) but also may prevent subsequent logic optimizations (e.g., constant propagation and wire trimming). However, several constants are unuseful and, in some cases, problematic to protect. For example, reset values are set at the beginning of the computation to a value that is usually zero and then assigned with algorithm-related values. Also, obfuscating reset polarity or clock sensitivity edges of the processes introduces two problems: incorrect register inferencing, which leads to synthesis issues of the obfuscated designs, and incorrect reset process that easily leads to identify the correct key value. In particular, if we apply obfuscation to the reset processes and the attacker provides an incorrect key value, the IC will be stalling in the reset state when it is supposed to be in normal execution. So, we exclude constants related to reset processes and sensitivity values from obfuscation. {\em\uline{Proof}}. The structure of the obfuscated circuit is independent of the constant and, given an $r$-bit constant, the $2^r$ values are indistinguishable. The attacker cannot get insights on the constants from the circuit structure. ASSURE constant obfuscation satisfies the provable security criteria of logic locking $\mathcal{L}$ under strong adversarial model as defined in Theorem~\ref{theo:strong}. Let us consider an RTL design of $m$ inputs and $n$ outputs $R : X \rightarrow Y$, $X \in \{0,1\}^m$ and uses an $r$-bit constant $C^*_{r}$. ASSURE constant obfuscation converts the $r$-bit constant into an $r$-bit key $K^*_r$ as a lock $\mathcal{O}$ and uses it to lock the design $\mathcal{L}_{\mathcal{K}^*_r}$. The obfuscated constant $C_r$ is depicted as follows: \begin{gather} C_r = \mathcal{K}_r \end{gather} where, $C_r = C^*_r$ only when $\mathcal{K}_r = \mathcal{K}^*_r = C^*_r$. \begin{quote} \leftskip =-20pt \rightskip =-20pt \textbf{Claim 1}: Any unlocked constant $C_{K_1}$ and $C_{K_2}$ using r-bit keys $K_1$ and $K_2$ are unique. (Theorem 1) \end{quote} \begin{proof} $\forall K_1 \neq K_2$, $K_1, K_2 \in \{0,1\}^r$ $\implies C_{K_1}\neq C_{K_2}$. \end{proof} \begin{quote} \leftskip =-20pt \rightskip =-20pt \textbf{Claim 2}: A constant-obfuscated circuit with r-bit key $K$ can be generated from $2^r$ possible constants (each of $r$-bit) with equal probability, i.e. the following holds true. \begin{gather} P[C_r | K = \mathcal{K}^*_r] = P[C_r | K = K_r] \nonumber\\ \forall K_r \neq K^*_r ; K_r \in 2^r \end{gather} \end{quote} \begin{proof} The probability of choosing $K_r$ is uniform. So, \\ $P[K = \mathcal{K}^*_r] = P[K = \mathcal{K}_r]$, $\forall K_r \neq K^*_r$ \\ $\implies P[C^*_r] = P[C_{r}]$, $C^*_r \neq C_r, \forall C_r \in \{0,1\}^r$. \end{proof} Claims 1 and 2 jointly denote that the constant obfuscated by $2^r$ unique constants are indistinguishable and can be unlocked uniquely by the correct $r$-bit key. Constant obfuscation hides the original constants with a security strength of $2^r$. In Fig.~\ref{fig:constantExtraction}, we show area overhead of \texttt{DES3} and \texttt{RSA}, two CEP benchmarks~\cite{cep}. This experiment shows that constant obfuscation generates indistinguishable circuits. We consider a variable from each benchmark: \texttt{sel\_round} from \texttt{DES3} and \texttt{modulus\_m1\_len} from \texttt{RSA}. We generate different circuits by assigning different constants to the same variable. We synthesize these circuit variants and obtain the area overhead. Fig.~\ref{fig:constantExtraction} shows that every constant value ($c1-c5$) can be reverse engineered from the synthesized circuit since each constant directly maps to unique area overhead. On the contrary, the area overhead of synthesized circuits remain the same after obfuscation, and the obfuscated circuits are indistinguishable, making it difficult for the attacker to recover the constant. \subsubsection{Operation Obfuscation} We generate a random key bit and use it to multiplex the operation result with that from another operation sharing the same inputs, as shown in Fig.~\ref{fig:op_obfuscation}. {\em\uline{The mux selector is a {\em hardware opaque predicate} because the designer knows its value and the mux propagates the correct result only for the correct key bit}}. This is similar to that proposed for C- and HLS-level obfuscation~\cite{dac18,8715083}. \noindent{\em {\bf Example:} Let us obfuscate RTL operation {\tt c = a + b} with a dummy subtraction. We generate a key bit {\tt k\_o = 1'b0} and rewrite the RTL as {\tt c = k\_o ? a - b : a + b}. The original function is selected for the correct {\tt k\_o}.}\hfill$\Box$ The ternary operator is a simple representation of the multiplexer, but it may impact code coverage. It introduces extra branches in the circuit, where one of the paths is never activated once the key is provided. To keep the same coverage as the original design, we rewrite the mux selection as {\tt o = in1 \& k | in2 \& $\mathtt{\sim}$k}. \noindent {\em {\bf Example:} Operation {\tt c = a + b} obfuscated as {\tt c = k\_o ? a - b : a + b} can be written as {\tt c = (a - b)\&\{8\{k\_o\}\} | (a + b)\&\{8\{$\mathtt{\sim}$k\_o}\}\}. This is equivalent to ternary operation without branches, and has the same code coverage.}\hfill$\Box$ Since operations use the same inputs, ASSURE adds a multiplexer at the output with its select connected to the key bits. The multiplexer and the additional operator are area overhead. The multiplexer impacts the critical path and the additional operation introduces a delay when it takes more time than the original one. We create a pool of alternatives for each operation type. Original and dummy operations are ``balanced'' in complexity to avoid increasing the area and the critical path. Dummy operations are selected to avoid structures the attacker can easily unlock. Incrementing a signal by one cannot be obfuscated by a multiplication by one, clearly a fake. Dummy operators are also selected to avoid collisions. For example, adding a constant to a signal cannot be obfuscated with a subtract because the wrong operation key bit can activate the circuit when the attacker provides the two's complement of the constant. {\em\uline{Proof}}. Consider an RTL design with $m$ inputs and $n$ outputs, with a mapping $\mathcal{F} : X \rightarrow Y$, $X \in \{0,1\}^m$ and with $r$ possible sites for operator obfuscation. ASSURE uses multiplexer-based locking $\mathcal{O}$ with an $r$-bit key $\mathcal{K}^*_r$ to lock the design and generate $\mathcal{L}_{\mathcal{K}^*_r}$. \begin{gather} \mathcal{L}_{\mathcal{K}^*_r} = \mathcal{F}(X,k_1,k_2,..,k_r) \nonumber\\ = \overline{k_1}\mathcal{F}(X,0,k_2,..,k_r) + k_1 \mathcal{F}(X,1,k_2,..,k_r) \nonumber\\ = {\mathcal{K}^1_r}\underbrace{\mathcal{F}(X,K=\mathcal{K}^1_r)}_{\mathcal{F}_{K_1}} + {\mathcal{K}^2_r}\underbrace{\mathcal{F}(X,K=\mathcal{K}^2_r)}_{\mathcal{F}_{K_2}} + .. \nonumber\\ .. + \mathcal{K}^{2^r}_r\underbrace{\mathcal{F}(X,K = \mathcal{K}^{2^r}_r)}_{\mathcal{F}_{K_{2^r}}} \end{gather} where, $\mathcal{F}_{K^*_r}(X) = \mathcal{L}_{\mathcal{K}^*_r}(X,K=\mathcal{K}^*_r)$ ($\mathcal{K}^*_r$ is the $r$-bit key). Each location of operator obfuscation applies output of different operations (one original and another fake) to a multiplexer. The following equation holds true for operator obfuscation. \begin{gather} \mathcal{F}(X,k_1,..,k_i=0,..,k_r) \neq \mathcal{F}(X,k_1,..,k_i=1,..,k_r) \nonumber\\ \forall i \in [1,r] \label{eq7} \end{gather} Secondly, the sites of operation obfuscation are different. The output of multiplexer using any key-bit value at one location is independent of the choice made elsewhere. Given a key $K$, the unlocked function of two circuits will be different if we set same logic value at two different key-bit locations. For an example $K=1101$, if one chooses bit location 2 and 4 and flip them, i.e. $K_1 = 1001, K_2=1100$, then $F_{K_1} \neq F_{K_2}$. \begin{gather} \mathcal{F}(X,k_1,..,k_i=\overline{k_i},..,k_r) \neq \mathcal{F}(X,k_1,..,k_j=\overline{k_j},..,k_r) \nonumber \\ \forall i,j \in [1,r], i \neq j \label{eq8} \end{gather} \begin{quote} \leftskip =-20pt \rightskip =-20pt \textbf{Claim 1}: Any pair of unlocked circuit $F_{K^1_r}$ and $F_{K^2_r}$ using r-bit keys $K^1_r$ and $K^2_r$ on multiplexer-based obfuscated circuit $\mathcal{L}_{\mathcal{K}^*_r}$ are unique. (Theorem 1) \end{quote} \begin{proof} $\forall K^1_r \neq K^2_r$, $K^1_r, K^2_r \in \{0,1\}^r$ \\ $\implies$ Hamming distance $(K_1,K_2) \in [1,r]$. \\ $\implies$ Eq.~\ref{eq7} + Eq.~\ref{eq8}, $F_{K_1} \neq F_{K_2}$ \end{proof} \begin{quote} \leftskip =-20pt \rightskip =-20pt \textbf{Claim 2}: MUX-based obfuscation with r-bit key $K$ can be generated from $r$ different locations having $2^r$ operations with equal probability, i.e. following condition holds true. \begin{gather*} P[\mathcal{L}_{\mathcal{K}_r} | \mathcal{O}(\mathcal{F}(X), K^*_r)] = P[\mathcal{L}_{\mathcal{K}_r} | \mathcal{O}(\mathcal{F}(X), K^i_r)] \\ \forall K^i_r \neq K^*_r ; F_{K^i_r} \neq F_{K^*_r}; i \in [1,2^r] \end{gather*} \end{quote} \begin{proof} The probability of choosing $K_r$ is uniform. Therefore, \\ P[K = $K^*_r$] = P[K = $K^i_r$], $\forall K^i_r \neq K^*_r$ \\ $\implies P[\mathcal{L}_{\mathcal{K}_r}(X, K = \mathcal{K}^*_r]) = P[\mathcal{L}_{\mathcal{K}_r}(X,K = \mathcal{K}^i_r)]$ \\ $\implies P[\mathcal{F}_{\mathcal{K}^*_r}] = P[\mathcal{F}_{\mathcal{K}^i_r}] = \frac{1}{2^r}$. \end{proof} Claims 1 and 2 show that operator obfuscation can generate indistinguishable netlists. In Fig.~\ref{fig:opObfuscation_eg}, we demonstrate area overhead of the two benchmark circuits \texttt{DES3} and \texttt{RSA} for operator obfuscation supporting our claims generate indistinguishable circuits. We consider a single operation from each benchmark: addition of \textit{auxiliary input} and \texttt{round\_output} from \texttt{DES3}, and subtraction of \texttt{modulus\_m1\_len} from a constant value in \texttt{RSA}. We generate different circuits by replacing the original operators with other operators. After synthesis, area overhead of these variants (Fig.~\ref{fig:opObfuscation_eg}) are unique and can be reverse engineered. On the contrary, the area overhead of synthesized circuits remain the same after obfuscation and so the obfuscated circuits reveals nothing about the original operator. \subsubsection{Branch Obfuscation}\label{sec:branch_obf} To hide which branch is taken after the evaluation of an RTL condition, we obfuscate the test with a key bit as {\tt cond\_res xor k\_b}, as shown in Fig.~\ref{fig:branch_obfuscation}. To maintain semantic equivalence, we negate the condition to reproduce the correct control flow when {\tt k\_b = 1'b1} because the XOR gate inverts the value of {\tt cond\_res}. We apply De Morgan's law to propagate the negation to disguise the identification of the correct condition. {\em\uline{The resulting predicate is {\em hardware-opaque} because the designer knows which branch is taken but this is unknown without the correct key bit}}. {\noindent\em {\bf Example:} Let {\tt a > b} be the RTL condition to obfuscate with key {\tt k\_b = 1'b1}. We rewrite the condition as {\tt(a <= b)$\wedge$k\_b}, which is equivalent to the original one only for the correct key bit. The attacker has no additional information to infer if the original condition is {\tt >} or {\tt <=}.}\hfill$\Box$ Obfuscating a branch introduces a 1-bit XOR gate, so the area and delay effects are minimal. Similar to constant obfuscation, branch obfuscation is applied only when relevant. For example, we do not obfuscate reset and update processes. We apply the same technique to ternary operators. When these operators are RTL multiplexers, this technique thwarts the data propagation between the inputs and the output. The multiplexer propagates the correct value with the correct key. {\em\uline{Proof}}. For an $m$ input RTL design, we have a control-flow graph (CFG) $G(V,E)$ having $|V|$ nodes and $|E|$ edges. We do a depth-first-traversal of the CFG and order the $r$ conditional nodes in the way they are visited. Let the ordered set of conditional nodes be $V_{CN} = \{v_1,v_2,...v_r\}, V_{CN} \subset V$ ($r = |V_{CN}|$). ASSURE applies XOR-based branch obfuscation to $V_{CN}$ with $r$-bit key $\mathcal{K}^*_r$ as the logic locking scheme $\mathcal{O}$ and generates a locked design $\mathcal{C}_{\mathcal{K}^*_r}$. For example, if $V_{CN} = \{v_1,v_2,v_3,v_4\}$ and $K = 1101$, then $\mathcal{L}(V_{CN}) = \{\overline{v_1},\overline{v_2},v_3,\overline{v_4}\}$. The locked design, post branch-obfuscation is illustrated as follows. \begin{gather} \mathcal{L}_{\mathcal{K}^*_r}(G(V,E),K)= \mathcal{O}(G(V,E),K^*_r) = \nonumber \\ G(\mathcal{O}(V_{CN},K^*_r)\cup (V \setminus V_{CN}),E) = \nonumber \\ G((V_{CN} \oplus K^*_r)\cup (V \setminus V_{CN}),E) \end{gather} where $G(V, E) = \mathcal{L}_{\mathcal{K}^*_r}(G(V,E),K = \mathcal{K}^*_r)$. \begin{table*}[t] \caption{Characteristics of the input RTL benchmarks.}\label{tab:benchmarks} \scriptsize \vspace{-6pt} \begin{tabularx}{\linewidth}{@{}L{1.4cm}@{} L{1.5cm}@{} @{}R{1cm} || @{}R{0.9cm}@{} @{}R{0.9cm}@{} @{}R{1.2cm} | @{}R{1.1cm} || R{1.2cm}@{} R{1.2cm}@{} R{1.2cm}@{} R{1.1cm}@{} R{1.1cm} | R{1.4cm}@{} R{1.4cm}@{}} \toprule {\bf Suite} & {\bf Design} & {\bf Modules} & {\bf Const} & {\bf Ops} & {\bf Branches} & {\bf Tot Bits} & {\bf Comb cells} & {\bf Seq cells} & {\bf Buf cells} & {\bf Inv cells} & {\bf \# nets} & {\bf Area ($\mu m^2$)} & {\bf Delay ($ns$)}\\ \midrule \multirow{9}{*}{CEP} & {\tt AES} & 657 & 102,403 & 429 & 1 & 819,726 & 127,667 & 8,502 & 506 & 21,812 & 136,493 & 42,854.69 & 136.75\\ & {\tt DES3} & 11 & 4 & 3 & 775 & 898 & 2,076 & 135 & 128 & 368 & 2,448 & 736.96 & 192.28\\ & {\tt DFT} & 211 & 447 & 151 & 132 & 8,697 & 118,201 & 38,521 & 9,552 & 41,320 & 158,807 & 81,865.94 & 336.72\\ & {\tt FIR} & 5 & 10 & 24 & 0 & 344 & 820 & 439 & 49 & 225 & 1,704 & 1,129.36 & 377.76\\ & {\tt IDFT} & 211 & 447 & 151 & 132 & 8,697 & 118,154 & 38,525 & 9,576 & 41,305 & 158,722 & 81,821.90 & 333.59\\ & {\tt IIR} & 5 & 19 & 43 & 0 & 651 & 1,378 & 648 & 72 & 367 & 2,621 & 1,679.72 & 464.82\\ & {\tt MD5} & 2 & 150 & 50 & 1 & 4,533 & 4,682 & 269 & 168 & 923 & 5,756 & 1,840.15 & 791.53\\ & {\tt RSA} & 15 & 243 & 35 & 13 & 1,942 & 222,026 & 57,987 & 21,808 & 66,088 & 280,222 & 134,907.05 & 386.55\\ & {\tt SHA256} & 3 & 159 & 36 & 2 & 4,992 & 5,574 & 1,040 & 243 & 1,024 & 7,532 & 3,201.07 & 440.67\\ \midrule \multirow{5}{*}{IWLS} & {\tt MEM\_CTRL} & 27 & 492 & 442 & 160 & 2,096 & 4,007 & 1,051 & 120 & 1,136 & 5,183 & 2,373.35 & 260.72 \\ & {\tt SASC} & 3 & 35 & 27 & 17 & 126 & 367 & 116 & 0 & 125 & 500 & 238.24 & 84.40 \\ & {\tt SIMPLE\_SPI } & 3 & 55 & 34 & 15 & 288 & 476 & 130 & 2 & 145 & 623 & 282.57 & 119.42\\ & {\tt SS\_PCM} & 1 & 5 & 10 & 3 & 24 & 231 & 87 & 1 & 94 & 338 & 168.29 & 90.51\\ & {\tt USB\_PHY} & 3 & 67 & 70 & 34 & 223 & 287 & 98 & 0 & 85 & 401 & 194.15 & 71.91\\ \midrule \multirow{3}{*}{OpenCores} & {\tt ETHMAC} & 66 & 487 & 1,217 & 218 & 3,849 & 34,783 & 10,545 & 2,195 & 12,021 & 45,441 & 22,453.76 & 190.44 \\ & {\tt I2C\_SLAVE} & 4 & 104 & 14 & 11 & 269 & 466 & 125 & 0 & 126 & 596 & 160.28 & 125.44\\ & {\tt VGA\_LCD} & 16 & 123 & 310 & 56 & 885 & 54,614 & 17,052 & 4,921 & 19,228 & 71,766 & 36,095.90 & 224.67\\ \midrule \multirow{3}{*}{OpenROAD} & {\tt ARIANE\_ID} & 4 & 3,498 & 385 & 723 & 4,606 & 1,993 & 378 & 96 & 559 & 2,615 & 980.97 & 225.48\\ & {\tt GCD} & 11 & 15 & 4 & 12 & 496 & 168 & 34 & 3 & 32 & 253 & 100.91 & 161.87\\ & {\tt IBEX} & 15 & 14,740 & 5,815 & 6,330 & 26,885 & 12,161 & 1,864 & 978 & 2,965 & 14,379 & 5,758.84 & 538.10\\ \bottomrule \end{tabularx} \end{table*} \begin{quote} \leftskip =-20pt \rightskip =-20pt \textbf{Claim 1}: The unlocked CFGs $\mathcal{L}_{\mathcal{K}^*_r}(G(V,E), K_1)$ and $\mathcal{L}_{\mathcal{K}^*_r}(G(V,E), K_2$ using $r$-bit keys $K_1$ and $K_2$, respectively, on the XOR-based encrypted CFG $\mathcal{L}_{\mathcal{K}^*_r}(G(V,E),K)$ are unique. \end{quote} \begin{proof} $\forall K_1 \neq K_2$, $K_1, K_2 \in \{0,1\}^r$ \\ $\implies K_1 \oplus V_{CN} \neq K_2 \oplus V_{CN}$ $\implies V^1_{CN} \neq V^2_{K_2}$. \\ $\implies G(V^1_{CN},E) \neq G(V^2_{CN},E)$. \end{proof} \begin{quote} \leftskip =-20pt \rightskip =-20pt \textbf{Claim 2}: The obfuscated CFG $\mathcal{L}_{\mathcal{K}^*_r}(G(V,E),K)$ can be generated from $2^r$ possible combination of condition statuses with equal probability, i.e. the following condition holds true. \begin{gather} P[\mathcal{L}_{\mathcal{K}'_r}(G(V,E),K) | G((V_{CN} \oplus K^*_r) \cup (V \setminus V_{CN}),E)] = \nonumber\\ P[\mathcal{L}_{\mathcal{K}'_r}(G(V,E),K) | G((V_{CN} \oplus K*_r) \cup (V \setminus V_{CN}),E)] \nonumber \\ \forall K_r \neq K^*_r ; V^r_{CN} \neq V_{CN} \end{gather} \end{quote} \begin{proof} The probability of choosing $K_r$ is uniform. So, \\ $P[K = \mathcal{K}^*_r] = P[K = \mathcal{K}_r$], $\forall \mathcal{K}_r \neq \mathcal{K}^*_r, \mathcal{K}_r \in 2^r$ \\ $\implies P[(V_{CN}\oplus \mathcal{K}^*_r) \oplus \mathcal{K}^*_r] = P[(V_{CN}\oplus \mathcal{K}^*_r) \oplus \mathcal{K}_r]$ \\ $\implies P[V_{CN}] = P[V^r_{CN}],V_{CN} \neq V^r_{CN},$ \\ $V^r_{CN} = \{p_1,p_2,..,p_i,..,p_r\}$, where $p_i \in \{v_i,\overline{v_i}\}$. \end{proof} Combining claims 1 and 2 shows that the encrypted CFGs are indistinguishable for a family of $2^r$ possible designs. In Fig.~\ref{fig:branchObfuscation_eg}, we report the area overhead of the two benchmark circuits \texttt{DES3} and \texttt{RSA} in case of branch obfuscation showing empirical evidence of our claim that obfuscated circuits are indistinguishable. We identify five conditions from each benchmark and generated five different variants, flipping each condition at a time. After synthesizing the circuits, we observed that area overhead is uniquely mapped to each variant of the design. The conditions in the CFG can be easily reverse engineered from the synthesized circuit and the flow of design can be unlocked. On the contrary, the area overhead of synthesized circuits remain the same after obfuscation, indicating the obfuscated circuits reveal no information about the control-flow of the circuit. \section{Experimental Validation of ASSURE} \subsection{Experimental Setup} We implemented ASSURE as a Verilog$\rightarrow$Verilog tool that leverages Pyverilog~\cite{Takamaeda:2015:ARC:Pyverilog}, a Python-based hardware design processing toolkit to manipulate RTL Verilog. Pyverilog parses the input Verilog descriptions and creates the design AST. ASSURE then manipulates the AST. Pyverilog then reproduces the output Verilog description ready for logic synthesis. \begin{figure*} \includegraphics[width=\textwidth]{graphs/visibility-a} \includegraphics[width=\textwidth]{graphs/visibility-b} \includegraphics[width=\textwidth]{graphs/visibility-c} \includegraphics[width=\textwidth]{graphs/visibility-d} \caption{Verification failure metric in \textsc{KEY-EFFECT} experiments.} \label{fig:visibility_results} \end{figure*} We used ASSURE to protect several Verilog designs from different sources\footnote{Supporting VHDL and SystemVerilog only requires proper HDL parsers.}: the MIT-LL Common Evaluation Platform (CEP) platform~\cite{cep}, the OpenROAD project~\cite{openroad_dac2019}, and the OpenCores repository~\cite{opencores}. Four CEP benchmarks ({\tt DCT}, {\tt IDCT}, {\tt FIR}, {\tt IIR}) are created with Spiral, a hardware generator~\cite{Pueschel:11}). Table~\ref{tab:benchmarks} shows the characteristics of these benchmarks in terms of number of hardware modules, constants, operations, and branches. This data also characterizes the functionality that needs obfuscation. The benchmarks are much larger than those used by the gate-level logic locking experiments by the community~\cite{llcarxiv}. Differently from~\cite{dac18}, ASSURE does not require any modifications to synthesis tools and applies to pre-existing industrial designs, processing the Verilog RTL descriptions with no modifications. We analyzed the ASSURE in terms of security (Section~\ref{sec:security} and Section~\ref{sec:attacks}) and overhead (Section~\ref{sec:cost}). For each benchmark, we created obfuscated variants using all techniques ({\tt ALL}) or one of constant ({\tt CONST}), operation {\tt (OP)}, and branch {\tt (BRANCH)} obfuscations. We repeat experiments by constraining the number of key bits available: 25\%, 50\%, 75\% or 100\% and reported in Table~\ref{tab:benchmarks}. The resulting design is then identified by a combination of its name, the configuration, and the number of key bits. For example, {\tt DFT-ALL-25} indicates obfuscation of the {\tt DFT} benchmark, where all three obfuscations are applied using 2,175 bits for obfuscation (25\% of 8,697) as follows: 38 for operations (25\% of 151), 33 for branches (25\% of 132) and the rest (2,104) for constants. \subsection{Correctness and Key Effects}\label{sec:security} We first apply formal verification on the locked design against the unprotected design with a twofold goal. First, we show that, when the correct key $\mathcal{K}^*_r$ is used, the unlocked circuit matches the original. We label this experiment as \textsc{correctness}. Second, we show that flipping each single key bit induces at least a failing point (i.e., no {\em collision}). This experiment demonstrates that each key bit has an effect on the functionality of the circuit. We label this experiment as \textsc{key effect}. We show no other key can activate the same IC, i.e., all other circuits ($K_r \neq K^*_r$) are not exact copies of the original designs. In this experiment, we also aim at quantifying how the obfuscation techniques affect the IC functionality when the attacker provides incorrect keys. With formal verification, we focus on IC functionality rather than IC results. We compute the {\em verification failure} metric as: \begin{equation} F = \frac{1}{K}\cdot\sum^{K}_{i=1}\frac{n(FailingPoints)_i}{n(TotalPoints)} \end{equation} This metric is the average fraction of verification points that do not match when testing with different wrong keys. We experimented using Synopsys Formality N-2017.09-SP3. \subsubsection{Correctness} We apply ASSURE several times, each time with a random key to obfuscate operations and branches (constants are always extracted in the same way. We formally verified these designs against the original ones. In all experiments, {\em\uline{ASSURE generates circuits that match the original design when using the correct key}}. \subsubsection{Key Effect} Given a design obfuscated with an $r$-bit key, we performed $r$ experiments where in each of them we flipped only one key bit with respect to the correct key. In all cases, {\em\uline{formal verification identifies at least one failing point, showing that an incorrect key always alters the circuit functionality}}. Varying the locking key has no effect since the failure is induced by the flipped bit (from correct to incorrect) and not its value. Fig.~\ref{fig:visibility_results} shows the verification failure metrics for each experiment. Results are not reported for {\tt FIR-BRANCH-*} and {\tt IIR-BRANCH-*} because they have no branches. {\tt AES}, {\tt DFT}, {\tt IDFT}, and {\tt OPENCORES-ETHMAC} benchmarks have low values ($\sim$10$^{-5}$) since they have many verification points and only a small part is failing. Operations and constants vitally impact the design as obfuscating them induces more failing points. Increasing the number of obfuscated operations reduces the metric. Since obfuscation is performed using a depth-first analysis, the first bits correspond to operations closer to the inputs. As the analysis proceeds, obfuscation is closer to the output and more internal points match. \begin{figure} \centering \includegraphics[height=3.2cm]{graphs/des3_rsa_combinedConstant.pdf} \caption{Area of original and obfuscated variants of \texttt{DES3} and \texttt{RSA} when synthesized with different constants ($c1-c5$).} \label{fig:constantExtraction} \end{figure} This experiment allowed us to identify design practices that lead to inefficient obfuscations or even collisions. In {\tt DFT}, one-bit signals were initialized with integer values 0/1. Verilog allows this syntax and signals are trimmed by logic synthesis. A naive RTL constant analysis would pick 32 bits for obfuscating a single-bit. Since only the least significant bit impacts the circuit function, flipping the other 31 bits would lead to a collision. So, we extended ASSURE AST analysis to match the constant sizes with those of the target signals. \begin{figure}[t] \centering \includegraphics[height=3.2cm]{graphs/des3_rsa_combinedOperator.pdf} \caption{Area of original and obfuscated variants of benchmarks \texttt{DES3} and \texttt{RSA} using different operators in the statement.} \label{fig:opObfuscation_eg} \end{figure} \input{table_attacks} \subsection{Resilience Against Locking Attacks}\label{sec:attacks} We outlined provable security guarantees that $n$ obfuscation bits induce $2^n$ RTL designs with uniform probability. We now discuss resilience to known locking attacks. \subsubsection{Resynthesis Attacks}\label{sec:resynthesis} Massad \textit{et al.}~\cite{DBLP:journals/corr/MassadZGT17} showed that greedy heuristics can recover the key of an obfuscated gate-level netlist. Performing re-synthesis with an incorrect key may trigger additional optimizations that produce large redundancy in the circuit. Similarly, Li \textit{et al.}~\cite{8714955} propose an attack using concepts from VLSI testing. Incorrect key results in large logic redundancy and most of stuck-at faults become untestable. A correctly unlocked circuit, however, has high testability. ASSURE obfuscates RTL design before synthesis. Since the obfuscated RTL is equally likely to be generated from $2^n$ designs, logic synthesis using different keys on a reverse-engineered obfuscated netlist reveals no information about the original netlist. Hence, the area overhead for the correct and incorrect keys are in same range (see Figs.~\ref{fig:constantExtraction}, \ref{fig:opObfuscation_eg} and \ref{fig:branchObfuscation_eg}). \begin{figure} \centering \includegraphics[height=3.2cm]{graphs/des3_rsa_combinedBranch.pdf} \caption{Area of original and obfuscated variants of benchmarks \texttt{DES3} and \texttt{RSA} in case of different CFG flows.} \label{fig:branchObfuscation_eg} \end{figure} \subsubsection{ML-guided Attacks}\label{sec:mlguided_attacks} Chakraborty \textit{et al.}~\cite{sail,surf} proposed oracle-less attacks on logic obfuscation based on the idea that obfuscation techniques insert XOR/XNOR gates that leave structural traces. The key gates are inserted before synthesis with known technology library and synthesis process (algorithms and tools). Since the effect of logic optimizations are local and the optimization rules are deterministic, one can recover the original function by launching an ML-guided removal attack on the obfuscated RTL design. In ASSURE, the obfuscation logic does not depend solely on the insertion of XOR/XNOR gates. For example, in branch obfuscation, we perform also logic inversion of the condition instead of simply adding a XOR gate followed by a NOT when the corresponding key bit is $1$. Recovering the original RTL from obfuscated RTL is hard (see claim 2 of ASSURE branch obfuscation proof in Section~\ref{sec:branch_obf}). Also, recovering extracted constants from an obfuscated design is impossible since the obfuscated circuit does not contain any information on the constant value. \subsubsection{Redundancy and KC2 Attacks}\label{sec:other_attacks} We analyze the strength of ASSURE's obfuscation by running oracle-less redundancy attacks~\cite{8714955}. Redundancy attacks decipher the key bits by identifying redundant lines in the synthesized netlist with incorrect key bits. KC2 is an improved version of SAT-based attacks incrementally unrolling a sequential circuit to recover the key. Even if ASSURE is not designed to protect against oracle-guided attacks, we evaluated its performance on KC2~\cite{neos}, a popular oracle-guided attack. We have run both attacks with a timeout of 96 hours and 50~GB of memory for each attack run. Table~\ref{tab2:attacksOnAssure} summarizes the results of both attacks on selected ASSURE obfuscated designs. In particular, we apply the attacks to benchmarks that we can safely convert into the format required by the attack tools. We perform the attacks after applying all obfuscations ({\tt ALL}) or after applying only constant obfuscation ({\tt Constant}). Constant obfuscation successfully thwarts all redundancy attacks showing this is the most powerful obfuscation. Indeed, on benchmarks like {\tt DES3}, {\tt FIR}, {\tt SS\_PCM}, and {\tt USB\_PHY}, redundancy attacks recovered some key bits. These results indicate that combining different obfuscation techniques is not 100\% secure compared to stand-alone obfuscation. Even if we focused on the netlist-only threat model, it is interesting to evaluate the effects of oracle-guided attacks. KC2 attacks were able to recover the correct keys only for {\tt DES3} and {\tt SS\_PCM} benchmarks. In all other cases, KC2 claimed to recover certain key bits. However, the equivalence checking performed by ABC within the tool showed the functionality unlocked with those bits is not equivalent with the original one, i.e. the key is incorrect. \begin{figure*} \centering \includegraphics[width=\textwidth]{graphs/area-16-20} \includegraphics[width=\textwidth]{graphs/area-11-15} \includegraphics[width=\textwidth]{graphs/area-6-10} \includegraphics[width=\textwidth]{graphs/area-1-5} \caption{\vspace{-4pt}Area overhead for ASSURE obfuscation. Benchmarks are presented in increasing order of total overhead.} \label{fig:area_overhead_key_bit} \end{figure*} \begin{figure*} \centering \includegraphics[width=0.98\columnwidth]{graphs/key-11-20} \hfill \includegraphics[width=0.98\columnwidth]{graphs/key-1-10} \vspace{-4pt}\caption{Area overhead per key bit for ASSURE obfuscation. Benchmarks are presented in increasing order of total overhead.} \label{fig:area_overhead} \end{figure*} \begin{figure*} \centering \includegraphics[width=\textwidth]{graphs/timing-16-20} \includegraphics[width=\textwidth]{graphs/timing-11-15} \includegraphics[width=\textwidth]{graphs/timing-6-10} \includegraphics[width=\textwidth]{graphs/timing-1-5} \caption{ \vspace{-4pt}Timing overhead for ASSURE obfuscation. Benchmarks are presented in increasing order of total overhead.} \label{fig:timing_overhead} \end{figure*} \subsection{Synthesis Overhead}\label{sec:cost} We did logic synthesis using the Synopsys Design Compiler J-2018.04-SP5 targeting the Nangate 15nm ASIC technology at standard operating conditions ($25^{\degree}$C). We evaluated the area overhead and critical-path delay degradation relative to the original design. While our goal is to protect the IP functionality and not to optimize the resources, designs with lower cost are preferred. {\em\uline{ASSURE generates correct designs with no combinational loops}}. Constant obfuscation extracts the values that are used as the key and no extra logic. Operation obfuscation multiplexes results of original and dummy operations. Branch obfuscation adds XOR to the conditions. \subsubsection{Area overhead}\label{sec:area_cost} Table~\ref{tab:benchmarks} reports the results of the original design -- the number of cells in the netlists, the area (in $\mu m^2$) and the critical-path delay (in $ns$). Fig.~\ref{fig:area_overhead} reports the area overhead of all obfuscations with respect to the original designs. The three techniques are independent and so, {\tt ALL} results are the aggregate of the three techniques. Constant obfuscation produces an average overhead in the range 18\% ({\tt *-CONST-25}) to 80\% ({\tt *-CONST-100}). The maximum overhead is about 450\% for {\tt AES-CONST-100}, which has the most number obfuscated constants. {\em\uline{ASSURE removes hard-coded constants from the circuit, preventing logic optimizations like constant propagation}}. In {\tt AES}, all S-Box modules are optimized as logic in the original circuit. This optimization is not possible anymore when the constants are provided as inputs. However, we showed this obfuscation provides maximum protection since the constants are semantically removed from the circuit. The average operation obfuscation overhead is in the range 9\% ({\tt *-OP-25}) to 25\% ({\tt *-OP-100}). {\tt IBEX-OP-100} has the maximum overhead of 155\% since it has the most operations. Branch obfuscation produces a smaller average overhead, in the range 6\% ({\tt *-BRANCH-25}) to 14\% ({\tt *-BRANCH-100}) with a maximum overhead of 113\% for {\tt DES-BRANCH-100}. This benchmark has the largest proportion of branches relative to other elements. {\tt MD5} results in savings ($\sim$4\%) when we apply branch obfuscation ({\tt MD5-BRANCH-*}). The branch conditions help pick elements from the library that lower area overhead. The real impact of ASSURE depends on how many elements are obfuscated in each configuration. So, we computed the {\em area overhead per key bit} as the area overhead of a configuration divided by the number of key bits used for its obfuscation and report it in Fig.~\ref{fig:area_overhead_key_bit}. In most cases, {\em\uline{operation obfuscation has the largest impact, followed by branches and then constants}}. This impact is larger for data-intensive benchmarks, like CEP filters ({\tt DFT}, {\tt IDFT}, {\tt FIR}, and {\tt IIR}). Constants usually require more obfuscation bits, so the impact per bit is smaller. Each obfuscated operation introduces a new functional unit and multiplexer per key bit. {\tt MD5} has a large negative impact when obfuscating the branches justifying the area reduction when we apply only branch obfuscation ({\tt MD5-BRANCH-*}). On the contrary, even if {\tt AES} was the benchmark with the largest overhead (and many more bits), its overhead per key bit is comparable with the others. We repeated the experiments several times and we observed minimal variants with different locking keys. To conclude {\em\uline{the area overhead is related to the design characteristics and to the number of key bits}}. The former determine the impact of ASSURE, while the latter determine the total amount of overhead. {\em\uline{The overhead depends on the design, the techniques, and the number of key bits and not on the values of the locking key}}. \subsubsection{Timing overhead}\label{sec:timing_cost} Fig.~\ref{fig:timing_overhead} shows the overhead introduced by the ASSURE obfuscation logic on the critical path when targeting area optimization. {\em\uline{Timing overhead is application dependent with similar results across the different techniques. The overhead is larger when the obfuscated elements are on the critical path}}. This is relevant in data-intensive (with many operations) and control-intensive (with control branches on critical path) designs. In most benchmarks, the timing overhead is $<$20\%. Constants have a positive impact on the overhead (see {\tt AES} and {\tt DES3}). The obfuscated designs can generally achieve the same performance as the original ones, limiting the impact on the IC design flow. \section{Discussion and Concluding Remarks}\label{sec:discussion} We presented ASSURE, an RTL locking framework against an {\em\uline{untrusted foundry that has no access to an unlocked functional chip}}. ASSURE operates on the Verilog RTL description and is fully compatible with industrial EDA flows. We discuss the major contributions in the form of Q\&A. \noindent $\blacktriangleright$ {\bf Which threat model are you considering? How is it relevant for my design?} We consider the netlist-only threat model where the attacker has no access to an activated chip. This model is relevant especially for an untrusted foundry with low-volume IC production. \noindent $\blacktriangleright$ {\bf Why should I use an RTL approach instead of existing gate-level techniques?} ASSURE hides the essential semantics (constants, operations, and control-flow branches) in a way that is {\em\uline{indistinguishible and provably secure against attackers with no prior knowledge of the IP function}}. Most of the semantic information (e.g., constants) cannot be protected at the gate level because synthesis tools embed it into the netlist. \noindent $\blacktriangleright$ {\bf Is ASSURE secure?} In our experimental analysis with formal verification and logic synthesis EDA tools, we show the {\em\uline{circuits can be unlocked only with the correct key}} and {\em\uline{obfuscating the design closer to the inputs induces more verification failures}}. Also, {\em\uline{ASSURE can thwart oracle-less attacks that can recover key bits even in case of SAT-resilient protections}}, showing the two approaches must be combined. \noindent $\blacktriangleright$ {\bf What is the overhead?} ASSURE obfuscations introduce {\em\uline{area overhead that depends on the obfuscation techniques and is proportional to the number of key bits}}. In case of constants, obfuscation prevent logic optimizations, like constant propagation, while {\em\uline{operation obfuscation has the largest overhead per key bit}}. The {\em\uline{key values have no impact on the obfuscation results}}. ASSURE has no impact on the clock cycles but only on the critical path delay in a way that depends on where the obfuscation is applied. The designers can use these guidelines to apply obfuscation on their design. \section*{Acknowledments} The authors would like to thank Benjamin Tan (NYU) and Jitendra Bhandari (NYU) for their support in implementing locking attacks. The research is supported in part by NSF Award (\# 1526405), ONR Award (\# N00014-18-1-2058), NSF CAREER Award (\# 1553419), the NYU Center for Cybersecurity (\url{cyber.nyu.edu}), and the NYUAD Center for Cybersecurity (\url{sites.nyuad.nyu.edu/ccs-ad}). \bibliographystyle{IEEEtran}
{'timestamp': '2021-04-20T02:25:27', 'yymm': '2010', 'arxiv_id': '2010.05344', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05344'}
arxiv
\section{Introduction} Disentangling aims to factorize an entity, like a feature vector, into several interpretable components, so that the behavior of a learning model can be better understood. In recent years, many approaches have been proposed towards tackling disentangling in deep neural networks and have achieved promising results. Most prior efforts, however, have been focused on the disentanglement of convolutional neural network~(CNN) especially the auto-encoder architecture, where disentangling takes place during the stage of latent feature generation. {For example, VAE~\citep{kingma2013autovae} restrains the distribution of the latent features to Gaussian and generates disentangled representation; $\beta$-VAE~\citep{higgins2017betaVAE} further improves the disentangling by introducing $\beta$ to balance the independence constraints and reconstruction accuracy.} Despite the many prior efforts in CNN disentangling, there are few endeavors toward disentangling in the irregular structural domain, where graph convolutional network~(GCN) models are applied. Meanwhile, the inherent differences between grid-like data and structural data precludes applying CNN-based disentangling methods to GCN ones. The works of~\citep{ma2019disentangled,liu2019independence}, as pioneering attempts, focus on the node-level neighbour partition and ignore the latent multi-relations among nodes. We introduce in this paper a novel GCN, that aims to explicitly conduct graph-level disentangling, based on which convolutional features are aggregated. Our approach, termed as \emph{factorizable graph convolutional network}~(FactorGCN), takes as input a \emph{simple graph}, and decomposes it into several factor graphs, each of which corresponds to a disentangled and interpretable relation space, as shown in Fig.~\ref{fig:factorlayer}. Each such graph then undergoes a GCN, tailored to aggregate features only from one disentangled latent space, followed by a merging operation that concatenates all derived features from disentangled spaces, so as to produce the final block-wise interpretable features. These steps constitute one layer of the proposed FactorGCN. As the output graph with updated features share the identical topology as input, nothing prevents us from stacking a number of layers to disentangle the input data at different levels, yielding a hierarchical disentanglement with various numbers of factor graph at different levels. FactorGCN, therefore, potentially finds application in a wide spectrum of scenarios. In many real-world graphs, multiple heterogeneous relations between nodes are mixed and collapsed to one single edge. In the case of social networks, two people may be \emph{friends}, \emph{colleagues}, and \emph{living in the same city} simultaneously, but linked via one single edge that omits such interconnections; in the co-purchasing scenario~\citep{co-purchase}, products are bought together for different reasons like \emph{promotion}, and \emph{functional complementary}, but are often ignored in the graph construction. FactorGCN would, in these cases, deliver a disentangled and interpretable solution towards explaining the underlying rationale, and provide discriminant learned features for the target task. \iffalse multiple relations may exist between two person, like friend, colleague, neighbor, and family. However, these relations may mixed up when constructing the graph by only considering whether them are connected. Another example is the co-purchase graph~\citep{co-purchase}, where products can be purchased together with different reasons, like promotion, advertisement, and functional complementary. These reasons cannot be detected when constructing the graph by consider whether they are bought together frequently. \fi \iffalse Many methods have been proposed to solve the problem of disentanglement. Most of these methods are based on the architecture of auto-encoder, where the disentanglement is happened during the generation of the latent features. For example, $\beta-$VAE~\citep{higgins2017betaVAE} improves the disentanglement performance of the original VAE by introducing a weight in the distribution constrain item. Using a $\bata$ more than one will enforce the auto-encoder to learn a more efficient latent representation and disentangle in an unsupervised manner. Although there are many pioneers focus on the disentanglement of CNN models, there are few works that discover the disentangling in the structural domain, where GCN models are applied. The inherent differences between grid-like data and structural data make the disentanglement on GCN difficult. One of the challenges is that the meaning of the disentangled features of a GCN model are hard to explain. In the field of image or audio, different dimensions of the disentangled features can represent a special aspect of the input data, like size of object or tone of the audio. However, in structural domain, it is hard to say what is one dimension of the node's feature represents. The exist methods~\citep{ma2019disentangled,liu2019independence} all focus on grouping the neighbours of the node and fail to capture the latent multi-relations among entities. In this paper, we propose factorized graph convolutional networks~(FactorGCN), a general framework that disentangles the structural input into several factor graphs. Each of these factor graphs represents a relations across all the entities and generates the features of entities independently. Fig.~\ref{fig:factorlayer} shows an example one layer in the FactorGCN model. \fi \begin{figure} \centering \includegraphics[width=0.95\linewidth]{Figs/pipeline.pdf} \caption{Illustration of one layer in the proposed FactorGCN. It contains three steps: \emph{Disentangling}, \emph{Aggregation}, and \emph{Merging}. In the disentangling step, the input graph is decomposed into several factor graphs, each of which represents a latent relation among nodes. In the aggregation step, GCNs are applied separately to the derived factor graphs and produce the latent features. In the merging step, features from all latent graphs are concatenated to form the final features, which are block-wise interpretable.} \label{fig:factorlayer} \end{figure} Specifically, the contributions of FactorGCN are summarized as follows. \begin{itemize} \item {\bf Graph-level Disentangling}. FactorGCN conducts disentangling and produces block-wise interpretable node features by analyzing the whole graph all at once, during which process the global-level topological semantics, such as the higher-order relations between edges and nodes, is explicitly accounted for. The disentangled factor graphs reveal latent-relation specific interconnections between the entities of interests, and yield interpretable features that benefit the downstream tasks. This scheme therefore contrasts to the prior approaches of~\citep{ma2019disentangled,liu2019independence}, where the {disentanglement takes place only within a local neighborhood, without accounting for global contexts}. \item {\bf Multi-relation Disentangling}. Unlike prior methods that decode only a single attribute for a neighboring node, FactorGCN enables multi-relation disentangling, meaning that {the center node may aggregate information from a neighbour under multiple types of relations}. This mechanism is crucial since real-world data may contain various relations among the same pair of entities. In the case of a social network graph, for example, FactorGCN would produce disentangled results allowing for two users to be both \emph{friends} and \emph{living in the same city}; such multi-relation disentangling is not supported by prior GCN methods. \item {\bf Quantitative Evaluation Metric}. Existing quantitative evaluation methods~\citep{eastwood2018framework,burgess2018understanding} in the grid domain rely on generative models, like auto-encoder~\citep{kim2018disentangling} or GAN~\citep{chen2016infogan}. Yet in the irregular domain, unfortunately, state-of-the-art graph generative models are only applicable for generating small graphs or larger ones without features. {Moreover, these models comprise a sequential generation step, making it infeasible to be integrated into the graph disentangling frameworks.} To this end, we propose a graph edit-distance based metric, which bypasses the generation step and estimates the similarity between the factor graphs and the ground truth. \end{itemize} We conducted experiments on five datasets in various domains, and demonstrate that the proposed FactorGCN yields state-of-the-art performances for both disentanglement and downstream tasks. This indicates that, even putting side its disentangling capability, FactorGCN may well serve as a general GCN framework. Specifically, on the ZINC dataset~\citep{jin2018junctionZINC}, FactorGCN outperforms other methods by a large margin, and, without {the bond information of the edges}, FactorGCN achieves a performance on par with the state-of-the-art method that explicitly {utilizes} edge-type information. \iffalse For two of them, ground truhts of the disentangled factor graphs are available; on these two datasets, FactorGCN performs consistently the best in terms of both the disentanglement performance and the downstream task performance. The other three datasets are from social network and bioinformatics graph, on which FactorGCN achieves the state-of-the-art performance, showing that it is ready to be used as a general GCN framework. Specifically, on the ZINC dataset, our method outperforms the other methods by a large margin and achieve a similar performance as the state-of-the-art method that explicitly \emph{utilizes} the type information of edges, indicating that the disentangled factor graphs can indeed boost results of the downstream tasks. \fi \section{Related Work} \textbf{Disentangled representation learning}. Learning disentangled representations has recently emerged as a significant task towards interpretable AI~\citep{yang2020ECCV,Song_2020_CVPR}. Unlike earlier attempts that rely on handcrafted disentangled representations or variables~\citep{WangECCV14,WangTPAMI16}, most of the recent works in disentangled representation learning are based on the architecture of auto-encoder~\citep{higgins2017betaVAE,feng2018dual,bouchacourt2018multi,burgess2018understanding,wang2017tag,kim2018disentangling} or generative model~\citep{chen2016infogan,zhao2017learning,siddharth2017learning}. One mainstream auto-encoder approach is to constrain the latent feature generated from the encoder to make it independent in each dimension. For example, VAE~\citep{kingma2013autovae} constrains the distribution of the latent features to Gaussian; $\beta$-VAE\citep{higgins2017betaVAE} enlarges the weight of the KL divergence term to balance the independence constraints and reconstruction accuracy; \citep{schmidhuber1992learning} disentangles the latent features by ensuring that each block of latent features cannot be predicted from the rest; DSD~\citep{feng2018dual} swaps some of the latent features twice to achieve semi-supervised disentanglement. For the generative model, extra information is introduced during the generation. For example, InfoGAN~\citep{chen2016infogan} adds the class code to the model and maximizes the mutual information between the generated data and the class code. \textbf{Graph convolutional network}. Graph convolutional network~(GCN) has shown its potential in the non-grid domain~\citep{xu2018powerful,Qiu2020ECCV,li2018combinatorial,yang2020distilling,monti2017geometricMoNet,ijcai_spagan}, achieving promising results on various type of structural data, like citation graph~\citep{velickovic2018graphgat}, social graph~\citep{kipf2017semi}, and relational graph~\citep{schlichtkrull2018modeling}. Besides designing GCN to better extract information from non-grid data, there are also a couple of works that explore the disentangled GCNs~\citep{ma2019learning,liu2019independence}. DisenGCN~\citep{ma2019disentangled} adopts neighbour routine to divide the neighbours of the node into several mutually exclusive parts. IPGDN~\citep{liu2019independence} improves DisenGCN by making the different parts of the embedded feature independent. Despite results of the previous works, there remain still several problems: the disentanglement is in the node level, which does not consider the information of the whole graph, and there is no quantitative metrics to evaluate the performance of disentanglement. \section{Method} In this section, we will give a detailed description about the architecture of FactorGCN, whose basic component is the disentangle layer, as shown in Fig.~\ref{fig:factorlayer}. \subsection{{Disentangling Step}} The goal of this step is to factorize the input graph into several factor graphs. To this end, we treat the edges equally across the whole graph. The mechanism we adopt to generate these factorized coefficient is similar to that of graph attention network~\citep{velickovic2018graphgat}. We denote the input of the disentangle layer as $\mathbf{h} = \{h_0, h_1, ..., h_n\}, h_i \in \mathcal{R}^F$ and $\mathbf{e} = \{e_0, e_1, ..., e_m\}, e_k = (h_i, h_j)$. $\mathbf{h}$ denotes the set of nodes with feature of $F$ dimension, and $\mathbf{e}$ denotes the set of edges. The input nodes are transformed to a new space, done by multiplying the features of nodes with a linear transformation matrix $\mathbf{W} \in \mathcal{R}^{F^\prime \times F}$. This is a standard operation in most GCN models, which increases the capacity of the model. The transformed features are then used to generate the factor coefficients as follows \begin{equation} E_{ije} = 1 / \left(1 + e^{-\Psi_e (h^\prime_{i}, h^\prime_{j}) } \right); h^\prime=\mathbf{W} h, \label{eq:1} \end{equation} where $\Psi_{e}$ is the function that takes the features of node $i$ and node $j$ as input and computes the attention score of the edge for factor graph $e$, and takes the form of an one-layer MLP in our implementation; $E_{ije}$ then can be obtained by normalizing the attention score to $[0, 1]$, representing the coefficient of edge from node $i$ to node $j$ in the factor graph $e$; {$h^\prime$ is the transformed node feature, shared across all functions $\Psi_{*}$.} Different from most previous {forms of attention-based GCNs} that normalize the attention coefficients among all the neighbours of nodes, our proposed model generates these coefficients directly {as the factor graph}. Once all the coefficients are computed, a factor graph $e$ can be represented by its own $E_e$, which will be used for the next aggregation step. However, without any other constrain, some of the generated factor graphs may contain a similar structure, degrading the disentanglement performance and capacity of the model. We therefore introduce an additional head in the disentangle layer, aiming to avoid the degradation of the generated factor graphs. The motivation of the additional head is that, a well disentangled factor graph should have enough information to be distinguished from the rest, only based on its structure. {Obtaining the solution that all the disentangled factor graphs differ from each other to the maximal degree, unfortunately, is not trivial.} We thus approximate the solution by giving unique labels to the factor graphs and optimizing the factor graphs as a graph classification problem. Our additional head will serve as a {discriminator, shown in Eq.~\ref{eq:2}}, to distinguish which label a given graph has: \begin{small} \begin{equation} G_e = {\rm Softmax}\Big( f \big({\rm Readout}(\mathcal{A}(\mathbf{E}_{e}, \mathbf{h^\prime}) ) \big) \Big). \label{eq:2} \end{equation} \end{small} The discriminator contains a three-layer graph auto-encoder $\mathcal{A}$, which takes the transformed feature $\mathbf{h^\prime}$ and the generated attention coefficients of factor graph $\mathbf{E}_e$ as inputs, and generates the new node features. These features are then readout to generate the representation of the whole factor graph. Next, the feature vectors will be sent to a classifier with one fully connected layer. Note that all the factor graphs share the same {node features}, making sure that the information discovered by the discriminator only comes from the difference among the structure of the factor graphs. More details about the discriminator architecture can be found in the supplementary materials. The loss used to train the discriminator is taken as follows: \begin{small} \begin{equation} \mathcal{L}_{d} = - \frac{1}{N} \sum_i^N \left( \sum_{c=1}^{N_e} \mathbbm{1}_{e=c} log(G_i^e[c]) \right), \label{eq:disloss} \end{equation} \end{small}\noindent where $N$ is the number of training samples, set to be the number of input graphs multiplies by the number of factor graphs; $N_e$ is the number of factor graphs; $G_i^e$ is the distribution of sample $i$ and $G_i^e[c]$ represents the probability that the generated factor graph has label $c$. $\mathbbm{1}_{e=c}$ is an indicator function, taken to be one when the predicted label is correct. \subsection{{Aggregation Step}} As the factor graphs derived from the disentangling step is optimized to be as diverse as possible, in the aggregation step, we will use the generated factor graphs to aggregate information in different structural spaces. This step is similar as the most GCN models, where the new node feature is generated by taking the weighted sum of its neighbors. Our aggregation mechanism is based on the simplest one, which is used in GCN~\citep{kipf2017semi}. The only difference is that the aggregation will take place independently for each of the factor graphs. The aggregation process is formulated as \begin{small} \begin{equation} h^{(l+1)_e}_i = \sigma(\sum_{j\in \mathcal{N}_i} E_{ije} / c_{ij} h^{(l)}_j \mathbf{W}^{(l)} ), c_{ij} = \left( |\mathcal{N}_i||\mathcal{N}_j| \right)^{1/2}, \label{eq:agg} \end{equation} \end{small}\noindent where $h^{(l+1)_e}_i$ represents the new feature for node $i$ in $l+1$ layer aggregated {from} the factor graph $e$; $\mathcal{N}_i$ represents all the neighbours of node $i$ in the input graph; $E_{ije}$ is the coefficient of the edge from node $i$ to node $j$ in the factor graph $e$; $c_{ij}$ is the normalization term that is computed according to the degree of node $i$ and node $j$; $\mathbf{W}^{(l)}$ is a linear transformation matrix, which is the same as the matrix used in the disentangling step. Note that although we use all the neighbours of a node in the input graph to aggregate information, {some of them are making no contribution if the corresponding coefficient in the factor graph is zero.} \subsection{{Merging Step}} Once the aggregation step is complete, different factor graphs will lead to different features of nodes. We merge these features generated from different factor graphs by applying \begin{small} \begin{equation} h^{(l+1)}_i = ||^{N_e}_{e=1} h^{(l+1)_e}_i, \label{eq:merge} \end{equation} \end{small}\noindent where $h^{(l+1)}_i$ is the output feature of node $i$; $N_e$ is the number of factor graphs; $||$ represents the concatenation operation. \subsection{Architecture} We discuss above the design of one disentangle layer, which contains three steps. The FactorGCN model we used in the experimental section contains several such disentangle layers, increasing the power of expression. Moreover, by setting different number of factor graphs in different layers, the proposed model can disentangle the input data in a hierarchical manner. The total loss to train FactorGCN model is $\mathcal{L} = \mathcal{L}_{t} + \lambda * \mathcal{L}_{d} $. $\mathcal{L}_{t}$ is the loss of the original task, which is taken to be a binary cross entropy loss for multi-label classification task, cross entropy loss for multi-class classification task, or L1 loss for regression task. $\mathcal{L}_{d}$ is the loss of the discriminator we mentioned above. $\lambda$ is the weight to balance these two losses. \section{Experiments} In this section, we show the effectiveness of the proposed FactorGCN, and provide discussions on its various components as well as the sensitivity with respect to the key hyper-parameters. More results can be found in the supplementary materials. \subsection{Experimental setups} {\textbf{Datasets}. } Here, we use six datasets to evaluate the effectiveness of the proposed method. The first one is a synthetic dataset that contains a fixed number of predefined graphs as factor graphs. The second one is the ZINC dataset~\citep{dwivedi2020benchmarkinggnn} built from molecular graphs. The third one is Pattern dataset~\citep{dwivedi2020benchmarkinggnn}, which is a large scale dataset for node classification task. The other three are widely used graph classification datasets include social networks~(COLLAB,IMDB-B) and bioinformatics graph~(MUTAG)~\citep{yanardag2015deepgin}. To generate the synthetic dataset that contains $N_e$ factor graphs, we first generate $N_e$ predefined graphs, which are the well-known graphs like Tur\'an graph, house-x graph, and balanced-tree graph. We then choose half of them and pad them with isolated nodes to make the number of nodes to be 15. The padded graphs will be merged together as a training sample. The label of the synthetic data is a binary vector, with the dimension $N_e$. Half of the labels will be set to one according to the types of graphs that the sample generated from, and the rest are set to zero. More information about the datasets can be found in the supplemental materials. \textbf{Baselines}. We adopt several methods, including state-of-the-art ones, as the baselines. Among all, MLP is the simplest one, which contains multiple fully connected layers. Although this method is simple, it can in fact perform well when comparing with other methods that consider the structural information. We use MLP to check whether the other compared methods benefit from using the structural information as well. GCN aggregates the information in the graph according to the laplacian matrix of the graph, which can be seen as a fixed weighted sum on the neighbours of a node. GAT~\citep{velickovic2018graphgat} extends the idea of GCN by introducing the attention mechanism. The weights when doing the aggregation is computed dynamically according to all the neighbours. For the ZINC dataset, we also add MoNet~\citep{monti2017geometricMoNet} and GatedGCN$_E$~\citep{dwivedi2020benchmarkinggnn} as baselines. The former one is the state-of-the-art method that does not use the type information of edges while the latter one is the state-of-the-art one that uses additional edge information. Random method is also added to provide the result of random guess for reference. For the other three graph datasets, we add non DL-based methods~(WL subtree, PATCHYSAN, AWL) and DL-based methods~(GCN, GraphSage~\citep{hamilton2017inductive}, GIN) as baselines. DisenGCN~\citep{ma2019disentangled} and IPDGN~\citep{liu2019independence} are also added. \textbf{Hyper-parameters}. For the synthetic dataset, Adam optimizer is used with a learning rate of 0.005, the number of training epochs is set to 80, the weight decay is set to 5e-5. The row of the adjacent matrix of the generated synthetic graph is used as the feature of nodes. The negative slope of LeakyReLU for GAT model is set to 0.2, which is the same as the original setting. The number of hidden layers for all models is set to two. The dimension of the hidden feature is set to 32 when the number of factor graphs is no more than four and 64 otherwise. The weight for the loss of discriminator in FactorGCN is set to 0.5. For the molecular dataset, the dimension of the hidden feature is set to 144 for all methods and the number of layers is set to four. Adam optimizer is used with a learning rate of 0.002. No weight decay is used. $\lambda$ of FactorGCN is set to 0.2. All the methods are trained for 500 epochs. The test results are obtained using the model with the best performance on validation set. For the other three datasets, three layers FactorGCN is used. \begin{figure} \centering \includegraphics[width=0.95\linewidth]{Figs/vis_samples.pdf} \vspace{-1.3em} \caption{Examples of the disentangled factor graphs on the synthetic dataset. The isolated nodes are eliminated for a better visualization.} \label{fig:synthetic_vis} \vspace{-1.2em} \end{figure} \subsection{Qualitative Evaluation} We first provide the qualitative evaluations of disentanglement performance, including the visualization of the disentangled factor graphs and the correlation analysis of the latent features. \textbf{Visualization of disentangled factor graphs}. To give an intuitive understanding of the disentanglement. We provide in Fig.~\ref{fig:synthetic_vis} some examples of the generated factor graphs. We remove the isolated nodes and visualize the best-matched factor graphs with ground truths. More results and analyses can be found in the supplemental materials. \begin{figure}[ht] \centering \includegraphics[width=0.93\linewidth]{Figs/corr_six.pdf} \caption{Feature correlation analysis. The hidden features are obtained from the test split using the pre-trained models on the synthetic dataset. It can be seen that the features generated from FactorGCN present a more block-wise correlation pattern, indicating that the latent features have indeed been disentangled. We also show the classification performance in brackets.} \label{fig:synthetic_corr} \end{figure} \textbf{Correlation of disentangled features}. Fig.~\ref{fig:synthetic_corr} shows the correlation analysis of the latent features obtained from several pre-trained models on the synthetic dataset. It can be seen that also GCN and MLP models can achieve a high performance in the downstream task, and their latent features are hidden entangled. GAT gives {more} independent latent features but the performance is degraded in the original task. FactorGCN is able to extract the highly independent latent features and meanwhile achieve a better performance in the downstream task. \subsection{Quantitative Evaluation} The quantitative evaluation focuses on two parts, the performance of the downstream tasks and that of the disentanglement. \textbf{Evaluation protocol}. For the downstream tasks, we adopt the corresponding metrics to evaluate, i.e., Micro-F1 for the multi-label classification task, mean absolute error~(MAE) for the regression task. We design two new metrics to evaluate the disentanglement performance on the graph data. The first one is graph edit distance on edge~(GED$_{E}$). This metric is inspired by the traditional graph edit distance~(GED). Since the input graph already provides the information about the order of nodes, the disentanglement of the input data, in reality, only involves the changing of edges. Therefore, we restrict the GED by only allowing adding and removing the edges, and thus obtain a score of GED$_{E}$ by Hungarian match between the generated factor graphs and the ground truth. Specifically, for each pair of the generated factor graph and the ground truth graph, we first convert the continuous value in the factor graph to 1/0 value by setting the threshold to make the number of edges in these two graphs are the same. Then, GED$_{E}$s can be computed for every such combination. Finally, Hungarian match is adopted to obtain the best bipartite matching results as the GED$_{E}$ score. Besides the GED$_{E}$ score, we also care about the consistency of the generated factor graph. In other words, the best-matched pairs between the generated factor graphs and the ground truths, optimally, should be identical across all samples. We therefore introduce the second metric named as consistency score~(C-Score), related to GED$_{E}$. C-Score is computed as the average percentage of the most frequently matched factor graphs. The C-score will be one if the ground truth graphs are always matched to the fixed factor graphs. A more detailed description of evaluation protocol can be found in the supplemental materials. \begin{table} \caption{Performance on synthetic dataset. The four methods are evaluated in terms of the classification and the disentanglement performance. Classification performance is evaluated by Micro-F1 and disentanglement performance is measured by GED$_E$ and C-Score. For each method, we run the experiments five times and report the mean and std. Random method generates four factor graphs. GAT\_W/Dis represents GAT model with the additional discriminator proposed in this paper.} \label{tab:synthetic} \centering \scalebox{0.71}{ \begin{tabular}{lccccccc} \toprule & MLP & GCN & GAT & GAT\_W/Dis & DisenGCN & FactorGCN~(Ours) & Random\\ \midrule Micro-F1 $\uparrow$ & 0.940 $\pm$ 0.002 & 0.947 $\pm$ 0.003 & 0.923 $\pm$ 0.009 & 0.928 $\pm$ 0.009 & 0.904$\pm$0.007 & \textbf{0.995 $\pm$ 0.004} & 0.250 $\pm$ 0.002 \\ GED$_{E}$ $\downarrow$ & - & - & 12.59 $\pm$ 3.00 & 12.35 $\pm$ 3.86 & \textbf{10.54$\pm$4.35} & \textbf{10.59 $\pm$ 4.37} & 32.09 $\pm$ 4.85 \\ C-Score $\uparrow$ & - & - & 0.288 $\pm$ 0.064 & 0.274 $\pm$ 0.065 & 0.367$\pm$0.026 & \textbf{0.532 $\pm$ 0.044} & 0.315 $\pm$ 0.002 \\ \bottomrule \end{tabular} } \end{table} \textbf{Evaluation on the synthetic dataset}. We first evaluate the disentanglement performance on a synthetic dataset. The results are shown in Tab.~\ref{tab:synthetic}. Although MLP and GCN achieve good classification performances, they are not capable of disentanglement. GAT disentangles the input by using multi-head attention, but the performance of the original task is degraded. Our proposed method, on the other hand, achieves a much better performance in terms of both disentanglement and the original task. We also evaluate the compared methods on the synthetic dataset with various numbers of factor graphs, shown in Tab.~\ref{tab:synthetic_various}. As the number of latent factor graphs increase, the performance gain of the FactorGCN becomes large. However, when the number of factor graphs becomes too large, the task will be more challenging, yielding lower performance gains. \begin{table} \caption{Classification performance on synthetic graphs with different numbers of factor graphs. We change the total number of factor graphs and generate five synthetic datasets. When the number of factor graphs increases, the performance gain of FactorGCN becomes larger. However, as the number of factor graphs becomes too large, disentanglement will be more challenging, yielding {lower performance gains}.} \label{tab:synthetic_various} \centering \scalebox{0.92}{ \begin{tabular}{cccccc} \toprule \multirow{2}{*}{Method} & \multicolumn{5}{c}{Number of factor graphs} \\ \cmidrule(r){2-6} & 2 & 3 & 4 & 5 & 6 \\ \midrule MLP & 1.000 $\pm$ 0.000 & 0.985 $\pm$ 0.002 & 0.940 $\pm$ 0.002 & 0.866 $\pm$ 0.001 & 0.809 $\pm$ 0.002 \\ GCN & 1.000 $\pm$ 0.000 & 0.984 $\pm$ 0.000 & 0.947 $\pm$ 0.003 & 0.844 $\pm$ 0.002 & 0.765 $\pm$ 0.001 \\ GAT & 1.000 $\pm$ 0.000 & 0.975 $\pm$ 0.002 & 0.923 $\pm$ 0.009 & 0.845 $\pm$ 0.006 & 0.791 $\pm$ 0.006 \\ FactorGCN & 1.000 $\pm$ 0.000 & \textbf{1.000 $\pm$ 0.000} & \textbf{0.995 $\pm$ 0.004} & \textbf{0.893 $\pm$ 0.021} & \textbf{0.813 $\pm$ 0.049} \\ \bottomrule \end{tabular} } \end{table} \begin{table} \caption{Performance on the ZINC dataset. FactorGCN outperforms the compared methods by a large margin, with the capability of disentanglement. Note that our proposed method even achieves a similar performance as GatedGCN$_E$, the state-of-the-art method on ZINC dataset that explicitly uses additional edge information. } \label{tab:zinc} \centering \scalebox{0.70}{ \begin{tabular}{c|cccccc|c} \toprule & MLP & GCN & GAT & MoNet & DisenGCN & FactorGCN~(Ours) & GatedGCN$_E$\\ \midrule MAE $\downarrow$ & 0.667 $\pm$ 0.002 & 0.503 $\pm$ 0.005 & 0.479 $\pm$ 0.010 & 0.407 $\pm$ 0.007 & 0.538$\pm$0.005 & \textbf{0.366 $\pm$ 0.014} & \textit{0.363 $\pm$ 0.009}\\ GED$_{E}$ $\downarrow$ & - & - & 15.46 $\pm$ 6.06 & - & 14.14$\pm$6.19 & \textbf{12.72 $\pm$ 5.34} &- \\ C-Score $\uparrow$ & - & - & 0.309 $\pm$ 0.013 & - & 0.342$\pm$0.034 & \textbf{0.441 $\pm$ 0.012} &- \\ \bottomrule \end{tabular} } \end{table} \begin{table} \caption{Accuracy~(\%) on three graph classification datasets. FactorGCN performances on par with or better than the state-of-the-art GCN models. We highlight the best DL-based methods and non DL-based methods separately. FactorGCN uses the same hyper-parameters for all datasets.} \label{tab:other} \centering \scalebox{0.85}{ \begin{tabular}{cccc|cccc} \toprule & WL subtree & PATCHYSAN & AWL & GCN & GraphSage & GIN & FactorGCN \\ \midrule IMDB-B & 73.8 $\pm$ 3.9 & 71.0 $\pm$ 2.2 & \textbf{74.5 $\pm$ 5.9}& 74.0 $\pm$ 3.4 &72.3 $\pm$ 5.3 & \textbf{75.1 $\pm$ 5.1} & \textbf{75.3 $\pm$ 2.7} \\ COLLAB & \textbf{78.9 $\pm$ 1.9} & 72.6 $\pm$ 2.2 & 73.9 $\pm$ 1.9 & 79.0 $\pm$ 1.8 & 63.9 $\pm$ 7.7 & 80.2 $\pm$ 1.9 & \textbf{81.2 $\pm$ 1.4} \\ MUTAG & 90.4 $\pm$ 5.7 & \textbf{92.6 $\pm$ 4.2} & 87.9 $\pm$ 9.8 & 85.6 $\pm$ 5.8 & 77.7 $\pm$ 1.5 & \textbf{89.4 $\pm$ 5.6} & \textbf{89.9 $\pm$ 6.5}\\ \bottomrule \end{tabular} } \end{table} \begin{table}[ht] \caption{Accuracy~(\%) on the Pattern dataset for node-classification task. FactorGCN achieves the best performance, showing its ability to serve as a general GCN framework.} \label{tab:pattern} \centering \scalebox{0.86}{ \begin{tabular}{ccccccc} \toprule GCN & GatedGCN & GIN & MoNet & DisenGCN & IPDGN & FactorGCN \\ \midrule 63.88 $\pm$ 0.07 & 84.48 $\pm$ 0.12 & 85.59 $\pm$ 0.01 & 85.48 $\pm$ 0.04 & 75.01 $\pm$ 0.15 & 78.70 $\pm$ 0.11 & \textbf{86.57 $\pm$ 0.02} \\ \bottomrule \end{tabular} } \end{table} \begin{figure}[ht] \centering \includegraphics[width=0.99\linewidth]{Figs/sens_1x2.pdf} \caption{The influence of the balanced weight $\lambda$ and the number of factor graphs.} \label{fig:sens} \end{figure} \textbf{Evaluation on the ZINC dataset}. For this dataset, the type information of edges is hidden during the training process, and is serve as the ground truth to evaluate the performance of disentanglement. Tab.~\ref{tab:zinc} shows the results. The proposed method achieves the best performance on both the disentanglement and the downstream task. We also show the state-of-the-art method GatedGCN$_E$ on this dataset on the right side of Tab.~\ref{tab:zinc}, which utilizes the type information of edges during the training process. Our proposed method, without any additional edge information, achieves truly promising results that are to that of GatedGCN$_E$, which {needs the bond information of edges during training.} \textbf{Evaluation on more datasets}. To provide a thorough understanding of the proposed method, We also carry out evaluations on three widely used graph classification datasets and one node classification dataset to see the performances of FactorGCN as a general GCN framework. The same 10-fold evaluation protocol as~\citep{xu2018powerful} is adopted. Since there are no ground truth factor graphs, we only report the accuracy, shown in Tab.~\ref{tab:other} and Tab.~\ref{tab:pattern}. Our method achieves consistently the best performance, showing the potential of the FactorGCN as a general GCN framework, even putting aside its disentangling capability. More details about the evaluation protocol, the setup of our method, and the statistic information about these datasets can be found in the supplemental materials. \subsection{Ablation and sensitivity analysis} We show in Fig.~\ref{fig:sens} the ablation study and sensitivity analysis of the proposed method. When varying $\lambda$, the number of factors is set to be eight; when varying the number of factors , $\lambda$ is set to be 0.2. As can be seen from the left figure, the performance of both the disentanglement and the downstream task will degrade without the discriminator. The right figure shows the relations between the performance and the number of factor graphs we used in FactorGCN. Setting the number of factor graphs to be slightly larger than that of the ground truth, in practice, leads to a better performance. \section{Conclusion} We propose a novel GCN framework, termed as FactorGCN, which achieves graph convolution through graph-level disentangling. Given an input graph, FactorGCN decomposes it into several interpretable factor graphs, each of which denotes an underlying interconnections between entities, and then carries out topology-aware convolutions on each such factor graph to produce the final node features. The node features, derived under the explicit disentangling, are therefore block-wise explainable and beneficial to the downstream tasks. Specifically, FactorGCN enables multi-relation disentangling, allowing information propagation between two nodes to take places in disjoint spaces. We also introduce two new metrics to measure the graph disentanglement performance quantitatively. FactorGCN outperforms other methods on both the disentanglement and the downstream tasks, indicating the proposed method is ready to serve as a general GCN framework with the capability of graph-level disentanglement. \section*{Acknowledgments} This work is supported by the startup funding of Stevens Institute of Technology. \section*{Broader Impact} In this work we introduce a GCN framework, termed as FactorGCN, that explicitly accounts for disentanglement FactorGCN is applicable to various scenarios, both technical and social. For conventional graph-related tasks, like node classification of the social network and graph classification of the molecular graph, our proposed method can serve as a general GCN framework. For disentangling tasks, our method generates factor graphs that reveal the latent relations among entities, and facilitate the further decision making process like recommendation. Furthermore, given sufficient data, FactorGCN can be used as a tool to analyze social issues like discovering the reasons for the quick spread of the epidemic disease in some areas. Like all learning-based methods, FactorGCN is not free of errors. If the produced disentangled factor graphs are incorrect, for example, the subsequent inference and prediction results will be downgraded, possibly yielding undesirable bias. \newpage \small \bibliographystyle{unsrtnat} \section{Introduction} Disentangling aims to factorize an entity, like a feature vector, into several interpretable components, so that the behavior of a learning model can be better understood. In recent years, many approaches have been proposed towards tackling disentangling in deep neural networks and have achieved promising results. Most prior efforts, however, have been focused on the disentanglement of convolutional neural network~(CNN) especially the auto-encoder architecture, where disentangling takes place during the stage of latent feature generation. {For example, VAE~\citep{kingma2013autovae} restrains the distribution of the latent features to Gaussian and generates disentangled representation; $\beta$-VAE~\citep{higgins2017betaVAE} further improves the disentangling by introducing $\beta$ to balance the independence constraints and reconstruction accuracy.} Despite the many prior efforts in CNN disentangling, there are few endeavors toward disentangling in the irregular structural domain, where graph convolutional network~(GCN) models are applied. Meanwhile, the inherent differences between grid-like data and structural data precludes applying CNN-based disentangling methods to GCN ones. The works of~\citep{ma2019disentangled,liu2019independence}, as pioneering attempts, focus on the node-level neighbour partition and ignore the latent multi-relations among nodes. We introduce in this paper a novel GCN, that aims to explicitly conduct graph-level disentangling, based on which convolutional features are aggregated. Our approach, termed as \emph{factorizable graph convolutional network}~(FactorGCN), takes as input a \emph{simple graph}, and decomposes it into several factor graphs, each of which corresponds to a disentangled and interpretable relation space, as shown in Fig.~\ref{fig:factorlayer}. Each such graph then undergoes a GCN, tailored to aggregate features only from one disentangled latent space, followed by a merging operation that concatenates all derived features from disentangled spaces, so as to produce the final block-wise interpretable features. These steps constitute one layer of the proposed FactorGCN. As the output graph with updated features share the identical topology as input, nothing prevents us from stacking a number of layers to disentangle the input data at different levels, yielding a hierarchical disentanglement with various numbers of factor graph at different levels. FactorGCN, therefore, potentially finds application in a wide spectrum of scenarios. In many real-world graphs, multiple heterogeneous relations between nodes are mixed and collapsed to one single edge. In the case of social networks, two people may be \emph{friends}, \emph{colleagues}, and \emph{living in the same city} simultaneously, but linked via one single edge that omits such interconnections; in the co-purchasing scenario~\citep{co-purchase}, products are bought together for different reasons like \emph{promotion}, and \emph{functional complementary}, but are often ignored in the graph construction. FactorGCN would, in these cases, deliver a disentangled and interpretable solution towards explaining the underlying rationale, and provide discriminant learned features for the target task. \iffalse multiple relations may exist between two person, like friend, colleague, neighbor, and family. However, these relations may mixed up when constructing the graph by only considering whether them are connected. Another example is the co-purchase graph~\citep{co-purchase}, where products can be purchased together with different reasons, like promotion, advertisement, and functional complementary. These reasons cannot be detected when constructing the graph by consider whether they are bought together frequently. \fi \iffalse Many methods have been proposed to solve the problem of disentanglement. Most of these methods are based on the architecture of auto-encoder, where the disentanglement is happened during the generation of the latent features. For example, $\beta-$VAE~\citep{higgins2017betaVAE} improves the disentanglement performance of the original VAE by introducing a weight in the distribution constrain item. Using a $\bata$ more than one will enforce the auto-encoder to learn a more efficient latent representation and disentangle in an unsupervised manner. Although there are many pioneers focus on the disentanglement of CNN models, there are few works that discover the disentangling in the structural domain, where GCN models are applied. The inherent differences between grid-like data and structural data make the disentanglement on GCN difficult. One of the challenges is that the meaning of the disentangled features of a GCN model are hard to explain. In the field of image or audio, different dimensions of the disentangled features can represent a special aspect of the input data, like size of object or tone of the audio. However, in structural domain, it is hard to say what is one dimension of the node's feature represents. The exist methods~\citep{ma2019disentangled,liu2019independence} all focus on grouping the neighbours of the node and fail to capture the latent multi-relations among entities. In this paper, we propose factorized graph convolutional networks~(FactorGCN), a general framework that disentangles the structural input into several factor graphs. Each of these factor graphs represents a relations across all the entities and generates the features of entities independently. Fig.~\ref{fig:factorlayer} shows an example one layer in the FactorGCN model. \fi \begin{figure} \centering \includegraphics[width=0.95\linewidth]{Figs/pipeline.pdf} \caption{Illustration of one layer in the proposed FactorGCN. It contains three steps: \emph{Disentangling}, \emph{Aggregation}, and \emph{Merging}. In the disentangling step, the input graph is decomposed into several factor graphs, each of which represents a latent relation among nodes. In the aggregation step, GCNs are applied separately to the derived factor graphs and produce the latent features. In the merging step, features from all latent graphs are concatenated to form the final features, which are block-wise interpretable.} \label{fig:factorlayer} \end{figure} Specifically, the contributions of FactorGCN are summarized as follows. \begin{itemize} \item {\bf Graph-level Disentangling}. FactorGCN conducts disentangling and produces block-wise interpretable node features by analyzing the whole graph all at once, during which process the global-level topological semantics, such as the higher-order relations between edges and nodes, is explicitly accounted for. The disentangled factor graphs reveal latent-relation specific interconnections between the entities of interests, and yield interpretable features that benefit the downstream tasks. This scheme therefore contrasts to the prior approaches of~\citep{ma2019disentangled,liu2019independence}, where the {disentanglement takes place only within a local neighborhood, without accounting for global contexts}. \item {\bf Multi-relation Disentangling}. Unlike prior methods that decode only a single attribute for a neighboring node, FactorGCN enables multi-relation disentangling, meaning that {the center node may aggregate information from a neighbour under multiple types of relations}. This mechanism is crucial since real-world data may contain various relations among the same pair of entities. In the case of a social network graph, for example, FactorGCN would produce disentangled results allowing for two users to be both \emph{friends} and \emph{living in the same city}; such multi-relation disentangling is not supported by prior GCN methods. \item {\bf Quantitative Evaluation Metric}. Existing quantitative evaluation methods~\citep{eastwood2018framework,burgess2018understanding} in the grid domain rely on generative models, like auto-encoder~\citep{kim2018disentangling} or GAN~\citep{chen2016infogan}. Yet in the irregular domain, unfortunately, state-of-the-art graph generative models are only applicable for generating small graphs or larger ones without features. {Moreover, these models comprise a sequential generation step, making it infeasible to be integrated into the graph disentangling frameworks.} To this end, we propose a graph edit-distance based metric, which bypasses the generation step and estimates the similarity between the factor graphs and the ground truth. \end{itemize} We conducted experiments on five datasets in various domains, and demonstrate that the proposed FactorGCN yields state-of-the-art performances for both disentanglement and downstream tasks. This indicates that, even putting side its disentangling capability, FactorGCN may well serve as a general GCN framework. Specifically, on the ZINC dataset~\citep{jin2018junctionZINC}, FactorGCN outperforms other methods by a large margin, and, without {the bond information of the edges}, FactorGCN achieves a performance on par with the state-of-the-art method that explicitly {utilizes} edge-type information. \iffalse For two of them, ground truhts of the disentangled factor graphs are available; on these two datasets, FactorGCN performs consistently the best in terms of both the disentanglement performance and the downstream task performance. The other three datasets are from social network and bioinformatics graph, on which FactorGCN achieves the state-of-the-art performance, showing that it is ready to be used as a general GCN framework. Specifically, on the ZINC dataset, our method outperforms the other methods by a large margin and achieve a similar performance as the state-of-the-art method that explicitly \emph{utilizes} the type information of edges, indicating that the disentangled factor graphs can indeed boost results of the downstream tasks. \fi \section{Related Work} \textbf{Disentangled representation learning}. Learning disentangled representations has recently emerged as a significant task towards interpretable AI~\citep{yang2020ECCV,Song_2020_CVPR}. Unlike earlier attempts that rely on handcrafted disentangled representations or variables~\citep{WangECCV14,WangTPAMI16}, most of the recent works in disentangled representation learning are based on the architecture of auto-encoder~\citep{higgins2017betaVAE,feng2018dual,bouchacourt2018multi,burgess2018understanding,wang2017tag,kim2018disentangling} or generative model~\citep{chen2016infogan,zhao2017learning,siddharth2017learning}. One mainstream auto-encoder approach is to constrain the latent feature generated from the encoder to make it independent in each dimension. For example, VAE~\citep{kingma2013autovae} constrains the distribution of the latent features to Gaussian; $\beta$-VAE\citep{higgins2017betaVAE} enlarges the weight of the KL divergence term to balance the independence constraints and reconstruction accuracy; \citep{schmidhuber1992learning} disentangles the latent features by ensuring that each block of latent features cannot be predicted from the rest; DSD~\citep{feng2018dual} swaps some of the latent features twice to achieve semi-supervised disentanglement. For the generative model, extra information is introduced during the generation. For example, InfoGAN~\citep{chen2016infogan} adds the class code to the model and maximizes the mutual information between the generated data and the class code. \textbf{Graph convolutional network}. Graph convolutional network~(GCN) has shown its potential in the non-grid domain~\citep{xu2018powerful,Qiu2020ECCV,li2018combinatorial,yang2020distilling,monti2017geometricMoNet,ijcai_spagan}, achieving promising results on various type of structural data, like citation graph~\citep{velickovic2018graphgat}, social graph~\citep{kipf2017semi}, and relational graph~\citep{schlichtkrull2018modeling}. Besides designing GCN to better extract information from non-grid data, there are also a couple of works that explore the disentangled GCNs~\citep{ma2019learning,liu2019independence}. DisenGCN~\citep{ma2019disentangled} adopts neighbour routine to divide the neighbours of the node into several mutually exclusive parts. IPGDN~\citep{liu2019independence} improves DisenGCN by making the different parts of the embedded feature independent. Despite results of the previous works, there remain still several problems: the disentanglement is in the node level, which does not consider the information of the whole graph, and there is no quantitative metrics to evaluate the performance of disentanglement. \section{Method} In this section, we will give a detailed description about the architecture of FactorGCN, whose basic component is the disentangle layer, as shown in Fig.~\ref{fig:factorlayer}. \subsection{{Disentangling Step}} The goal of this step is to factorize the input graph into several factor graphs. To this end, we treat the edges equally across the whole graph. The mechanism we adopt to generate these factorized coefficient is similar to that of graph attention network~\citep{velickovic2018graphgat}. We denote the input of the disentangle layer as $\mathbf{h} = \{h_0, h_1, ..., h_n\}, h_i \in \mathcal{R}^F$ and $\mathbf{e} = \{e_0, e_1, ..., e_m\}, e_k = (h_i, h_j)$. $\mathbf{h}$ denotes the set of nodes with feature of $F$ dimension, and $\mathbf{e}$ denotes the set of edges. The input nodes are transformed to a new space, done by multiplying the features of nodes with a linear transformation matrix $\mathbf{W} \in \mathcal{R}^{F^\prime \times F}$. This is a standard operation in most GCN models, which increases the capacity of the model. The transformed features are then used to generate the factor coefficients as follows \begin{equation} E_{ije} = 1 / \left(1 + e^{-\Psi_e (h^\prime_{i}, h^\prime_{j}) } \right); h^\prime=\mathbf{W} h, \label{eq:1} \end{equation} where $\Psi_{e}$ is the function that takes the features of node $i$ and node $j$ as input and computes the attention score of the edge for factor graph $e$, and takes the form of an one-layer MLP in our implementation; $E_{ije}$ then can be obtained by normalizing the attention score to $[0, 1]$, representing the coefficient of edge from node $i$ to node $j$ in the factor graph $e$; {$h^\prime$ is the transformed node feature, shared across all functions $\Psi_{*}$.} Different from most previous {forms of attention-based GCNs} that normalize the attention coefficients among all the neighbours of nodes, our proposed model generates these coefficients directly {as the factor graph}. Once all the coefficients are computed, a factor graph $e$ can be represented by its own $E_e$, which will be used for the next aggregation step. However, without any other constrain, some of the generated factor graphs may contain a similar structure, degrading the disentanglement performance and capacity of the model. We therefore introduce an additional head in the disentangle layer, aiming to avoid the degradation of the generated factor graphs. The motivation of the additional head is that, a well disentangled factor graph should have enough information to be distinguished from the rest, only based on its structure. {Obtaining the solution that all the disentangled factor graphs differ from each other to the maximal degree, unfortunately, is not trivial.} We thus approximate the solution by giving unique labels to the factor graphs and optimizing the factor graphs as a graph classification problem. Our additional head will serve as a {discriminator, shown in Eq.~\ref{eq:2}}, to distinguish which label a given graph has: \begin{small} \begin{equation} G_e = {\rm Softmax}\Big( f \big({\rm Readout}(\mathcal{A}(\mathbf{E}_{e}, \mathbf{h^\prime}) ) \big) \Big). \label{eq:2} \end{equation} \end{small} The discriminator contains a three-layer graph auto-encoder $\mathcal{A}$, which takes the transformed feature $\mathbf{h^\prime}$ and the generated attention coefficients of factor graph $\mathbf{E}_e$ as inputs, and generates the new node features. These features are then readout to generate the representation of the whole factor graph. Next, the feature vectors will be sent to a classifier with one fully connected layer. Note that all the factor graphs share the same {node features}, making sure that the information discovered by the discriminator only comes from the difference among the structure of the factor graphs. More details about the discriminator architecture can be found in the supplementary materials. The loss used to train the discriminator is taken as follows: \begin{small} \begin{equation} \mathcal{L}_{d} = - \frac{1}{N} \sum_i^N \left( \sum_{c=1}^{N_e} \mathbbm{1}_{e=c} log(G_i^e[c]) \right), \label{eq:disloss} \end{equation} \end{small}\noindent where $N$ is the number of training samples, set to be the number of input graphs multiplies by the number of factor graphs; $N_e$ is the number of factor graphs; $G_i^e$ is the distribution of sample $i$ and $G_i^e[c]$ represents the probability that the generated factor graph has label $c$. $\mathbbm{1}_{e=c}$ is an indicator function, taken to be one when the predicted label is correct. \subsection{{Aggregation Step}} As the factor graphs derived from the disentangling step is optimized to be as diverse as possible, in the aggregation step, we will use the generated factor graphs to aggregate information in different structural spaces. This step is similar as the most GCN models, where the new node feature is generated by taking the weighted sum of its neighbors. Our aggregation mechanism is based on the simplest one, which is used in GCN~\citep{kipf2017semi}. The only difference is that the aggregation will take place independently for each of the factor graphs. The aggregation process is formulated as \begin{small} \begin{equation} h^{(l+1)_e}_i = \sigma(\sum_{j\in \mathcal{N}_i} E_{ije} / c_{ij} h^{(l)}_j \mathbf{W}^{(l)} ), c_{ij} = \left( |\mathcal{N}_i||\mathcal{N}_j| \right)^{1/2}, \label{eq:agg} \end{equation} \end{small}\noindent where $h^{(l+1)_e}_i$ represents the new feature for node $i$ in $l+1$ layer aggregated {from} the factor graph $e$; $\mathcal{N}_i$ represents all the neighbours of node $i$ in the input graph; $E_{ije}$ is the coefficient of the edge from node $i$ to node $j$ in the factor graph $e$; $c_{ij}$ is the normalization term that is computed according to the degree of node $i$ and node $j$; $\mathbf{W}^{(l)}$ is a linear transformation matrix, which is the same as the matrix used in the disentangling step. Note that although we use all the neighbours of a node in the input graph to aggregate information, {some of them are making no contribution if the corresponding coefficient in the factor graph is zero.} \subsection{{Merging Step}} Once the aggregation step is complete, different factor graphs will lead to different features of nodes. We merge these features generated from different factor graphs by applying \begin{small} \begin{equation} h^{(l+1)}_i = ||^{N_e}_{e=1} h^{(l+1)_e}_i, \label{eq:merge} \end{equation} \end{small}\noindent where $h^{(l+1)}_i$ is the output feature of node $i$; $N_e$ is the number of factor graphs; $||$ represents the concatenation operation. \subsection{Architecture} We discuss above the design of one disentangle layer, which contains three steps. The FactorGCN model we used in the experimental section contains several such disentangle layers, increasing the power of expression. Moreover, by setting different number of factor graphs in different layers, the proposed model can disentangle the input data in a hierarchical manner. The total loss to train FactorGCN model is $\mathcal{L} = \mathcal{L}_{t} + \lambda * \mathcal{L}_{d} $. $\mathcal{L}_{t}$ is the loss of the original task, which is taken to be a binary cross entropy loss for multi-label classification task, cross entropy loss for multi-class classification task, or L1 loss for regression task. $\mathcal{L}_{d}$ is the loss of the discriminator we mentioned above. $\lambda$ is the weight to balance these two losses. \section{Experiments} In this section, we show the effectiveness of the proposed FactorGCN, and provide discussions on its various components as well as the sensitivity with respect to the key hyper-parameters. More results can be found in the supplementary materials. \subsection{Experimental setups} {\textbf{Datasets}. } Here, we use six datasets to evaluate the effectiveness of the proposed method. The first one is a synthetic dataset that contains a fixed number of predefined graphs as factor graphs. The second one is the ZINC dataset~\citep{dwivedi2020benchmarkinggnn} built from molecular graphs. The third one is Pattern dataset~\citep{dwivedi2020benchmarkinggnn}, which is a large scale dataset for node classification task. The other three are widely used graph classification datasets include social networks~(COLLAB,IMDB-B) and bioinformatics graph~(MUTAG)~\citep{yanardag2015deepgin}. To generate the synthetic dataset that contains $N_e$ factor graphs, we first generate $N_e$ predefined graphs, which are the well-known graphs like Tur\'an graph, house-x graph, and balanced-tree graph. We then choose half of them and pad them with isolated nodes to make the number of nodes to be 15. The padded graphs will be merged together as a training sample. The label of the synthetic data is a binary vector, with the dimension $N_e$. Half of the labels will be set to one according to the types of graphs that the sample generated from, and the rest are set to zero. More information about the datasets can be found in the supplemental materials. \textbf{Baselines}. We adopt several methods, including state-of-the-art ones, as the baselines. Among all, MLP is the simplest one, which contains multiple fully connected layers. Although this method is simple, it can in fact perform well when comparing with other methods that consider the structural information. We use MLP to check whether the other compared methods benefit from using the structural information as well. GCN aggregates the information in the graph according to the laplacian matrix of the graph, which can be seen as a fixed weighted sum on the neighbours of a node. GAT~\citep{velickovic2018graphgat} extends the idea of GCN by introducing the attention mechanism. The weights when doing the aggregation is computed dynamically according to all the neighbours. For the ZINC dataset, we also add MoNet~\citep{monti2017geometricMoNet} and GatedGCN$_E$~\citep{dwivedi2020benchmarkinggnn} as baselines. The former one is the state-of-the-art method that does not use the type information of edges while the latter one is the state-of-the-art one that uses additional edge information. Random method is also added to provide the result of random guess for reference. For the other three graph datasets, we add non DL-based methods~(WL subtree, PATCHYSAN, AWL) and DL-based methods~(GCN, GraphSage~\citep{hamilton2017inductive}, GIN) as baselines. DisenGCN~\citep{ma2019disentangled} and IPDGN~\citep{liu2019independence} are also added. \textbf{Hyper-parameters}. For the synthetic dataset, Adam optimizer is used with a learning rate of 0.005, the number of training epochs is set to 80, the weight decay is set to 5e-5. The row of the adjacent matrix of the generated synthetic graph is used as the feature of nodes. The negative slope of LeakyReLU for GAT model is set to 0.2, which is the same as the original setting. The number of hidden layers for all models is set to two. The dimension of the hidden feature is set to 32 when the number of factor graphs is no more than four and 64 otherwise. The weight for the loss of discriminator in FactorGCN is set to 0.5. For the molecular dataset, the dimension of the hidden feature is set to 144 for all methods and the number of layers is set to four. Adam optimizer is used with a learning rate of 0.002. No weight decay is used. $\lambda$ of FactorGCN is set to 0.2. All the methods are trained for 500 epochs. The test results are obtained using the model with the best performance on validation set. For the other three datasets, three layers FactorGCN is used. \begin{figure} \centering \includegraphics[width=0.95\linewidth]{Figs/vis_samples.pdf} \vspace{-1.3em} \caption{Examples of the disentangled factor graphs on the synthetic dataset. The isolated nodes are eliminated for a better visualization.} \label{fig:synthetic_vis} \vspace{-1.2em} \end{figure} \subsection{Qualitative Evaluation} We first provide the qualitative evaluations of disentanglement performance, including the visualization of the disentangled factor graphs and the correlation analysis of the latent features. \textbf{Visualization of disentangled factor graphs}. To give an intuitive understanding of the disentanglement. We provide in Fig.~\ref{fig:synthetic_vis} some examples of the generated factor graphs. We remove the isolated nodes and visualize the best-matched factor graphs with ground truths. More results and analyses can be found in the supplemental materials. \begin{figure}[ht] \centering \includegraphics[width=0.93\linewidth]{Figs/corr_six.pdf} \caption{Feature correlation analysis. The hidden features are obtained from the test split using the pre-trained models on the synthetic dataset. It can be seen that the features generated from FactorGCN present a more block-wise correlation pattern, indicating that the latent features have indeed been disentangled. We also show the classification performance in brackets.} \label{fig:synthetic_corr} \end{figure} \textbf{Correlation of disentangled features}. Fig.~\ref{fig:synthetic_corr} shows the correlation analysis of the latent features obtained from several pre-trained models on the synthetic dataset. It can be seen that also GCN and MLP models can achieve a high performance in the downstream task, and their latent features are hidden entangled. GAT gives {more} independent latent features but the performance is degraded in the original task. FactorGCN is able to extract the highly independent latent features and meanwhile achieve a better performance in the downstream task. \subsection{Quantitative Evaluation} The quantitative evaluation focuses on two parts, the performance of the downstream tasks and that of the disentanglement. \textbf{Evaluation protocol}. For the downstream tasks, we adopt the corresponding metrics to evaluate, i.e., Micro-F1 for the multi-label classification task, mean absolute error~(MAE) for the regression task. We design two new metrics to evaluate the disentanglement performance on the graph data. The first one is graph edit distance on edge~(GED$_{E}$). This metric is inspired by the traditional graph edit distance~(GED). Since the input graph already provides the information about the order of nodes, the disentanglement of the input data, in reality, only involves the changing of edges. Therefore, we restrict the GED by only allowing adding and removing the edges, and thus obtain a score of GED$_{E}$ by Hungarian match between the generated factor graphs and the ground truth. Specifically, for each pair of the generated factor graph and the ground truth graph, we first convert the continuous value in the factor graph to 1/0 value by setting the threshold to make the number of edges in these two graphs are the same. Then, GED$_{E}$s can be computed for every such combination. Finally, Hungarian match is adopted to obtain the best bipartite matching results as the GED$_{E}$ score. Besides the GED$_{E}$ score, we also care about the consistency of the generated factor graph. In other words, the best-matched pairs between the generated factor graphs and the ground truths, optimally, should be identical across all samples. We therefore introduce the second metric named as consistency score~(C-Score), related to GED$_{E}$. C-Score is computed as the average percentage of the most frequently matched factor graphs. The C-score will be one if the ground truth graphs are always matched to the fixed factor graphs. A more detailed description of evaluation protocol can be found in the supplemental materials. \begin{table} \caption{Performance on synthetic dataset. The four methods are evaluated in terms of the classification and the disentanglement performance. Classification performance is evaluated by Micro-F1 and disentanglement performance is measured by GED$_E$ and C-Score. For each method, we run the experiments five times and report the mean and std. Random method generates four factor graphs. GAT\_W/Dis represents GAT model with the additional discriminator proposed in this paper.} \label{tab:synthetic} \centering \scalebox{0.71}{ \begin{tabular}{lccccccc} \toprule & MLP & GCN & GAT & GAT\_W/Dis & DisenGCN & FactorGCN~(Ours) & Random\\ \midrule Micro-F1 $\uparrow$ & 0.940 $\pm$ 0.002 & 0.947 $\pm$ 0.003 & 0.923 $\pm$ 0.009 & 0.928 $\pm$ 0.009 & 0.904$\pm$0.007 & \textbf{0.995 $\pm$ 0.004} & 0.250 $\pm$ 0.002 \\ GED$_{E}$ $\downarrow$ & - & - & 12.59 $\pm$ 3.00 & 12.35 $\pm$ 3.86 & \textbf{10.54$\pm$4.35} & \textbf{10.59 $\pm$ 4.37} & 32.09 $\pm$ 4.85 \\ C-Score $\uparrow$ & - & - & 0.288 $\pm$ 0.064 & 0.274 $\pm$ 0.065 & 0.367$\pm$0.026 & \textbf{0.532 $\pm$ 0.044} & 0.315 $\pm$ 0.002 \\ \bottomrule \end{tabular} } \end{table} \textbf{Evaluation on the synthetic dataset}. We first evaluate the disentanglement performance on a synthetic dataset. The results are shown in Tab.~\ref{tab:synthetic}. Although MLP and GCN achieve good classification performances, they are not capable of disentanglement. GAT disentangles the input by using multi-head attention, but the performance of the original task is degraded. Our proposed method, on the other hand, achieves a much better performance in terms of both disentanglement and the original task. We also evaluate the compared methods on the synthetic dataset with various numbers of factor graphs, shown in Tab.~\ref{tab:synthetic_various}. As the number of latent factor graphs increase, the performance gain of the FactorGCN becomes large. However, when the number of factor graphs becomes too large, the task will be more challenging, yielding lower performance gains. \begin{table} \caption{Classification performance on synthetic graphs with different numbers of factor graphs. We change the total number of factor graphs and generate five synthetic datasets. When the number of factor graphs increases, the performance gain of FactorGCN becomes larger. However, as the number of factor graphs becomes too large, disentanglement will be more challenging, yielding {lower performance gains}.} \label{tab:synthetic_various} \centering \scalebox{0.92}{ \begin{tabular}{cccccc} \toprule \multirow{2}{*}{Method} & \multicolumn{5}{c}{Number of factor graphs} \\ \cmidrule(r){2-6} & 2 & 3 & 4 & 5 & 6 \\ \midrule MLP & 1.000 $\pm$ 0.000 & 0.985 $\pm$ 0.002 & 0.940 $\pm$ 0.002 & 0.866 $\pm$ 0.001 & 0.809 $\pm$ 0.002 \\ GCN & 1.000 $\pm$ 0.000 & 0.984 $\pm$ 0.000 & 0.947 $\pm$ 0.003 & 0.844 $\pm$ 0.002 & 0.765 $\pm$ 0.001 \\ GAT & 1.000 $\pm$ 0.000 & 0.975 $\pm$ 0.002 & 0.923 $\pm$ 0.009 & 0.845 $\pm$ 0.006 & 0.791 $\pm$ 0.006 \\ FactorGCN & 1.000 $\pm$ 0.000 & \textbf{1.000 $\pm$ 0.000} & \textbf{0.995 $\pm$ 0.004} & \textbf{0.893 $\pm$ 0.021} & \textbf{0.813 $\pm$ 0.049} \\ \bottomrule \end{tabular} } \end{table} \begin{table} \caption{Performance on the ZINC dataset. FactorGCN outperforms the compared methods by a large margin, with the capability of disentanglement. Note that our proposed method even achieves a similar performance as GatedGCN$_E$, the state-of-the-art method on ZINC dataset that explicitly uses additional edge information. } \label{tab:zinc} \centering \scalebox{0.70}{ \begin{tabular}{c|cccccc|c} \toprule & MLP & GCN & GAT & MoNet & DisenGCN & FactorGCN~(Ours) & GatedGCN$_E$\\ \midrule MAE $\downarrow$ & 0.667 $\pm$ 0.002 & 0.503 $\pm$ 0.005 & 0.479 $\pm$ 0.010 & 0.407 $\pm$ 0.007 & 0.538$\pm$0.005 & \textbf{0.366 $\pm$ 0.014} & \textit{0.363 $\pm$ 0.009}\\ GED$_{E}$ $\downarrow$ & - & - & 15.46 $\pm$ 6.06 & - & 14.14$\pm$6.19 & \textbf{12.72 $\pm$ 5.34} &- \\ C-Score $\uparrow$ & - & - & 0.309 $\pm$ 0.013 & - & 0.342$\pm$0.034 & \textbf{0.441 $\pm$ 0.012} &- \\ \bottomrule \end{tabular} } \end{table} \begin{table} \caption{Accuracy~(\%) on three graph classification datasets. FactorGCN performances on par with or better than the state-of-the-art GCN models. We highlight the best DL-based methods and non DL-based methods separately. FactorGCN uses the same hyper-parameters for all datasets.} \label{tab:other} \centering \scalebox{0.85}{ \begin{tabular}{cccc|cccc} \toprule & WL subtree & PATCHYSAN & AWL & GCN & GraphSage & GIN & FactorGCN \\ \midrule IMDB-B & 73.8 $\pm$ 3.9 & 71.0 $\pm$ 2.2 & \textbf{74.5 $\pm$ 5.9}& 74.0 $\pm$ 3.4 &72.3 $\pm$ 5.3 & \textbf{75.1 $\pm$ 5.1} & \textbf{75.3 $\pm$ 2.7} \\ COLLAB & \textbf{78.9 $\pm$ 1.9} & 72.6 $\pm$ 2.2 & 73.9 $\pm$ 1.9 & 79.0 $\pm$ 1.8 & 63.9 $\pm$ 7.7 & 80.2 $\pm$ 1.9 & \textbf{81.2 $\pm$ 1.4} \\ MUTAG & 90.4 $\pm$ 5.7 & \textbf{92.6 $\pm$ 4.2} & 87.9 $\pm$ 9.8 & 85.6 $\pm$ 5.8 & 77.7 $\pm$ 1.5 & \textbf{89.4 $\pm$ 5.6} & \textbf{89.9 $\pm$ 6.5}\\ \bottomrule \end{tabular} } \end{table} \begin{table}[ht] \caption{Accuracy~(\%) on the Pattern dataset for node-classification task. FactorGCN achieves the best performance, showing its ability to serve as a general GCN framework.} \label{tab:pattern} \centering \scalebox{0.86}{ \begin{tabular}{ccccccc} \toprule GCN & GatedGCN & GIN & MoNet & DisenGCN & IPDGN & FactorGCN \\ \midrule 63.88 $\pm$ 0.07 & 84.48 $\pm$ 0.12 & 85.59 $\pm$ 0.01 & 85.48 $\pm$ 0.04 & 75.01 $\pm$ 0.15 & 78.70 $\pm$ 0.11 & \textbf{86.57 $\pm$ 0.02} \\ \bottomrule \end{tabular} } \end{table} \begin{figure}[ht] \centering \includegraphics[width=0.99\linewidth]{Figs/sens_1x2.pdf} \caption{The influence of the balanced weight $\lambda$ and the number of factor graphs.} \label{fig:sens} \end{figure} \textbf{Evaluation on the ZINC dataset}. For this dataset, the type information of edges is hidden during the training process, and is serve as the ground truth to evaluate the performance of disentanglement. Tab.~\ref{tab:zinc} shows the results. The proposed method achieves the best performance on both the disentanglement and the downstream task. We also show the state-of-the-art method GatedGCN$_E$ on this dataset on the right side of Tab.~\ref{tab:zinc}, which utilizes the type information of edges during the training process. Our proposed method, without any additional edge information, achieves truly promising results that are to that of GatedGCN$_E$, which {needs the bond information of edges during training.} \textbf{Evaluation on more datasets}. To provide a thorough understanding of the proposed method, We also carry out evaluations on three widely used graph classification datasets and one node classification dataset to see the performances of FactorGCN as a general GCN framework. The same 10-fold evaluation protocol as~\citep{xu2018powerful} is adopted. Since there are no ground truth factor graphs, we only report the accuracy, shown in Tab.~\ref{tab:other} and Tab.~\ref{tab:pattern}. Our method achieves consistently the best performance, showing the potential of the FactorGCN as a general GCN framework, even putting aside its disentangling capability. More details about the evaluation protocol, the setup of our method, and the statistic information about these datasets can be found in the supplemental materials. \subsection{Ablation and sensitivity analysis} We show in Fig.~\ref{fig:sens} the ablation study and sensitivity analysis of the proposed method. When varying $\lambda$, the number of factors is set to be eight; when varying the number of factors , $\lambda$ is set to be 0.2. As can be seen from the left figure, the performance of both the disentanglement and the downstream task will degrade without the discriminator. The right figure shows the relations between the performance and the number of factor graphs we used in FactorGCN. Setting the number of factor graphs to be slightly larger than that of the ground truth, in practice, leads to a better performance. \section{Conclusion} We propose a novel GCN framework, termed as FactorGCN, which achieves graph convolution through graph-level disentangling. Given an input graph, FactorGCN decomposes it into several interpretable factor graphs, each of which denotes an underlying interconnections between entities, and then carries out topology-aware convolutions on each such factor graph to produce the final node features. The node features, derived under the explicit disentangling, are therefore block-wise explainable and beneficial to the downstream tasks. Specifically, FactorGCN enables multi-relation disentangling, allowing information propagation between two nodes to take places in disjoint spaces. We also introduce two new metrics to measure the graph disentanglement performance quantitatively. FactorGCN outperforms other methods on both the disentanglement and the downstream tasks, indicating the proposed method is ready to serve as a general GCN framework with the capability of graph-level disentanglement. \section*{Acknowledgments} This work is supported by the startup funding of Stevens Institute of Technology. \section*{Broader Impact} In this work we introduce a GCN framework, termed as FactorGCN, that explicitly accounts for disentanglement FactorGCN is applicable to various scenarios, both technical and social. For conventional graph-related tasks, like node classification of the social network and graph classification of the molecular graph, our proposed method can serve as a general GCN framework. For disentangling tasks, our method generates factor graphs that reveal the latent relations among entities, and facilitate the further decision making process like recommendation. Furthermore, given sufficient data, FactorGCN can be used as a tool to analyze social issues like discovering the reasons for the quick spread of the epidemic disease in some areas. Like all learning-based methods, FactorGCN is not free of errors. If the produced disentangled factor graphs are incorrect, for example, the subsequent inference and prediction results will be downgraded, possibly yielding undesirable bias. \newpage \small \bibliographystyle{unsrtnat}
{'timestamp': '2020-10-13T02:27:36', 'yymm': '2010', 'arxiv_id': '2010.05421', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05421'}
arxiv
\section{Introduction} It is an important problem in robotics to coordinate the movements of vehicles along a system of tracks without collisions. This problem was originally studied by Ghrist in \cite{Ghrist} by constructing the configuration space $C^n(G)$ of $n$ particles on a graph $G$, given by \[ C^n(G) = \{ (x_1, \ldots, x_n)\in G^n\,|\, \text{$x_i\neq x_j$ for $i\neq j$} \}. \] Every collision-free movement between two configurations of $n$ points on the graph $G$ corresponds to a path in the configuration space $C^n(G)$. The \emph{motion planning problem} consists of finding a function that assigns to any pair of points in the configuration space, a path between them. Mathematically, we can formalize this idea with the aid of the evaluation fibration. For any path-connected space $X,$ let $P(X)$ denote the space of continuous paths in $X$. The {\em evaluation fibration} $\operatorname{ev}: P(X)\to X\times X$ sends a path $\alpha$ to its endpoints: $\operatorname{ev}(\alpha)=(\alpha(0),\alpha(1)).$ A section $s$ of this fibration takes a pair of points as input and gives a path between those points as output. This section can be viewed as a rule $$s: X\times X\to P(X)$$ which assigns to each pair of initial and final positions, a path between them in $X$. If $s$ is continuous, we have that any small perturbation in the initial and final positions will lead to only small variations between the assigned paths. Farber \cite{Farber1} proved that it is impossible to find a section that is continuous over the whole domain $X\times X$ if space $X$ is not contractible. Motivated by this, Farber introduced the topological complexity of a space, see \cite{survey} for a more recent survey on the subject. The topological complexity of $X$, denoted by $TC(X)$, is a measure of this inability to find a continuous section over the whole domain. The topological complexity of a space is invariant under homotopy. We provide an explicit algorithm for two robots moving in a wedge of three circles $\Gamma$, which is optimal in the sense that the motion planning is performed with the minimal number of instabilities given by the topological complexity, $TC(C^2(\Gamma))$. The organization of the paper is as follows. In the second section, we describe the statement of the motion planning problem in our case and give a throughout description of the configuration space. In the third section, we introduce the topological complexity. Our approach consists of presenting a comprehensive construction of the configuration space for the case of two robots moving on a wedge of circles and then building a deformation retract of this space into a simpler space that we call the {\em network}. We dedicate section 4 to this construction. We also describe here some homeomorphic spaces to the network that will make possible the calculation of the topological complexity in the next section. In section 5, we use the homotopy invariance to calculate the topological complexity of the configuration space, which provides us with the minimal number of instructions for our algorithm. We exhibit an algorithm with a minimal number of instructions in section 6. This is the main section of this article. We give a detailed description of the instructions in the configuration space as well as in the physical space. We show how these instructions work in a sample case of two robots moving from a particular initial configuration to a final one. This paper is the result of an undergraduate research project at Wilbur Wright College supervised by Professor Hellen Colman. \section{Motion Planning Problem} We consider two robots confined to move on a graph given by three loops joined at a point, where a collision between robots is not allowed. This restricted movement of the robots in tracks is quite common in applications of motion planning and can be viewed as an instance of the problem of simultaneous control of two objects avoiding collisions with each other. Our problem involves constructing a program that allows two robots to move from their initial positions to their final ones without collisions. We want our algorithm to be robust, in the sense that small variations in the measuring of initial and final positions should lead to just small variations in those paths. We will now define some terms that we will use throughout the paper. A {\em robot} is a mechanical system capable of moving autonomously. The {\em physical space} is the physical environment in which the robots move. In our setting, the robots are two points $(A,B)$ and the physical space $\Gamma$ is a wedge of three circles, $\Gamma= \bigvee_3 S^1$. \subsection{Configuration Space} Although the motion planning problem is defined in the physical space where the robots move, we will study another auxiliary space where it will be easier to design the motion: the configuration space. A {\em state} of the system is a specification of the positions of all robots, and the {\em configuration space} is the space of all possible states. Motion planning problems involve navigation of the system through the configuration space in order to achieve a certain objective. The problem of finding individual paths for each robot in the physical space from initial to final positions translates into finding a single path in the configuration space from initial to final states. Let $(A,B)$ be two robots moving in a graph $\Gamma$ that consists of three circles joined at a point. The physical space is a wedge of circles as shown in figure \ref{wedge}. \begin{figure}[h] \caption{Physical space $\Gamma=\bigvee_3 S^1$} \label{wedge} \centering \includegraphics[height=4cm]{g} \end{figure} In order to construct the configuration space $X$ of two robots moving on a track $\Gamma$, $X=C^2(\Gamma)$, first we find the Cartesian product of $\Gamma\times \Gamma$ of all states and then exclude the diagonal $\Delta$ of collision states. Formally, the configuration space is $$X=C^2(\Gamma)=\Gamma\times \Gamma-\Delta=\big( \bigvee_3 S^1\times\bigvee_3 S^1\big)-\Delta$$ The space $\Gamma\times \Gamma$ consists of three groups of three tori joined by a wedge of three circles. The circles in this wedge are meridians of the three tori in each group, and each group is a union of three tori with a common parallel circle. See figure \ref{9tori}. \begin{figure}[H] \caption{Cartesian product $(\bigvee_3 S^1)\times(\bigvee_3 S^1)$} \label{9tori} \centering \includegraphics[height=6cm]{vandv} \end{figure} The product $\Gamma\times \Gamma$ consists of nine tori in total and is considerably complicated to visualize since even though the dimension of the space is two, it is not possible to embed it in $R^3$. To remove the diagonal, we take into consideration that the collision points are the states where the two robots are in the same circle in $\Gamma$: only one of the tori in each group would contain the entire diagonal circle. Once the diagonal is removed, each of these three tori will be cut open across its diagonal circle and homeomorphic to a cylinder. The other two tori in each group will be missing one point after the diagonal is removed. The configuration space is then composed of six tori and three cylinders all joined in an intricate way. Our approach will be to construct a flat representation of this space that will allow us to manipulate the space and understand it better. In this representation, each of the circles in the wedge are considered segments with the extreme points identified and each torus corresponds to a square with the edges identified as in the figure \ref{circletorus}. \begin{figure}[H] \caption{Interval to circle and square to torus} \label{circletorus} \centering \includegraphics[height=6cm]{circletointerval1} \end{figure} To track the robots in this representation, we will use the Cartesian system of coordinates, where the $x$-axis represents the positions of the first robot $A$ and the $y$-axis represents the positions of the second robot $B$. Each state represents the combined positions of the two robots $(A,B)$ in $\Gamma\times \Gamma$. Alternatively, we will also use a triangle shape $\triangle$ for the robot $A$ and a square shape $\square$ for the robot $B$. Figure \ref{flat} depicts the flat representation of $\Gamma\times \Gamma$. \begin{figure}[H] \caption{Flat Representation of $\Gamma\times \Gamma$} \label{flat} \centering \includegraphics[height=5cm]{cartesian2} \end{figure} The next step is to subtract the diagonal $\Delta$ from the Cartesian product of $\Gamma\times \Gamma$ to obtain the configuration space $X=\Gamma\times \Gamma-\Delta$. Our configuration space $X$ consists of six squares with vertices removed and with the edges identified; and three pairs of triangles, each pair with one edge identified. The squares correspond to those configurations where the two robots are on different circles in $\Gamma$, and the triangles correspond to the positions of robots in the same circle. Therefore, the configuration space $X$ consists of six squares and six triangles with the identifications are shown in figure \ref{parallelogram}. \begin{figure}[H] \caption{Flat representation of $\Gamma\times \Gamma-\Delta$} \label{parallelogram} \centering \includegraphics[height=5cm]{grid17} \end{figure} \section{Topological Complexity} The notion of topological complexity of the configuration space $X$, $TC(X)$, was introduced by Farber in \cite{Farber1}. If $X$ is the configuration space of robots moving in a physical space $\Gamma$, then the topological complexity is an invariant that measures the navigational complexity of robots moving in $\Gamma$. This number can be defined as the minimum number of {\em continuous rules} required to describe the movement between any two points in $X$. A motion planning algorithm takes a pair of points as input, the initial and the final states, and returns a continuous path as output between them. In other words, a motion planning algorithm is a section $s: X \times X \to P X$ of the evaluation map $\operatorname{ev} : P X \to X \times X$. That is, the section $s$ receives as input the initial and final positions of the robots $(A_i, B_i)$ and $(A_f, B_f)$ and returns as output a path $\alpha: I\to X$ such that $\alpha(0)=(A_i, B_i)$ and $\alpha(1)=(A_f, B_f)$. As we stated before, we would like a {\em robust} motion planning algorithm. Unfortunately, most navigation plans are discontinuous. Farber showed that a continuous navigation plan exists if and only if $X$ is contractible and for non-contractible spaces considered navigation plans that are continuous only when restricted to subsets of the whole Cartesian product $X\times X$. The {\em topological complexity} is the minimal $k$ for which $X \times X$ can be covered by $k$ open subsets over each of which the section is continuous. These open sets are called {\em domains of continuity}. In the same paper, Farber proved that the topological complexity is invariant under homotopy. \begin{teo}\cite{Farber1}\label{FarberHomotopy} If $X$ has the same type of homotopy as $Y$, then $TC(X)=TC(Y)$. \end{teo} This result will allow us to find the topological complexity of our configuration space by deforming $X$ into a simpler space with the same type of homotopy and then calculate its topological complexity. \section{Homotopy of the Configuration Space} As previously mentioned, topological complexity is the same across spaces with the same type of homotopy. Finding another space $N$ that is homotopically equivalent to $X$ will reduce the complexity of the configuration space and allow us to work on a relatively simpler space, which will be of great use not only to calculate the topological complexity but also to describe the final algorithm. \subsection{The network N}\label{sectionHomotopy} We construct a homotopy $$H:X\times I\rightarrow X$$ that deforms the whole space $X$ into a graph, which we call network $N$. In other words, $H_{0}(X)=X$ and $H_{1}(X)=N$, where $N$ is a graph. The network $N\subset X$ consists of horizontal, vertical and diagonal segments with the identifications showed in figure \ref{network}. \begin{figure}[H] \caption{The network N} \label{network} \centering \includegraphics[height=6cm]{networkSt2} \end{figure} We refer to the network parts in squares as {\em cross segments} and in triangles as {\em diagonal segments}. The deformation of squares into cross segments is illustrated in figure \ref{cross} and the triangles into diagonal segments in figure \ref{diagonal}. \begin{figure}[H] \caption{Cross segments} \label{cross} \centering \includegraphics[height=3cm]{torusandlineb_} \end{figure} \begin{figure}[H] \caption{Diagonal segments} \label{diagonal} \centering \includegraphics[height=4cm]{diagonaltriangles} \end{figure} The traces $H_t(x)$ of the homotopy $H$ for all $x\in X$ are shown in figure \ref{traces}. These traces will be useful to transit in and out of the network $N$ in the configuration space $X$. \begin{figure}[H] \caption{Homotopy traces in $X$} \label{traces} \centering \includegraphics[height=6cm]{tracesadjusted2} \end{figure} \subsection{The chain $C$} Following the identification of sides in the flat representation of $X$, we can observe that the network $N$ is homeomorphic to a chain of circles. Observe that the points along the diagonal are removed from our product space, forming tori with a removed point. Each torus minus a point is deformed into the cross segments in the corresponding square, namely a figure eight. See figure \ref{figure8}. \begin{figure}[H] \caption{Torus minus a point into a figure eight} \label{figure8} \centering \includegraphics[height=4cm]{figureeight} \end{figure} As we glue the two triangle parts along their identified edge, we obtain a parallelogram with two sides identified. Once that we glue these sides of the parallelogram together, we obtain a cylinder. Each cylinder is deformed into the diagonal segments in the corresponding triangles, namely a circle. See figure \ref{cylinder}. \begin{figure}[H] \caption{Cylinder into a circle} \label{cylinder} \centering \includegraphics[height=5cm]{cylindercircle} \end{figure} We obtained a figure eight from each of the six squares in $X$ and a circle from each of the three parallelograms. In total, $12$ circles $+ 3$ circles $=15$ circles. We will call this union of circles the chain $C$. We have that the network $N$ is homeomorphic to the chain $C$. We use the following naming system for the cross and diagonal segments in $N$. The cross segments are ${S_1,S_2,...S_{12}}$ and diagonal segments are ${u_1,u_2,v_1,v_1,v_2,z_1,z_2}$. See figure \ref{names}. \begin{figure}[H] \caption{Labelling segments in the network $N$} \label{names} \centering \includegraphics[height=6cm]{networknamed5} \end{figure} Then we draw the chain of $15$ circles accordingly, as reflected in figure \ref{chain}. \begin{figure}[H] \caption{Chain of $15$ circles} \label{chain} \centering \includegraphics[height=5cm]{chain4_} \end{figure} We will refer to the outer circles in the chain $C$ as {\em border circles} and inner circles as {\em connecting circles}. The outermost semicircles forming the border circles will be called {\em exterior semicircles} and the innermost ones will be the {\em interior semicircles}. In the construction of our motion planning algorithm, these exterior semicircles will have a distinguished role. The exterior semicircles in $C$ and in $N$ are shown in figures \ref{exteriorC} and \ref{exteriorN}. \begin{figure}[H] \caption{Exterior semicircles in the chain $C$} \label{exteriorC} \centering \includegraphics[height=5cm]{chainL} \end{figure} \begin{figure}[H] \caption{Exterior semicircles in the network $N$} \label{exteriorN} \centering \includegraphics[height=6cm]{semiex3} \end{figure} The chain circles in $C$ that correspond to vertical cross segments in the network $N$ are called {\em vertical circles}, and the circles that correspond to horizontal cross segments in $N$ are {\em horizontal circles}. Vertical circles correspond to positions in the physical space at which robot $A$ is at a pole while robot $B$ is at any place other than a pole in a different circle. Similarly, horizontal circles are the positions in $\Gamma$ at which robot $B$ is at a pole while robot $A$ is at a position other than a pole in a different circle. Vertical and horizontal circles in $C$ are shown in figure \ref{hv}. \begin{figure}[H] \caption{Horizontal and vertical circles in $C$} \label{hv} \centering \includegraphics[height=6cm]{hvcircles} \end{figure} \subsection{The bouquet of circles $B$} Now, we will find a homotopy equivalent space to the chain $C$. We see that each circle in the chain has two distinguished points that connect it to other circles. When we compress an interior semicircle into these points through homotopy, the interior semicircle contracts to a point, and the exterior semicircle forms a teardrop shape, as shown in the figure \ref{drop}. \begin{figure}[H] \caption{A Circle into a Teardrop} \label{drop} \centering \includegraphics[height=5cm]{droplet3} \end{figure} As we apply the operation to the entire chain $C$, all interior semicircles except one will collapse into a point. The process will follow as these $11$ interior semicircles collapse one by one forming eleven teardrops until they reach the last circle. At the final step, the two distinguished points will collapse into one forming two more teardrops. Hence, the total is $13$ teardrops. We can observe this occurring in the figure \ref{drop12}. \begin{figure}[H] \caption{Border circles into 13 teardrops} \label{drop12} \includegraphics[height=3.5cm]{bouquetstep1} \includegraphics[height=3.5cm]{step2chainaa} \includegraphics[height=3.5cm]{step3} \end{figure} As stated before, the connecting circles in the chain $C$ consist of two different semicircles joined by their endpoints. When we identified these endpoints, each connecting circle forms two teardrops. Therefore, we have $6$ teardrops from connecting circles and $13$ from border circles, forming a total of $19$ teardrops joined at one point, namely, a bouquet of $19$ circles, $B=\bigvee_{19}S^1$. See figure \ref{bouquet}. Observe that the connecting semicircles in $C$ lie on the outer rim of $B$. \begin{figure}[H] \caption{Bouquet of $19$ Circles} \label{bouquet} \centering \includegraphics[height=6cm]{bouquet_} \end{figure} We have that the configuration space is homotopic to a bouquet of $19$ circles: $$X\simeq N \cong C \simeq B$$ where $\simeq$ means homotopy equivalence and $\cong$ means homeomorphism. \section{Topological Complexity of $X$} In order to find the number of instructions for our motion planning algorithm, we consider the topological complexity of the configuration space, $TC(X)$. Farber calculated the topological complexity of a graph $G$ based on their first Betti number. The first Betti number of a graph $G$ with $n$ vertices, $m$ edges and $k$ connected components equals $ b_1(G)=m-n+k$. \begin{teo}\cite{Farber2} Let $G$ be a connected graph, then \begin{equation} TC(G) = \begin{cases} 1 & \text{if $b_1(G) = 0$}\\ 2 & \text{if $b_1(G) = 1$}\\ 3 & \text{if $b_1(G) \geq 2$} \end{cases} \end{equation} Here $b_1(G)$ denotes the first Betti number of $G$. \end{teo} We have shown that the configuration space $X$ is homotopy equivalent to $N$. Then we showed that the network $N$ is homeomorphic to a chain of circles $C$, which is homotopic to a wedge of $19$ circles $B$. We know that the topological complexity of $X$ will be equal to that of $B$ by theorem \ref{FarberHomotopy}. Since the first Betti number of a bouquet of nineteen circles is $b_1=19-1+1\geq 2 $, we have that $TC(B)=3$ and therefore, $TC(X)=3$. We conclude that for two robots moving on a wedge of three circles, any motion planning algorithm will require at least three continuous instructions. \section{Motion Planning Algorithm} Our goal is to give an explicit description of three continuous instructions in the physical space where the robots motion takes place. We will start by building the algorithm in the configuration space and then translate these instructions to the physical space by using all the constructions we have shown previously. Recall that any position in the physical space $\Gamma$ correspond to a state in the configuration space $X$. Our first step will be to move any state in $X$ to the corresponding state in the network $N$ following the traces of the homotopy shown in section \ref{sectionHomotopy}. The following definitions of specific positions and states in $\Gamma$ and $X$ will help to describe our algorithm. \begin{defi} The {\em vertex} is the center point of the physical space at which the three circles intersect and the {\em poles} are the antipodal points to the vertex in each circle in the physical space $\Gamma$. \end{defi} The states in the network $N$ correspond to positions of the robots in $\Gamma$ where at least one robot is at a pole and the other at a different circle or both robots are at antipodal positions in the same circle. \begin{defi} The {\em nodes} in the chain $C$ are the intersection points of the circles. The nodes where three circles intersect will be called {\em j-points}. \end{defi} \begin{defi} When a state is located in the interior of a cross segment in $X$, we will say it is a {\em cross state}. In the physical space $\Gamma$, cross states translate as the position of at least one robot being at the pole and the other at any of the other two circles but not at the vertex. A cross state in the chain $C$ will correspond to a point in a border circle that is not a j-point. See figures \ref{CSN} and \ref{CSC}. \end{defi} \begin{figure}[H] \caption{Cross states in $N$ and $C$} \label{CSN} \centering \includegraphics[height=5cm]{cstateN2} \includegraphics[height=5cm]{cstateC} \end{figure} \begin{figure}[H] \caption{An example of cross state in $\Gamma$} \label{CSC} \centering \includegraphics[height=4cm]{crossstateing} \end{figure} \begin{defi} A {\em cross center} is a cross state where two robots are at the intersection of horizontal and vertical network segments. A cross center corresponds to the positions in which both robots are at a pole in different circles in $\Gamma$ . We can observe this state in the chain $C$ at the nodes that are not j-points. See figure \ref{CC}. \begin{figure}[H] \caption{Cross center states in $N$ and $C$} \label{CC} \centering \includegraphics[height=5cm]{crosscenter2N} \includegraphics[height=5cm]{crosscenterC2} \end{figure} \begin{figure}[H] \caption{An example of cross center state in $\Gamma$} \label{CC} \centering \includegraphics[height=4cm]{crosscentering} \end{figure} \end{defi} \begin{defi} When the state is in the interior of a diagonal segment in the network $N$, we will say that the state is a {\em diagonal state}. In $\Gamma$, this state will correspond to antipodal positions in any circle, but none is at the vertex. Diagonal states correspond to points in connecting circles with the exception of j-points. See figures \ref{DSN} and \ref{DSC}. \begin{figure}[H] \caption{Diagonal states in $N$ and $C$} \label{DSN} \centering \includegraphics[height=5cm]{diagonalN3} \includegraphics[height=5cm]{diagonalC2} \end{figure} \begin{figure}[H] \caption{An example of diagonal state in $\Gamma$} \label{DSC} \centering \includegraphics[height=4cm]{diagonaling} \end{figure} \end{defi} We observe that j-states are states in $N$ that are neither diagonal nor cross states. There are two types of j-states: {\em vertical} and {\em horizontal}. Vertical j-states are those located between a diagonal segment and a vertical cross segment, whereas horizontal j-states are found between a diagonal segment and a horizontal cross segment. A j-state occurs when one robot in the physical space $\Gamma$ is at a center while the other is at a pole. In a vertical j-state, robot $B$ is at the vertex, whereas in a horizontal j-state, robot $A$ is at the vertex while the other robot is at a pole. In the chain $C$, they correspond to the intersection points of border and connecting circles. Vertical j-point are between a connecting circle and two vertical circles, and a horizontal j-point is between a connecting circle and two horizontal circles. See figure \ref{jN} and \ref{jC}. \begin{figure}[H] \caption{ j-states in $N$ and $\Gamma$} \label{jN} \centering \includegraphics[height=5cm]{jstateN2} \includegraphics[height=5cm]{jstateC2} \end{figure} \begin{figure}[H] \caption{An example of j-state in $\Gamma$} \label{jC} \centering \includegraphics[height=4cm]{jstateing} \end{figure} In the network $N$ the counterclockwise orientation is given by the orientation in $X$: in $x$-axis from left to right and in $y$-axis upwards. This orientation in the physical space and the chain $C$ is illustrated in the figure \ref{fig:counterclockwise} and \ref{fig:chaindire}. \begin{figure}[H] \caption{Counterclockwise direction in N and $C$} \label{fig:counterclockwise} \centering \includegraphics[height=5cm]{directionN2} \includegraphics[height=5cm]{directioninC2} \end{figure} \begin{figure}[H] \caption{Counterclockwise direction in $\Gamma$} \label{fig:chaindire} \centering \includegraphics[height=4cm]{counterclockwiseing} \end{figure} \subsection{Algorithm in the configuration space} In this section, we will describe the instructions needed to move a initial state $P_i$ in $X$ to the final state $P_f$. Recall that the first step of the algorithm consists of projecting the initial and final states $P_i$ and $P_f$ into the network $N$ following the traces of the homotopy $H:X\times I\rightarrow X$ as in figure \ref{traces}. We will denote the projections $P^*_i= H_1(P_i)$ and $P^*_f= H_1(P_f)$ . Next, we will construct the algorithm in the network $N$ to move from $P^*_i$ to $P^*_f$. The following definitions will help to describe the algorithm in the network $N$ and chain $C$. \begin{defi} The {\em initial node} ${CN}_i$ is the node in the chain $C$ corresponding to the cross center or j-state in $N$ at which the robots are initially located in N. If $P^*_i$ is a cross state, then the initial chain node ${CN}_i$ is the cross center of that cross state. If $P^*_i$ is a diagonal state, then the initial chain node ${CN}_i$ is the closest j-point in the counterclockwise direction. If $P^*_i$ is a node itself, then ${CN}_i=P^*_i$ Similarly, the {\em final node} ${CN}_f$ is the node in the chain $C$ corresponding to the final state $P^*_f$. \end{defi} \begin{defi} The {\em zigzag circle} is the union of the exterior semicircles in the chain $C$. See figure \ref{exteriorC} and \ref{exteriorN}. \end{defi} In figure \ref{zigzagNC} we show the zigzag circle in both network $N$ and chain $C$ with the counterclockwise orientation. \begin{figure}[H] \caption{Zigzag circle in $N$ and $C$} \centering \label{zigzagNC} \includegraphics[height=5cm]{zigzagN2} \includegraphics[height=5cm]{zigzagC2} \end{figure} Observe that the zigzag circle positions that are not nodes, correspond in $\Gamma$ to configurations in which the robot that is not at a pole or vertex is positioned at one of the two innermost semicircles opposite to the robot at the pole. We show sample positions of robots in the zigzag circle in figure \ref{halftwo}. \begin{figure}[H] \caption{Example of zigzag circle positions in $\Gamma$} \centering \label{halftwo} \includegraphics[height=4cm]{twounit} \end{figure} Once that the states are nodes, the idea of our algorithm will be to move robots from a node to another following the zigzag circle in counterclockwise direction. First we move the initial and final states $P_i^*$ and $P_f^*$ in N to initial and final nodes ${CN}_i$ and ${CN}_f$ following shortest path or counterclockwise shortest path as described before. As a result of this step, the states are nodes in the network $N$. Next, we move counterclockwise in zigzag circle from $CN_i$ to $CN_f$, which is the fundamental step of our algorithm. Finally, we reverse the motion from $CN_f$ to $P_f^* $. \begin{alg}\label{N} Therefore, the algorithm in the network $N$ is as follows. \begin{enumerate} \item {\textbf{First Step}} If $P_i^*$ is a cross state, move shortest path to initial chain node ${CN}_i$. If it is a diagonal state, move counterclockwise to ${CN}_i$. If $P_i^*$ is a node, stay motionless. Do the same with the final state to obtain ${CN}_f$. \item { \textbf{Second Step}} Move from ${CN}_i$ to ${CN}_f$ following the zigzag circle counterclockwise. If ${CN}_i={CN}_f$, stay motionless. \item{ \textbf{Third Step}} Reverse the movement in first step to obtain $P_f^*$. \end{enumerate} \end{alg} \begin{alg} When transitioning to the chain $C$, we obtain the following motion planning algorithm: \begin{enumerate} \item {\textbf{First Step}} If $P_i^*$ is on a border circle, move shortest path to initial chain node ${CN}_i$. Otherwise, move counterclockwise to ${CN}_i$. Do the same with the final state to obtain ${CN}_f$. \item { \textbf{Second Step}} Move the robots from ${CN}_i$ to ${CN}_f$ counterclockwise through exterior circles in the chain $C$. If ${CN}_i={CN}_f$, stay motionless. \item{ \textbf{Third Step}} Reverse the movement in first step to move back from ${CN}_f$ to $P_f^*$ . \end{enumerate} \end{alg} We can extend the range of the algorithm in the network and chain to all sets of points in the configuration space $X$ by adding at the beginning and end, the steps given by the traces of the homotopy. \begin{alg} Hence, the algorithm in the configuration space $X$ is: \begin{enumerate} \item {\textbf{Preliminary Step}} Move from $P_i$ to $P_i^*$ following the traces of the homotopy. Do the same to move from $P_f$ to $P_f^*$. \item { \textbf{Main Step}} Move from $P_i^*$ to $P_f^*$ following the above algorithm \ref{N} described in $N$. \item{ \textbf{Final Step}} Reverse the movement in preliminary step to move from $P_f^*$ to $P_f$. \end{enumerate} \end{alg} \subsection{Algorithm in the physical space} We deduce now the instructions in the physical space $\Gamma$. The goal will be first to move the robots such that they will be in a network position, then to translate the algorithm in N to the physical space. The movement determined by the traces of the homotopy is translated to the physical space as follows: if the robots are in the same circle, move them away from each other until they reach an antipodal position and if they are in different circles, move them until one reaches a pole position. In both cases ratio of the robots' speeds are given by the slopes of the homotopy traces shown in figure \ref{traces}. Once that initial and final positions are retracted to the network, we describe the movement within the network. The first step is to move any point in the network to a node. Then the movement will proceed between nodes. The fundamental observation here is that the counterclockwise movement following the zigzag circle in the chain $C$ restricts the movement in the physical space as shown in figure \ref{halftwo}. Recall that states in the network can be described as positions in which at least one robot is at a pole if the robots are in different circles and antipodal positions if the robots are in the same circle. If the robots are not already at a node, move the robot that is not at a pole to the pole following the shortest path if they are at different circles and move the robots simultaneously counterclockwise until one arrives at the vertex and the other at a pole if they are in the same circle. \begin{defi} We will say that the two robots are in a {\em pole-pole} position in $\Gamma$ if they are both at poles. Observe that these positions correspond to cross center states in the network $N$. \end{defi} \begin{defi} We will say that the two robots are in a {\em pole-vertex} position in $\Gamma$ if one is at a pole and another is at the vertex. Observe that these positions correspond to j-states in the network $N$. \end{defi} Therefore, all nodes in the network can be described in the physical space as pole-pole or pole-vertex positions. Now we will describe the movement in the physical space between these positions following the counterclockwise direction in the zigzag circle. We will call {\em allowed semicircles} to the two innermost semicircles opposite to the stationary robot as shown in figure \ref{halftwo}. The following movements $m_{VP}$ and $m_{PV}$ describe the way to exit a pole-vertex or a pole-pole position. \begin{enumerate} \item[$m_{VP}$] From pole-vertex to contiguous pole-pole: Move the robot that is at the vertex counterclockwise in the allowed semicircles until it reaches the pole. \item[$m_{PV}$] From pole-pole to contiguous pole-vertex: Move the only robot that can move counterclockwise in the allowed semicircles until it reaches the vertex. \end{enumerate} \begin{defi} A {\em zigzag movement from a pole-vertex to a pole-pole position} is a series of concatenated movements $m_{VP}m_{PV}m_{VP}\cdots m_{VP}$ as before where the first movement originates in the given pole-vertex position and the last movement finished at the given pole-pole position. Similarly, a {\em zigzag movement from a pole-pole to a pole-vertex position} is a series of concatenated movements $m_{PV}m_{VP}\cdots m_{PV}$. \end{defi} \begin{alg}\label{physicalN} The algorithm for network positions is as follows. \begin{enumerate} \item {\textbf{First Step}} If the two robots are at a pole-pole or pole-vertex position, stay motionless. Otherwise, if the robots are at different circles, move the robot that is not at a pole to the pole following the shortest path. If they are in the same circle, move the robots simultaneously counterclockwise until one arrives at the vertex and the other at a pole. Do the same for the final positions. Let us call {\em initial pole position} and {\em final pole position} the output of this step. \item{ \textbf{Second Step}} Move from the initial pole position to the final one following the zigzag movement. \item{ \textbf{Third Step}} Reverse the movement in first step to go from the final pole position to the final position in the network. \end{enumerate} \end{alg} \begin{alg} To extend the previous algorithm to all the possible positions in the physical space, we add the preliminary and final steps given by the traces of the homotopy. \begin{enumerate} \item {\textbf{Preliminary Step}} If the initial position of the robots are in the same circle, move them away from each other until they reach an antipodal position and if they are in different circles, move them until one reaches a pole position. Do the same with the final position. Let us call {\em initial network position} and {\em final network position} the output of this step \item { \textbf{Main Step}} Move from the initial to the final network position as in algorithm \ref{physicalN}. \item{ \textbf{Final Step}} Reverse the movement in preliminary step to move from the final network position to the final position. \end{enumerate} \end{alg} The above algorithm is discontinuous: if the initial or final configuration is a node, then a small perturbation of $P$ may lead to a different motion. Note that if, for instance, we restrict the algorithm to the states $P_i$ and $P_f$ that are not nodes the algorithm is continuous here. We previously proved that $TC(X)$ is 3. Our objective then will be to exhibit the three domains of continuity. We will restrict the algorithm to the pairs in the following three regions $U'$, $V'$, and $W'$ of the Cartesian product $X\times X$. The first region $U'$ is the set of points $P_i$ and $P_f$, such that none of them is a node, $$U'=\{(P_i, P_f) / P_i\not \in CN, P_f\notin CN \}.$$ The second region $V'$ consists of the pair of points, initial and final, such that one of them is a node and the other is not, $$V'=\{(P_i, P_f) / (P_i\not \in CN, P_f\in CN) \mbox{ or } (P_i\in CN, P_f\not\in CN) \}.$$ The third region $W'$ covers the rest of the Cartesian product, $$W'=\{(P_i, P_f) / P_i\in CN, P_f\in CN\} $$ where both initial and final points are nodes. Let $U$, $V$, and $W$ be small open neighborhoods of $U'$, $V'$, and $W'$ respectively. These are our domains of continuity. \subsubsection{Sample case} Now, we will show how our motion planning algorithm works in a sample case. \begin{figure}[H] \caption{Preliminary Step in $X$: $P_i\rightarrow P_i^*$, $P_f\rightarrow P_f^*$} \centering \includegraphics[height=6cm]{preliminary1} \end{figure} \begin{figure}[H] \caption{Preliminary Step in $\Gamma$} \centering \includegraphics[height= 5cm]{preliminaryG} \end{figure} \begin{figure}[H] \caption{First Step in $N$ and $C$: $P_i^*\rightarrow {CN}_i$, $P_f^*\rightarrow {CN}_f$} \centering \includegraphics[height=6 cm]{firststep1} \end{figure} \begin{figure}[H] \caption{First Step in $\Gamma$} \centering \includegraphics[height=5cm]{firststepgma} \end{figure} \begin{center} \begin{figure}[H] \caption{Second Step in $N$ and $C$: Move from ${CN}_i$ to ${CN}_f$} \includegraphics[height=6cm]{secondstep1} \includegraphics[height=6cm]{secondstep2-2a} \includegraphics[height=6cm]{secondstep3b} \end{figure} \end{center} \begin{center} \begin{figure}[H] \includegraphics[height=6cm]{secondstep4} \includegraphics[height=6cm]{secondstep5} \includegraphics[height=6cm]{secondstep6c} \end{figure} \end{center} \begin{center} \begin{figure}[H] \caption{Second Step in $\Gamma$} \includegraphics[height=4cm]{secondstepGamma} \includegraphics[height=4cm]{secondstep2Gamma} \includegraphics[height=4cm]{secondstep3Gamma}\\ \includegraphics[height=4cm]{secondstep4Gamma} \includegraphics[height=4cm]{second5Ga} \includegraphics[height=4cm]{secondstep6Gamma} \end{figure} \end{center} \begin{center} \begin{figure}[H] \caption{Third Step in $N$ and $C$: $ {CN}_f \rightarrow P_f^*$} \centering \includegraphics[height=6cm]{thirdstep1d} \end{figure} \end{center} \begin{center} \begin{figure}[H] \caption{Third Step in $\Gamma$} \centering \includegraphics[height=5cm]{thirdstepGamma} \end{figure} \end{center} \begin{figure}[H] \caption{Final Step in $N$ and $C$: ${CN}_f\rightarrow P_{f}^*$} \centering \includegraphics[height=6cm]{finalone} \end{figure} \begin{figure}[H] \caption{Final Step in $\Gamma$} \centering \includegraphics[height=5cm]{finalstepinGamma} \end{figure}
{'timestamp': '2020-10-13T02:25:32', 'yymm': '2010', 'arxiv_id': '2010.05339', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05339'}
arxiv
\section{Introduction} The goal of quality estimation (QE) systems is to determine the quality of a translation without having access to a reference translation. This makes it very useful in translation workflows where it can be used to determine whether an automatically translated sentence is good enough to be used for a given purpose, or if it needs to be shown to a human translator for translation from scratch or postediting \cite{kepler-etal-2019-openkiwi}. Quality estimation can be done at different levels: document level, sentence level and word level \cite{ive-etal-2018-deepquest}. This paper presents TransQuest\xspace, a sentence-level quality estimation framework which is the winning solution in all the language pairs in the WMT 2020 Sentence-Level Direct Assessment shared task \cite{specia2020findings}. In the past, high preforming quality estimation systems such as QuEst \cite{specia-etal-2013-quest} and QuEst++ \cite{specia-etal-2015-multi} were heavily dependent on linguistic processing and feature engineering. These features were fed into traditional machine-learning algorithms like support vector regression and randomised decision trees \cite{specia-etal-2013-quest}, which then determined the quality of a translation. Even though, these approaches provide good results, they are no longer the state of the art, being replaced in recent years by neural-based QE systems which usually rely on little or no linguistic processing. For example the best-performing system at the WMT 2017 shared task on QE was \textsc{POSTECH}, which is purely neural and does not rely on feature engineering at all \cite{kim-etal-2017-predictor}. In order to achieve high results, approaches such as \textsc{POSTECH} require extensive pre-training, which means they depend on large parallel data and are computationally intensive \cite{ive-etal-2018-deepquest}. TransQuest\xspace, our QE framework removes this dependency on large parallel data by using crosslingual embeddings \cite{transquest:2020} that are already fine-tuned to reflect properties between languages \cite{10.1613/jair.1.11640}. \citet{transquest:2020} show that by using them, TransQuest eases the burden of having complex neural network architectures, which in turn entails a reduction of the computational resources. That paper also shows that TransQuest performs well in transfer learning settings where it can be trained on language pairs for which we have resources and applied successfully on less resourced language pairs. The remainder of the paper is structured as follows. The dataset used in the competition is briefly discussed in Section \ref{sec:datasets}. In Section \ref{sec:methodology} we present the TransQuest\xspace framework and the methodology employed to train it. This is followed by the evaluation results and their discussion in Section \ref{sec:evaluation}. The paper finishes with conclusions and ideas for future research directions. \section{Dataset} \label{sec:datasets} The dataset for the Sentence-Level Direct Assessment shared task is composed of data extracted from Wikipedia for six language pairs, consisting of high-resource languages English-German (En-De) and English-Chinese (En-Zh), medium-resource languages Romanian-English (Ro-En) and Estonian-English (Et-En), and low-resource languages Sinhala-English (Si-En) and Nepalese-English (Ne-En), as well as a a Russian-English (Ru-En) dataset which combines articles from Wikipedia and Reddit \cite{specia2020findings}. Each language pair has 7,000 sentence pairs in the training set, 1,000 sentence pairs in the development set and another 1,000 sentence pairs in the testing set. Each translation was rated with a score between 0 and 100 according to the perceived translation quality by at least three translators \cite{fomicheva2020unsupervised}. The DA scores were standardised using the z-score. The quality estimation systems have to predict the mean DA z-scores of the test sentence pairs \cite{specia2020findings}. \section{Methodology} \label{sec:methodology} This section presents the methodology used to develop our quality estimation methods. Our methodology is based on TransQuest\xspace our recently introduced QE framework \cite{transquest:2020}. We first briefly describe the neural network architectures TransQuest proposed, followed by the training details. More details about the framework can be found in \cite{transquest:2020}. \subsection{Neural Network Architectures} \label{sebsec:archi} The \textit{TransQuest\xspace} framework that is used to implement the two architectures described here relies on the XLM-R transformer model \cite{conneau2019unsupervised} to derive the representations of the input sentences \cite{transquest:2020}. The XLM-R transformer model takes a sequence of no more than 512 tokens as input, and outputs the representation of the sequence. The first token of the sequence is always \textsc{[CLS]} which contains the special embedding to represent the whole sequence, followed by embeddings acquired for each word in the sequence. As shown below, proposed neural network architectures of TransQuest can utilise both the embedding for the \textsc{[CLS]} token and the embeddings generated for each word \cite{transquest:2020}. The output of the transformer (or transformers for \textbf{SiameseTransQuest\xspace} described below), is fed into a simple output layer which is used to estimate the quality of translation. The way the XLM-R transformer is used and the output layer are different in the two instantiations of the framework. We describe each of them below. The fact that TransQuest does not rely on a complex output layer makes training its architectures much less computationally intensive than alternative solutions. The \textit{TransQuest\xspace} framework is open-source, which means researchers can easily propose alternative architectures to the ones TransQuest presents \cite{transquest:2020}. Both neural network architectures presented below use the pre-trained XLM-R models released by HuggingFace's model repository \cite{Wolf2019HuggingFacesTS}. There are two versions of the pre-trained XLM-R models named XLM-R-base and XLM-R-large. Both of these XLM-R models cover 104 languages \cite{conneau2019unsupervised}, potentially making it very useful to estimate the translation quality for a large number of language pairs. \textit{TransQuest\xspace} implements two different neural network architectures \cite{transquest:2020} to perform sentence-level translation quality estimation as described below. The architectures are presented in Figure \ref{fig:architectures}. \begin{enumerate} \item \textbf{MonoTransQuest\xspace} (\textbf{MTransQuest\xspace}): The first architecture proposed uses a single XLM-R transformer model and is shown in Figure \ref{fig:transquest_architecture}. The input of this model is a concatenation of the original sentence and its translation, separated by the \textsc{[SEP]} token. TransQuest proposes three pooling strategies for the output of the transformer model: using the output of the \textsc{[CLS]} token (\texttt{CLS}-strategy); computing the mean of all output vectors of the input words (\texttt{MEAN}-strategy); and computing a max-over-time of the output vectors of the input words (\texttt{MAX}-strategy) \cite{transquest:2020}. The output of the pooling strategy is used as the input of a softmax layer that predicts the quality score of the translation. TransQuest used mean-squared-error loss as the objective function \cite{transquest:2020}. Similar to \citet{transquest:2020}, the early experiments we carried out demonstrated that the \texttt{CLS}-strategy leads to better results than the other two strategies for this architecture. Therefore, we used the embedding of the \textsc{[CLS]} token as the input of a softmax layer. \item \textbf{SiameseTransQuest\xspace} (\textbf{STransQuest\xspace}): The second approach proposed in TransQuest relies on the Siamese architecture depicted in Figure \ref{fig:siamese_transquest_architecture} which has shown promising results in monolingual semantic textual similarity tasks \cite{reimers-gurevych-2019-sentence,ranasinghe-etal-2019-semantic}. For this, we fed the original text and the translation into two separate XLM-R transformer models. Similarly to the previous architecture, we experimented with the same three pooling strategies for the outputs of the transformer models \cite{transquest:2020}. TransQuest then calculates the cosine similarity between the two outputs of the pooling strategy. TransQuest used mean-squared-error loss as the objective function. Similar to \citet{transquest:2020} in the initial experiments we carried out with this architecture the \texttt{MEAN}-strategy showed better results than the other two strategies. For this reason, we used the \texttt{MEAN}-strategy for our experiments. Therefore, cosine similarity is calculated between the mean of all output vectors of the input words produced by each transformer. \end{enumerate} \begin{figure*}[ht] \begin{subfigure}[b]{6cm} \centering\includegraphics[width=5cm]{images/Transquest.png} \caption{\textit{MTransQuest\xspace} architecture} \label{fig:transquest_architecture} \end{subfigure} \begin{subfigure}[b]{6cm} \centering\includegraphics[width=10cm]{images/SiameseTransquest.png} \caption{\textit{STransQuest\xspace} Architecture} \label{fig:siamese_transquest_architecture} \end{subfigure} \caption{Two architectures of the \textit{TransQuest\xspace} framework.} \label{fig:architectures} \end{figure*} \subsection{Training Details} \label{subsec:training} We used the same set of configurations suggested in \citet{transquest:2020} for all the language pairs evaluated in this paper in order to ensure consistency between all the languages. This also provides a good starting configuration for researchers who intend to use TransQuest\xspace on a new language pair. In both architectures, we used a batch-size of eight, Adam optimiser with learning rate $2\mathrm{e}{-5}$, and a linear learning rate warm-up over 10\% of the training data. The models were trained using only training data. Furthermore, they were evaluated while training using an evaluation set that had one fifth of the rows in training data. We performed early stopping if the evaluation loss did not improve over ten evaluation rounds. All of the models were trained for three epochs. For some of the experiments, we used an Nvidia Tesla K80 GPU, whilst for others we used an Nvidia Tesla T4 GPU. This was purely based on the availability of the hardware and it was not a methodological decision. \subsection{Implementation Details} \label{subsec:implementation} The TransQuest\xspace framework was implemented using Python 3.7 and PyTorch 1.5.0. To integrate the functionalities of the transformers we used the version 3.0.0 of the HuggingFace's Transformers library. The implemented framework is available on GitHub\footnote{TransQuest\xspace GitHub repository - \url{https://github.com/tharindudr/transQuest}}. \section{Evaluation, Results and Discussion} \label{sec:evaluation} This section presents the evaluation results of our architectures and the fine tuning strategies that can be used to improve the results. We first evaluate the TransQuest\xspace framework with the default setting (Section \ref{subsec:default}). Next we evaluate an ensemble setting of TransQuest\xspace in Section \ref{subsec:ensemble}. We finally assess the performance of TransQuest\xspace with augmented data. We conclude the section with a discussion of the results. The evaluation metric used was the Pearson correlation ($r$) between the predictions and the gold standard from the test set, which is the most commonly used evaluation metric in WMT quality estimation shared tasks \cite{specia-etal-2018-findings,fonseca-etal-2019-findings}. We report the Pearson correlation values that we obtained from CodaLab, the hosting platform of the WMT 2020 QE shared task. As a baseline we compare our results with the performance of OpenKiwi as reported by the task organisers \cite{specia2020findings}. \renewcommand{\arraystretch}{1.2} \begin{table*}[t] \begin{center} \small \begin{tabular}{l l c c c c c c c} \toprule & & \multicolumn{2}{c}{\bf Low-resource} & \multicolumn{3}{c}{\bf Mid-resource} & \multicolumn{2}{c}{\bf High-resource}\\\cmidrule(r){3-4}\cmidrule(lr){5-7}\cmidrule(l){8-9} &{\bf Method} & Si-En & Ne-En & Et-En & Ro-En & Ru-En & En-De & En-Zh\\ \midrule \multirow{2}{*}{\bf I} & MTransQuest\xspace & 0.6525 & 0.7914 & 0.7748 & 0.8982 & 0.7734 & 0.4669 & 0.4779 \\ & STransQuest\xspace & 0.5957 & 0.7081 & 0.6804 & 0.8501 & 0.7126 & 0.3992 & 0.4067 \\ \midrule \multirow{2}{*}{\bf II} & MTransQuest\xspace-base & 0.6412 & 0.7823 & 0.7651 & 0.8715 & 0.7593 & 0.4421 & 0.4593 \\ & STransQuest\xspace-base & 0.5773 & 0.6853 & 0.6692 & 0.8321 & 0.6962 & 0.3832 & 0.3975 \\ \midrule \multirow{2}{*}{\bf III} & MTransQuest\xspace $\otimes$ & 0.6661 & 0.8023 & 0.7876 & 0.8988 & 0.7854 & 0.4862 & 0.4853 \\ & STransQuest\xspace $\otimes$ & 0.6001 & 0.7132 & 0.6901 & 0.8629 & 0.7248 & 0.4096 & 0.4159 \\ \midrule \multirow{2}{*}{\bf IV} & MTransQuest\xspace $\otimes$ - Aug & \textbf{0.6849} & \textbf{0.8222} & \textbf{0.8240} & \textbf{0.9082} & \textbf{0.8082} & \textbf{0.5539} & \textbf{0.5373} \\ & STransQuest\xspace $\otimes$ - Aug & 0.6241 & 0.7354 & 0.7239 & 0.8621 & 0.7458 & 0.4457 & 0.4658 \\ \midrule \multirow{1}{*}{\bf V} & OpenKiwi & 0.3737 & 0.3860 & 0.4770 & 0.6845 & 0.5479 & 0.1455 & 0.1902 \\ \bottomrule \end{tabular} \end{center} \caption{Pearson ($r$) correlation between \textit{TransQuest\xspace} algorithm predictions and human DA judgments. Best results for each language (any method) are marked in bold. Rows I, II, III and IV indicate the different settings of \textit{TransQuest\xspace}, explained in Sections \ref{subsec:default}-\ref{subsec:augmentation}. OpenKiwi baseline results are in Row V.} \label{tab:results:direct_assesement} \end{table*} \subsection{TransQuest\xspace with Default settings} \label{subsec:default} The first evaluation we carried out was for the default configurations of the TransQuest\xspace framework where we used the training set of each language to build a quality estimation model using XLM-R-large transformer model and we evaluated it on a test set from the same language. The results for each language with \textit{default} settings are shown in row I of Table \ref{tab:results:direct_assesement}. The results indicate that both architectures proposed in \textit{TransQuest\xspace} outperform the baseline, OpenKiwi, in all the language pairs. From the two architectures, \textit{MTransQuest\xspace} performs slightly better than \textit{STransQuest\xspace}. As shown in Table \ref{tab:results:direct_assesement}, \textit{MTransQuest\xspace} gained $\approx$ 0.2-0.3 Pearson correlation boost over OpenKiwi in all the language pairs. Additionally, \textit{MTransQuest\xspace} achieves $\approx$ 0.4 Pearson correlation boost over OpenKiwi in the low-resource language pair Ne-En. \subsection{TransQuest\xspace with Ensemble} \label{subsec:ensemble} Transformers have been proven to provide better results when experimented with ensemble techniques \cite{xu2020improving}. In order to improve the results of TransQuest\xspace we too followed an ensemble approach which consisted of two steps. We conducted these steps for both architectures in TransQuest\xspace. \begin{enumerate} \item We train TransQuest\xspace using the pre-trained XLM-R-base transformer model instead of the XLM-R-large transformer model in the TransQuest\xspace default setting. We report the results from the two architectures from this step in row II of Table \ref{tab:results:direct_assesement} as MTransQuest\xspace-base and STransQuest\xspace-base. \item We perform a weighted average ensemble for the output of the default setting and the output we obtained from step 1. We experimented on weights 0.8:0.2, 0.6:0.4, 0.5:0.5 on the output of the default setting and output from the step 1 respectively. Since the results we got from XLM-R-base transformer model are slightly worse than the results we got from default setting we did not consider the weight combinations that gives higher weight to XLM-R-base transformer model results. We obtained best results when we used the weights 0.8:0.2. We report the results from the two architectures from this step in row III of Table \ref{tab:results:direct_assesement} as MTransQuest\xspace $\otimes$ and STransQuest\xspace $\otimes$. \end{enumerate} As shown in Table \ref{tab:results:direct_assesement} both architectures in TransQuest\xspace with ensemble setting gained $\approx$ 0.01-0.02 Pearson correlation boost over the default settings for all the language pairs. \subsection{TransQuest\xspace with Data Augmentation} \label{subsec:augmentation} All of the languages had 7,000 training instances that we used in the above mentioned settings in TransQuest\xspace. To experiment how TransQuest\xspace performs with more data, we trained TransQuest\xspace on a data augmented setting. Alongside the training, development and testing datasets, the shared task organisers also provided the parallel sentences which were used to train the neural machine translation system in each language. In the data augmentation setting, we added the sentence pairs from that neural machine translation system training file to training dataset we used to train TransQuest\xspace. In order to find the best setting for the data augmentation we experimented with adding 1000, 2000, 3000, up to 5000 sentence pairs randomly. Since the ensemble setting performed better than the default setting of TransQuest\xspace, we conducted this data augmentation experiment on the ensemble setting. We assumed that the sentence pairs added from the neural machine translation system training file have maximum translation quality. Up to 2000 sentence pairs the results continued to get better. However, adding more than 2000 sentence pairs did not improve the results. We did not experiment with adding any further than 5000 sentence pairs to the training set since the timeline of the competition was tight. We were also aware that adding more sentence pairs with the maximum translation quality to the training file will make it imbalance and affect the performance of the machine learning models negatively. We report the results from the two architectures from this step in row IV of Table \ref{tab:results:direct_assesement} as MTransQuest\xspace $\otimes$-Aug and STransQuest\xspace $\otimes$-Aug. This setting provided the best results for both architectures in TransQuest\xspace for all of the language pairs. As shown in Table \ref{tab:results:direct_assesement} both architectures in TransQuest\xspace with the data augmentation setting gained $\approx$ 0.01-0.09 Pearson correlation boost over the default settings for all the language pairs. Additionally, \textit{MTransQuest\xspace $\otimes$-Aug} achieves $\approx$ 0.09 Pearson correlation boost over default MTransQuest\xspace in the high-resource language pair En-De. \subsection{Error analysis} \label{sebsec:error} In an attempt to better understand the performance and limitations of \textit{TransQuest\xspace} we carried out an error analysis on the results obtained on Romanian - English and Sinhala - English. The choice of language pairs we analysed was determined by the availability of native speakers to perform this analysis. We focused on the cases where the difference between the predicted score and expected score was the greatest. This included both cases where the predicted score was underestimated and overestimated. Analysis of the results does not reveal very clear patterns. The largest number of errors seem to be caused by the presence of named entities in the source sentences. In some cases these entities are mishandled during the translation. The resulting sentences are usually syntactically correct, but semantically odd. Typical examples are \emph{RO: În urmă explorărilor Căpitanului James Cook, Australia și Noua Zeelandă au devenit ținte ale colonialismului britanic. (As a result of Captain James Cook's explorations, Australia and New Zealand have become the targets of British colonialism.)} - \emph{EN: Captain James Cook, Australia and New Zealand have finally become the targets of British colonialism.} (expected: -1.2360, predicted: 0.2560) and \emph{RO: O altă problemă importantă cu care trupele Antantei au fost obligate să se confrunte a fost malaria. (Another important problem that the Triple Entente troops had to face was malaria.)} - EN: \emph{Another important problem that Antarctic troops had to face was malaria.} (expected: 0.2813, predicted: -0.9050). In the opinion of the authors of this paper, it is debatable whether the expected scores for these two pairs should be so different. Both of them have obvious problems and cannot be clearly understood without reading the source. For this reason, we would expect that both of them have low scores. Instances like this also occur in the training data. As a result of this, it may be that \textit{TransQuest\xspace} learns contradictory information, which in turn leads to errors at the testing stage. A large number of problems are caused by incomplete source sentences or input sentences with noise. For example the pair \emph{RO: thumbright250pxDrapelul cu fâșiile în poziție verticală (The flag with strips in upright position)} - \emph{EN: ghtghtness 250pxDrapel with strips in upright position} has an expected score of 0.0595, but our method predicts -0.9786. Given that only \emph{ghtghtness 250pxDrapel} is wrong in the translation, the predicted score is far too low. In an attempt to see how much this noise influences the result, we run the system with the pair \emph{RO: Drapelul cu fâșiile în poziție verticală} - \emph{EN: Drapel with strips in upright position}. The prediction is 0.42132, which is more in line with our expectations given that one of the words is not translated. Similar to Ro-En, in Si-En the majority of problems seem to be caused by the presence of named entities in the source sentences. For an example in the English translation: \emph{But the disguised Shiv will help them securely establish the statue. } (expected: 1.3618, predicted: -0.008), the correct English translation would be \emph{But the disguised Shividru will help them securely establish the statue.}. Only the named entity \emph{Shividru} is translated incorrectly, therefore the annotators have annotated the translation with a high quality. However TransQuest\xspace fails to identify that. Similar scenarios can be found in English translations \emph{Kamala Devi Chattopadhyay spoke at this meeting, Dr. Ann.} (expected:1.3177, predicted:-0.2999) and \emph{The Warrior Falls are stone's, halting, heraldry and stonework rather than cottages. The cathedral manor is navigable places} (expected:0.1677, predicted:-0.7587). It is clear that the presence of the named entities seem to confuse the algorithm we used, hence it needs to handle named entities in a proper way. \section{Conclusion} In this paper we evaluated different settings of \textit{TransQuest\xspace} in sentence-level direct quality assessment. We showed that ensemble results with XLM-R-base and XLM-R-large with data augmentation techniques can improve the performance of TransQuest\xspace framework. The official results of the competition show that \textit{TransQuest\xspace} won the first place in all the language pairs in Sentence-Level Direct Assessment task. \textit{TransQuest\xspace} is the sole winner in En-Zh, Ne-En and Ru-En language pairs and the multilingual track. For the other language pairs (En-De, Ro-En, Et-En and Si-En) it shares the first place with another system, whose results are not statistically different from ours. The full results of the shared task can be seen in \citet{specia2020findings}. In the future, we plan to experiment more with the data augmentation settings. We are interested in augmenting the training file with semantically similar sentences to the test set rather than augmenting with random sentence pairs as we did in this paper. As shown in the error analysis in Section \ref{sebsec:error} the future releases of the framework need to handle named entities properly. We also hope to implement \textit{TransQuest\xspace} in document level quality estimation too.
{'timestamp': '2020-10-13T02:24:44', 'yymm': '2010', 'arxiv_id': '2010.05318', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05318'}
arxiv
\section{Introduction} \label{sec:intro} In the last few years, natural language understanding has made considerable progress, driven largely by the availability of large-scale datasets and advances in neural modeling \cite{elmo,bert}. At the center of this progress has been natural language inference (NLI), which focuses on the problem of deciding whether two statements are connected via an entailment or a contradiction. NLI profited immensely from new datasets such as the Stanford NLI (SNLI, \citet{snli}) and Multi-Genre NLI (MNLI, \citet{mnli}) datasets. % However, as often the case, this progress has centered around the English language given that the most well-known datasets are limited to English. % Efforts to build comparable datasets for other languages have largely focused on (automatically) translating existing English NLI datasets \cite{mehdad2011,xnli}. But this approach comes with its own issues (see section~\ref{sec:related}). { \renewcommand{\arraystretch}{1.5} % \begin{CJK}{UTF8}{gbsn} \begin{table*}[t] {\footnotesize \begin{tabular}{p{7cm}p{1.3cm}p{2cm}p{4cm}} \toprule Premise & Genre\newline \texttt{Level} & \textbf{Majority label} \newline All labels & Hypothesis \\ \midrule 但是不光是中国,日本,整个东亚文化都有这个特点就是被权力影响很深 \newline But not only China and Japan, the entire East Asian culture has this feature, that is it is deeply influenced by the power. & TV\newline \texttt{medium} & \textbf{Entailment}\newline E E E E E & 有超过两个东亚国家有这个特点\newline More than two East Asian countries have this feature. \\ 完善加工贸易政策体\newline (We need to) perfect our work and trade policies. & GOV\newline \texttt{easy} & \textbf{Entailment}\newline E E E E E & 贸易政策体系还有不足之处\newline (Our) trade policies still need to be improved. \\ 咖啡馆里面对面坐的年轻男女也是上一代的故事,她已是过来人了\newline Stories of young couples sitting face-to-face in a cafe is already something from the last generation. She has gone through all that. & LIT\newline \texttt{medium} & \textbf{Contradiction}\newline C C C N N & 男人和女人是背对背坐着的\newline The man and the woman are sitting back-to-back. \\ 今天,这一受人关注的会议终于在波恩举行\newline Today, this conference which has drawn much attention finally took place in Bonn. & NEWS\newline \texttt{easy} & \textbf{Neutral}\newline N N N N C & 这一会议原定于昨天举行\newline This conferences was scheduled to be held yesterday. \\ 嗯,今天星期六我们这儿,嗯哼.\newline En, it's Saturday today in our place, yeah. & PHONE\newline \texttt{hard} & \textbf{Contradiction}\newline C C C C C & 昨天是星期天\newline It was Sunday yesterday. \\ \bottomrule \end{tabular} } \caption{Examples from the \textsc{MultiConstraint} elicitation of our Chinese NLI dataset, one from each of the five text genres. \texttt{easy}: 1st hypothesis the annotator wrote for that particular premise and label; \texttt{medium}: 2nd hypothesis; \texttt{hard}: 3rd hypothesis. \textbf{Bold} label shows the majority vote from the annotators. \label{tab:ocnli:examples} } \end{table*} \end{CJK} } % To overcome these shortcomings and contribute to ongoing progress in Chinese NLU, we present the first large-scale NLI dataset for Chinese called the \emph{Original Chinese Natural Language Inference} dataset (OCNLI). Unlike previous approaches, we rely entirely on original Chinese sources and use native speakers of Chinese with special expertise in linguistics and language studies for creating hypotheses and for annotation. Our % dataset contains $\sim$56,000 annotated premise-hypothesis pairs and follows a similar procedure of data collection to the English MNLI. Following MNLI, the premises in these sentence pairs are drawn from multiple genres (5 in total), including both written and spoken Chinese (see Table~\ref{tab:ocnli:examples} for examples). To ensure annotation quality and consistency, we closely mimic MNLI's original annotation protocols for monitoring annotator performance. We find that our trained annotators have high agreement on label prediction (with $\sim$98\% agreement based on a 3-vote consensus). To our knowledge, this dataset constitutes the first large-scale NLI dataset for Chinese that does not rely on automatic translation. Additionally, we establish baseline results based on a standard set of NLI models \cite{chen2017lstm} tailored to Chinese, as well as new pre-trained Chinese transformer models \cite{cui2019pretraining}. We find that our strongest model, based on RoBERTa \cite{roberta}, performs far behind expert human performance ($\sim$78\% vs.\ % $\sim$90\% accuracy on our test data). These results show that the dataset is challenging without using special filtering that has accompanied many recent NLI datasets \cite{le2020adversarial}. \paragraph{Contributions of this paper:} 1) We introduce a new, high quality dataset for NLI for Chinese, based on Chinese data sources and expert annotators; % 2) We provide strong baseline models for the task, and establish the difficulty of our task through experiments with recent pre-trained transformers. 3) We also demonstrate the benefit of naturally annotated NLI data by comparing performance with large-scale automatically translated datasets. \section{Related Work}\label{sec:related} Natural language inference (NLI), or recognizing textual entailment (RTE), is a long-standing task in NLP. Since we cannot cover the whole field, we focus on existing datasets and current systems. \paragraph{Data:} To date, there exists numerous datasets for English, ranging from smaller/more linguistics oriented resources such as FraCaS \citep{fracas}, to larger ones like the RTE challenges \citep{Dagan} and SICK \citep{SICK}. Perhaps the most influential are the two large-scale, human-elicited datasets: the Stanford Natural Language Inference Corpus (SNLI) \citep{snli}, whose premises are taken from image captions, and the Multi-Genre Natural Language Inference Corpus (MNLI) \citep{mnli}, whose premises are from texts in 10 different genres. Both are built by collecting premises from pre-defined text, then having annotators come up with possible hypotheses and inference labels, which is the procedure we also employ in our work. These large corpora have been used as part of larger benchmark sets, e.g., GLUE \citep{glue}, and have proven useful for problems beyond NLI, such as sentence representation and transfer learning \citep{infersent,subramanian2018learning,reimers2019sentence}, automated question-answering \citep{khot2018scitail,trivedi2019repurposing} and model probing \cite{warstadt2019investigating,probing2020,geiger2020modular,jeretic2020natural}. % \added{The most recent English corpus Adversarial NLI \citep{anli} uses Human-And-Model-in-the-Loop Enabled Training (HAMLET) method for data collection. Their annotation method requires an existing NLI corpus to train the model during annotation, which is not possible for Chinese at the moment, as there exists no high-quality Chinese data. } \added{In fact,} there has been relatively little work on developing large-scale human-annotated resources for languages other than English. Some NLI datasets exist in other languages, e.g., \citet{assin1} and \citet{assin2} for Portuguese, \citet{hayashibe2020japanese} for Japanese, and \citet{amirkhani2020farstail} for Persian, but none of them have human elicited sentence pairs. Efforts have largely focused on automatic translation of existing English resources \cite{mehdad2011}, sometimes coupled with smaller-scale hand annotation by native speakers \cite{negri2011divide,agic2017baselines}. This is also true for some of the datasets included in the recent Chinese NLU benchmark CLUE \cite{clue} and for XNLI \cite{xnli}, a multilingual NLI dataset covering 15 languages including Chinese. \begin{table}[t] \centering \begin{CJK}{UTF8}{gbsn} {\footnotesize \begin{tabular}{ p{5cm} | p{1.7cm} } \multicolumn{1}{c}{\textbf{Premise}} & \multicolumn{1}{c}{\textbf{Hypothesis}} \\ \hline a. \textcolor{darkgray}{Louisa May Alcott和Nathaniel Hawthorne 住在Pinckney街道,而 那个被Oliver Wendell Holmes称为 “晴天街道 的Beacon Street街道住着有些喜欢自吹自擂的历史学家 William Prescott} \newline \emph{\textbf{Eng.:} Louisa May Alcott and Nathaniel Hawthorne lived on Pinckney street, but on Beacon Street street, which is named ``Sunny Street by Oliver Wendell Holmes, lived the bragging historian William Prescott. [sic]} & \textcolor{darkgray}{Hawthorne住在Main Street上} \newline \emph{Eng.: Hawthorne lived on Main Street}. \\ \hline b. \textcolor{darkgray}{运行 Slient,运行Deep,运行答案} \newline \emph{Eng.: run Slient, run Deep, run answer. [sic]} & \textcolor{darkgray}{悄悄的逃走} \newline \emph{\textbf{Eng.:} secretly escape.} \\ \hline \end{tabular} } \end{CJK} \caption{Examples from crowd-translated XNLI development set \cite{xnli}, showing problems of \emph{translationese} (top) and poor translation quality (bottom).} \label{fig:first_example} \end{table} While automatically translated data have proven to be useful in many contexts, such as cross-lingual representation learning \cite{siddhant2019evaluating}, there are well-known issues, especially when used in place of human annotated, quality controlled data. One issue concerns limitations in the quality of automatic translations, resulting in incorrect or unintelligible sentences (e.g., see Table~\ref{fig:first_example}b). But even if the translations are correct, they suffer from ``translationese", resulting in unnatural language, since lexical and syntactic choices are copied from the source language even though they are untypical for the target language \citep{koppel2011ACLtranslationese,stylevar2018,translationese-chinese}. A related issue is that a translation approach also copies the cultural context of the source language, such as an overemphasis on Western themes or cultural situations. The latter two issues are shown in Table~\ref{fig:first_example}a, % where many English names are directly carried over into the Chinese translation, along with aspects of English syntax, such as long relative clauses, which are common in English but dispreferred in Chinese \cite{lin2011chinese}. \paragraph{Systems:} \added{As inference is closely related to logic, there has always been a line of research building logic-based or logic-and-machine-learning hybrid models for NLI/RTE problems \citep[e.g.][]{MacCartney,Abzianidze15,martinez2017,YanakaMMB18,monalog}. } However, in recent years, large datasets such as SNLI and MNLI have been almost exclusively approached by deep learning models. For examples, several transformer architectures achieve impressive results on MNLI, with current state-of-the-art T5 \cite{2019t5} reaching 92.1/91.9\% accuracy on the matched and mismatched sets. Re-implementations of these transformer models for Chinese have led to similar successes on related tasks. For example, \citet{cui2019pretraining} report that a large RoBERTa model \cite{roberta}, pre-trained with whole-word masking, achieves the highest accuracy (81.2\%) among their transformer models on XNLI. In the CLUE benchmark \cite{clue}, the same RoBERTa model also achieves the highest aggregated score from eight tasks. We will use this model to establish baselines on our new dataset. \paragraph{\added{Biases:}} The advances in dataset creation have led to an increased awareness of systematic biases in existing datasets \cite{gururangan2018annotation}, as measured through \emph{partial-input baselines}, e.g., the \emph{hypothesis-only} baselines explored in \citet{poliak2018hypothesis} where a model can achieve high accuracy by only looking at the hypothesis and ignoring the premise completely \added{(see also \citet{feng2019misleading})}. These biases have been mainly associated with the annotators (crowd workers in MNLI's case) who use certain strategies to form hypotheses of a specific label, e.g., adding a negator for contradictions. There have been several recent attempts to reduce such biases \citep{belinkov2019don,sakaguchi2019winogrande,le2020adversarial,anli}. \added{There has also been a large body of work using probing datasets/tasks to stress-test NLI models trained on datasets such as SNLI and MNLI, in order to expose the weaknesses and biases in either the models or the data \citep{dasgupta2018evaluating,naik2018stress,hans}. } For this work, we closely monitor the hypothesis-only and other biases but leave systematic filtering/bias-reduction/stress-testing for future work. \added{An interesting future challenge will involve seeing how such techniques, which focus exclusively on English, transfer to other languages such as Chinese.} { \renewcommand{\arraystretch}{1.5} % \begin{table*}[t] \centering \small \begin{tabular}{l|p{4cm}|l|l|l|l}\toprule \multirow{2}{*}{Subsets} & \multirow{2}{*}{Instructions} & \multicolumn{4}{c}{\# Pairs / Mean length of hypothesis \textit{H} in characters} \\\cmidrule{3-6} & & Total & \texttt{easy} & \texttt{medium} & \texttt{hard} \\\hline \textsc{Single} & same as MNLI; one \textit{H} per label & 11,986 / 10.9 & n.a. & n.a. & n.a. \\ \textsc{Multi} & three \textit{H}s per label & 12,328 / 10.4 & 4,836 / 9.9 & 4,621 / 10.6 & 2,871 / 11.0 \\ \textsc{MultiEncourage} & \textsc{Multi} + encouraging annotators to use fewer negators and write more diverse hypotheses & 16,584 / 12.2 & 6,263 / 11.5 & 6,092 / 12.5 & 4,229 / 12.7 \\ \textsc{MultiConstraint} & \textsc{Multi} + constraints on the negators used in contradictions & 15,627 / 12.0 & 5,668 / 11.6 & 5,599 / 12.2 & 4,360 / 12.4 \\\hline total & & 56,486 / 11.5 & & & \\ \bottomrule \end{tabular} \caption{Information on the four subsets of data collected. Premises in all subsets are drawn from the same pool of text from five genres. \texttt{easy/medium/hard} refers to the 1st/2nd/3rd hypothesis written for the same premise and inference label. Number of pairs in the \texttt{hard} condition is smaller because not all premises and all labels have a third hypothesis. See section \ref{sec:hypo:generation} for details of the subsets. \label{tab:4-batch}} \end{table*} } % \section{Creating OCNLI} Here, we describe our data collection and annotation procedures. Following the standard definition of NLI \cite{dagan-etal-2006-direct}, our data consists of ordered pairs of sentences, one \textit{premise} sentence and one \textit{hypothesis} sentence, annotated with one of three labels: % Entailment, Contradiction, or Neutral (see examples in Table~\ref{tab:ocnli:examples}). Following the strategy that \citet{mnli} established for MNLI, we start by selecting a set of premises from a collection of multi-genre Chinese texts, see Section~\ref{sec:select:premise}. We then elicit hypothesis annotations based on these premises using expert annotators (Section~\ref{sec:hypo:generation}). We develop novel strategies to ensure that we elicit diverse hypotheses. % We then describe our verification procedure in Section~\ref{sec:verification}. \subsection{Selecting the Premises \label{sec:select:premise}} Our premises are drawn from the following five text genres: government documents, news, literature, TV talk shows, and telephone conversations. The genres were chosen to ascertain varying degrees of formality, and they were collected from different primary Chinese sources. The government documents are taken from annual Chinese government work reports\footnote{\urlstyle{rm}\url{http://www.gov.cn/guowuyuan/baogao.htm}, last visited 4/21/2020, same below.}. The news data are extracted from the news portion of the Lancaster Corpus of Mandarin Chinese \citep{LCMC}. The data in the literature genre are from two contemporary Chinese novels\footnote{\textit{Ground Covered with Chicken Features} by Liu Zhenyun, \textit{Song of Everlasting Sorrow} by Wang Anyi.}, and the TV talk show data and telephone conversations are extracted from transcripts of the talk show \textit{Behind the headlines with Wentao}\footnote{\urlstyle{rm}\url{http://phtv.ifeng.com/listpage/677/1/list.shtml}.} and the Chinese Callhome transcripts \citep{callhome-zh}. As for pre-processing, annotation symbols in the Callhome transcripts were removed and we limited our premise selection to sentences containing 8 to 50 characters. \subsection{Hypothesis Generation \label{sec:hypo:generation}} One issue with the existing data collection strategies in MNLI is that humans tend to use the simplest strategies to create the hypotheses, such as negating a sentence to create a contradiction. This makes the problem unrealistically easy. To create more realistic, and thus more challenging data, we propose a new hypothesis elicitation method called \textit{multi-hypothesis} elicitation. We collect four sets of inference pairs and compare the proposed method with the MNLI annotation method, where a single annotator creates an entailed sentence, a neutral sentence and a contradictory sentence given a premise (Condition: \textsc{Single}). \paragraph{Multi-hypothesis elicitation} In this newly proposed setting, we ask the writer to produce \textit{three} sentences per label, resulting in three entailments, three neutrals and three contradictions for each premise (Condition: \textsc{Multi}). I.e. we obtain a total of nine hypotheses if the writer is able to come up with that many inferences, which is indeed the case for most premises in our experiment. Our hypothesis is that by asking them to produce three sentences for each type of inference, we push them to think beyond the easiest case. We call the 1st, 2nd and 3rd hypothesis by an annotator per label \texttt{easy}, \texttt{medium} and \texttt{hard} respectively, with the assumption that they start with the easiest inferences and then move on to harder ones. First experiments show that \textsc{Multi} is more challenging than \textsc{Single}, and at the same time, inter-annotator agreement is slightly higher than for \textsc{Single} (see section~\ref{sec:verification}). \begin{CJK}{UTF8}{gbsn} However, we also found that \textsc{Multi} introduces more hypothesis-only bias. Especially in contradictions, negators such as 没有 (``no/not'') stood out as cues, similar to what had been reported in SNLI and MNLI \citep{poliak2018hypothesis,gururangan2018annotation,pavlick2019inherent}. Therefore we experiment with two additional strategies to control the bias, resulting in \textsc{MultiEncourage} (\textit{encourage} the annotators to write more diverse hypothesis) and \textsc{MultiConstraint} (put \textit{constraints} on what they can produce), which will be explained in detail below. These four strategies result in four different subsets. Table~\ref{tab:4-batch} gives a summary of these subsets. \end{CJK} \paragraph{Instructions for hypothesis generation} The basis of our instructions are very similar to those for MNLI, but we modified them for each setting: \paragraph{\textsc{Single}} We asked the writer to produce one hypothesis per label, same as MNLI\footnote{See Appendix \ref{sec:instructions} for the complete instructions.}. \paragraph{\textsc{Multi}} Instructions are the same except that we ask for three hypotheses per label. \begin{table*}[t] \centering \small \begin{tabular}{l|rrr|rrrr} \toprule & \bf SNLI$^{\dagger}$ & \bf MNLI$^{\dagger}$ & \bf XNLI$^{\dagger}$ & \multicolumn{4}{c}{\bf OCNLI} \\ & & & \bf & \bf \textsc{Single} &\bf \textsc{Multi} & \bf \textsc{MultiEnc} &\bf \textsc{MultiCon} \\\midrule \# pairs in total & 570,152 & 432,702 & 7,500 & 11,986 & 12,328 & 16,584 & 15,627 \\ \# pairs relabeled & 56,941 & 40,000 & 7,500 & 1,919 & 1,994 & 3,000 & 3,000 \\ \% relabeled & 10.0\% & 9.2\% & 100.0\% & 16.0\% & 16.2\% & 18.1\% & 19.2\% \\\midrule 5 labels agree (unanimous) & 58.3\% & 58.2\% & na & 62.1\% & 63.5\% & 57.2\% & 57.6\% \\ 4+ labels agree & na & na & na & 82.2\% & 84.8\% & 82.0\% & 80.8\% \\ 3+ labels agree & \textbf{98.0\%} & \textbf{98.2\%} & \textbf{93.0\%} & \textbf{98.6}\% & \textbf{98.8\%} & \textbf{98.7\%} & \textbf{98.3\%} \\\midrule Individual label $=$ gold label & 89.0\% & 88.7\% & na & 88.1\% & 88.9\% & 87.0\% & 86.7\% \\ Individual label $=$ author's label & 85.8\% & 85.2\% & na & 81.8\% & 82.3\% & 80.2\% & 79.7\% \\\midrule Gold label $=$ author's label & 91.2\% & 92.6\% & na & 89.8\% & 89.6\% & 89.6\% & 88.2\% \\ Gold label $\ne$ author's label & 6.8\% & 5.6\% & na & 8.8\% & 9.2\% & 9.0\% & 10.1\% \\ No gold label (no 3 labels match) & 2.0\% & 1.8\% & na & 1.4\% & 1.2\% & 1.3\% & 1.7\% \\ \bottomrule \end{tabular} \caption{Results from labeling experiments for the four subsets. \textsc{MultiEnc}: \textsc{MultiEncourage}; \textsc{MultiCon}: \textsc{MultiConstraint}. $^{\dagger}$ = numbers for SNLI, MNLI, XNLI are copied from the original papers \protect \citep{snli,mnli,xnli}. For XNLI, the numbers are for the English portion of the dataset, which is the only language that has been relabelled. \label{tab:labelling}} \end{table*} \paragraph{\textsc{MultiEncourage}} We \textit{encouraged} the writers to write high-quality hypotheses by telling them explicitly which types of data we are looking for, and promised a monetary bonus to those who met our criteria after we examined their hypotheses. Among our criteria are: 1) we are interested in \textit{diverse} ways of making inferences, and 2) we are looking for contradictions that do \textit{not} contain a negator. \paragraph{\textsc{MultiConstraint}} We put \textit{constraints} on hypothesis generation by specifying that \textit{only one out of the three contradictions can contain a negator}, and that we would randomly check the produced hypothesis, with violations of the constraint resulting in lower payment. We also provided extra examples in the instructions to demonstrate contradictions without negators. These examples are drawn from the hypotheses collected from prior data. \added{We are also aware of other potential biases or heuristics in human-elicited NLI data such as the lexical overlap heuristic \citep{hans}. Thus in all our instructions, we made explicit to the annotators that no hypothesis should overlap more than 70\% with the premise. However, examining how prevalent such heuristics are in our data requires constructing new probing datasets for Chinese, which is beyond the scope of this paper. } \paragraph{Annotators} We hired 145 undergraduate and graduate students from several top-tier Chinese universities to produce hypotheses. All of the annotators (\textit{writers}) are native speakers of Chinese and are majoring in Chinese or other languages. They were paid roughly 0.3 RMB (0.042 USD) per P-H pair. No single annotator produced an excessive amount of data to avoid annotator-bias \added{(for a discussion of this, see \citet{annotator2019Geva})}. \subsection{Data Verification \label{sec:verification}} Following SNLI and MNLI, we perform data verification, where each premise-hypothesis pair is assigned a label by four independent annotators (\textit{labelers}). Together with the original label assigned by the annotator, each pair has five labels. We then use the majority vote as the gold label. We selected a subset of the writers from the hypothesis generation experiment to be our labelers. For each subset, about 15\% of the total data were randomly selected and relabeled. The labelers were paid 0.2 RMB (0.028 USD) for each pair. \paragraph{Relabeling results \label{sec:relabel:results}} Our results, shown in Table~\ref{tab:labelling}, are very close to the numbers reported for SNLI/MNLI, with labeler agreement even higher than SNLI/MNLI for \textsc{Single} and \textsc{Multi}. Crucially, the three \textsc{Multi} subsets, created using the three variants of the \textit{multi-hypothesis} generation method, have similar agreement to MNLI, suggesting that producing nine hypotheses for a given premise is feasible. Furthermore, the agreement rates on the \texttt{medium} and \texttt{hard} portions of the subsets are only slightly lower than on the \texttt{easy} portion, with agreement rates of 3 labels at least 97.90\% (see Table~\ref{tab:labelling:3portions} in the Appendix), suggesting that our data in general is of high quality. Agreement is lower for \textsc{MultiConstraint}, showing that it may be difficult to produce many hypotheses under these constraints. In a separate relabeling experiment, we examine the quality of human-translated examples from the XNLI dev set. The results show considerably lower agreement: The majority vote of our five annotators only agree with the XNLI gold-label 67\% of the time, as compared to the lowest rate of 88.2\% on \textsc{MultiConstraint}. Additionally, 11.6\% of the XNLI dev examples in Chinese contain more than 10 Roman alphabets, which are extremely rare in original, every-day Chinese speech/text. These \added{results} suggest that XNLI is less suitable as validation set for Chinese NLI, and thus we excluded XNLI dev set in our evaluation. For \added{further} details, see Appendix \ref{sec:xnli:label}. \subsection{The Resulting Corpus \label{sec:ocnli:datasplit}} Overall, we have a corpus of more than 56,000 pairs of inference pairs in Chinese. We have randomized the total of 6,000 \textit{relabeled} pairs from \textsc{MultiEncourage} and \textsc{MultiConstraint} and used them as the development and test sets, each consisting of 3,000 examples. All pairs from \textsc{Single} and \textsc{Multi}, plus the remaining 26,211 pairs from \textsc{MultiEncourage} and \textsc{MultiConstraint} are used for the training set, about 50,000 pairs\footnote{We note that given the constraints of having equal number of \texttt{easy}, \texttt{medium} and \texttt{hard} examples in dev/test sets, the resulting corpus ended up having high premise overlap between training and dev/test sets, in contrast to the original MNLI design. To ensure that such premise overlap does not bias the current models and inflate performance, we experimented with a smaller \textbf{non-overlap} train and test split, which was constructed by filtering parts of the training. This lead to comparable results, despite the non-overlap being much smaller in size, which we detail in Appendix \ref{sec:no-overlap}. Both the \textbf{overlap} and \textbf{non-overlap} splits will be released for public use, as well as part of the the public leaderboard at \urlstyle{rm}\url{https://www.cluebenchmarks.com/nli.html}. }. This split ensures that all labels in the development and test sets have been verified, and the number of pairs in the \texttt{easy}, \texttt{medium} and \texttt{hard} portions are roughly the same in both sets. It is also closer to a realistic setting where contradictions without negation are much more likely. Pairs that do not receive a majority label in our relabeling experiment are marked with ``-'' as their label, and can thus be excluded if necessary. % \section{Experimental Investigation of OCNLI} \subsection{Experimental Setup} To demonstrate the difficulty of our dataset, we establish baselines using several widely-used NLI models tailored to Chinese\footnote{Additional details about all of our models and hyper-parameters are included as supplementary material.}. This includes the baselines originally used in \citet{mnli} such as the continuous bag of words (CBOW) model, the biLSTM encoder model and an implementation of ESIM \cite{chen2017lstm}\footnote{We use a version of the implementations from \urlstyle{rm}\url{https://github.com/NYU-MLL/multiNLI}.}. In each case, we use Chinese character embeddings from \citet{chinese-emb} in place of the original GloVe embeddings. We also experiment with state-of-the-art pre-trained transformers for Chinese \cite{cui2019pretraining} using the fine-tuning approach from \citet{bert}. Specifically, we use the Chinese versions of BERT-base \cite{bert} and RoBERTa-large \cite{roberta} with whole-word masking (see details in \citet{cui2019pretraining}). In both cases, we rely on the publicly-available TensorFlow implementation provided in the CLUE benchmark \cite{clue}\footnote{See: \urlstyle{rm}\url{https://github.com/CLUEbenchmark/CLUE}}. Following \citet{bowman2020collecting}, we also fine-tune \emph{hypothesis-only} variants of our main models to measure annotation artifacts. To measure human performance, we employed an additional set of 5 Chinese native speakers to annotate a sample ($300$ examples) of our OCNLI test set. This follows exactly the strategy used in \citet{glue-human} for measuring human performance in GLUE, and provides a \emph{conservative} estimate of human performance in that annotators were provided with minimal amounts of task training (see Appendix \ref{sec:human:baseline} for details). \paragraph{Datasets} In addition to experimenting with OCNLI, we also compare the performance of our main models against models fine-tuned on the Chinese training data of XNLI \cite{xnli} (an automatically translated version of MNLI), as well as combinations of OCNLI and XNLI. The aim of these experiments is to evaluate the relative advantage of automatically translated data. We also compare both models against the CLUE diagnostic test from \citet{clue}, which is a set of 514 NLI problems that was annotated by \added{an independent set of} Chinese linguists. To analyze the effect of our different hypothesis elicitation strategies, we look at model performance on different subsets of OCNLI. Due to the way in which the data is partitioned (all of \textsc{Single} and \textsc{Multi} are in the training set), it is difficult to fine-tune on OCNLI and test on all four subsets. We instead use an XNLI trained model, which is independent of any biases related to our annotation process, to probe the difficulty of our different subsets. \begin{table*}[t] \centering \begin{tabular}{l|lll|ll}\toprule Maj. & CBOW & biLSTM & ESIM & BERT & RoBERTa \\\midrule 38.1 & 55.7 \fz{(0.5)} & 59.2 \fz{(0.5)} & 59.8 \fz{(0.4)} & 72.2 \fz{(0.7)} & 78.2 \fz{(0.7)} \\ \bottomrule \end{tabular} \caption{Test performance on OCNLI for all baseline models. Majority label is \textit{neutral}. \added{We report the mean accuracy \% across five training runs with random re-starts (the standard deviation is shown in parentheses).} \label{tab:all}} \end{table*} \subsection{Baseline Results and Analysis} In this section, we describe our main results. \begin{table*}[t] \centering \begin{tabular}{ll|rr|rr|c} \toprule \multicolumn{2}{c|}{\textbf{Fine-tuning data} / size} & \multicolumn{2}{c|}{\textbf{OCNLI} / 50k} & \multicolumn{2}{c|}{\textbf{XNLI} / 392k} & \multicolumn{1}{c}{\textbf{Combined} / 443k} \\ Test data & size & BERT & RoBERTa & BERT & RoBERTa & RoBERTa \\ \midrule OCNLI human & 300 & \multicolumn{2}{c|}{90.3* (OCNLI.test)} & & & \\ OCNLI.dev & 3k & 74.5 \fz{(0.3)} & \textbf{78.8} \fz{(1.0)} & 66.8 \fz{(0.5)} & 70.5 \fz{(1.0)} & 76.4 \fz{(1.3)} \\ OCNLI.test & 3k & 72.2 \fz{(0.7)} & \textbf{78.2} \fz{(0.7)} & 66.7 \fz{(0.3)} & 70.4 \fz{(1.2)} & 75.6 \fz{(1.2)} \\ CLUE diagnostics & 0.5k & 54.4 \fz{(0.9)} & 61.3 \fz{(1.3)} & 53.0 \fz{(0.9)} & 62.5 \fz{(2.9)} & \textbf{63.7} \fz{(2.4)} \\ \bottomrule \end{tabular} \caption{Accuracy on OCNLI, finetuned on OCNLI, XNLI and Combined (50k OCNLI combined with 392k XNLI). *: See Appendix \ref{sec:human:baseline} for details about the human baseline. \added{As in Table~\ref{tab:all}, we report the mean accuracy \% across five training runs with the standard deviation shown in parenthesis.} } \label{tab:res:1} \end{table*} \paragraph{How Difficult is OCNLI?} To investigate this, we train/fine-tune all five neural architectures on OCNLI training data and test on the OCNLI test set. The main results % are shown in Table~\ref{tab:all}. All of the non-transformer models perform poorly while BERT and RoBERTa reach a $\sim$20 percentage-point advantage over the strongest of these models (ESIM). This shows the relative strength of pre-trained models on our task. We find that while transformers strongly outperform other baseline models, our best model, based on RoBERTa, is still about 12 points below human performance on our test data (i.e., 90.3\% versus 78.2\%). This suggests that models have considerable room for improvement, and provides additional evidence of task difficulty. In comparison, these transformer models reach human-like performance in many of the GLUE \cite{glue} and SuperGLUE \cite{superglue} tasks. For NLI specifically, the performance of the English RoBERTa on MNLI is 90.4\%, and only about 2 percentage-points below the human score \citep{bowman2020collecting,glue-human}. We see a similar trend for BERT, which is about 18 points behind human performance on OCNLI, but the difference is roughly 8 points for MNLI \cite{bert}. We also see much room for improvement on the CLUE diagnostic task, where our best model achieves only 61.3\% (a slight improvement over the result reported in \citet{clue}). \begin{table}[t] \centering \begin{tabular}{l|ll} \toprule Test data & BERT & RoBERTa \\\midrule OCNLI\_dev & 65.3 & 65.7 \\ OCNLI\_test & 64.3 & 65.0 \\ OCNLI\_test\_easy & 63.5 & 64.0 \\ OCNLI\_test\_medium & 63.9 & 65.6 \\ OCNLI\_test\_hard & 65.5 & 65.5 \\\midrule MNLI & na. & 62.0 \\\bottomrule \end{tabular} \caption{Hypothesis-only baselines for OCNLI (fine-tuned on OCNLI.train) and MNLI (retrieved from \protect \citet{bowman2020collecting}). \label{tab:res:hypo:only} } \end{table} We also looked at how OCNLI fares on hypothesis-only tests, where all premises in train and test are replaced by the same non-word, thus forcing the system to make predictions on the hypothesis only. Table~\ref{tab:res:hypo:only} shows the performance of these models on different portions of OCNLI. These results show that our elicitation gives rise to annotation artifacts in a way similar to most benchmark NLI datasets (e.g., OCNLI: $\sim66\%$; MNLI $\sim62\%$ and SNLI: $\sim69\%$, as reported in \citet{bowman2020collecting} and \citet{poliak2018hypothesis}, respectively). We specifically found that negative polarity items (``any'', ``ever''), negators and ``only'' are among the indicators for contradictions, whereas ``at least'' biases towards entailments. We see no negators for the \textsc{MultiConstraint} subset, which shows the effect of putting constraints on the hypotheses that the annotators can produce. Instead, ``only'' is correlated with contradictions. A more detailed list is shown in Figure~\ref{tab:bias:pmi}, listing individual word and label pairs with high pairwise mutual information (PMI). PMI was also used by \citet{bowman2020collecting} for the English NLI datasets. Given the large literature on adversarial filtering \cite{le2020adversarial} and adversarial learning \cite{belinkov2019don} for NLI, which have so far been limited to English and on much larger datasets that are easier to filter, we see extending these methods to our dataset and Chinese as an interesting challenge for future research. \begin{CJK}{UTF8}{gbsn} \begin{table}[t] \centering\small \begin{tabular}{llll}\toprule Word & Label & PMI & Counts \\\midrule OCNLI & & & \\ 任何 \textit{any} & contradiction & 1.02 & 439/472 \\ 从来 \textit{ever} & contradiction & 0.99 & 229/244 \\ 至少 \textit{at least} & entailment & 0.92 & 225/254 \\ \midrule \textsc{Single} & & & \\ 任何 \textit{any} & contradiction & 0.89 & 87/90 \\ 没有 \textit{no} & contradiction & 0.83 & 582/750 \\ 无关 \textit{not related} & contradiction & 0.72 & 39/42 \\ \midrule \textsc{Multi} & & & \\ 任何 \textit{any} & contradiction & 0.92 & 97/103 \\ 没有 \textit{no} & contradiction & 0.88 & 721/912 \\ 从来 \textit{ever} & contradiction & 0.75 & 42/46 \\ \midrule \textsc{MultiEncourage} & & & \\ 任何 \textit{any} & contradiction & 0.98 & 198/212 \\ 从来 \textit{ever} & contradiction & 0.96 & 131/137 \\ 至少 \textit{at least} & entailment & 0.82 & 81/91 \\ \midrule \textsc{MultiConstraint} & & & \\ 至少 \textit{at least} & entailment & 0.91 & 105/110 \\ 只有 \textit{only} & contradiction & 0.86 & 179/216 \\ 只 \textit{only} & contradiction & 0.77 & 207/280 \\ \bottomrule \end{tabular} \caption{Top 3 \texttt{(word, label)} pairs according to PMI for different subsets of OCNLI. \label{tab:bias:pmi}} \end{table} \end{CJK} \paragraph{Comparison with XNLI} To ensure that our dataset is not easily solved by simply training on existing translations of MNLI, we show the performance of BERT and RoBERTa when trained on XNLI but tested on OCNLI. The results in Table~\ref{tab:res:1} (column XNLI) show a much lower performance than when the systems are trained on OCNLI, even though XNLI contains 8 times more examples.\footnote{To ensure that this result is not unique to XNLI, we ran the same experiments using CMNLI, which is an alternative translation of MNLI used in CLUE, and found comparable results.} While these results are not altogether comparable, given that the OCNLI training data was generated from the same data sources and annotated by the same annotators (see \citet{annotator2019Geva}), we still see these results as noteworthy given that XNLI is currently the largest available multi-genre NLI dataset for Chinese. The results are indicative of the limitations of current models trained solely on translated data. More strikingly, we find that when OCNLI and XNLI are combined for fine-tuning (column Combined in Table~\ref{tab:res:1}), this improves performance over the results using XNLI, but reaches lower accuracies than fine-tuning on the considerably smaller OCNLI (except for the diagnostics). \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{xnli_ocnli_diagnostics500.png} \caption{Ablation over the number of fine-tuning examples for RoBERTa fine-tuned on OCNLI vs. XNLI.} % \label{fig:curve} \end{figure} Figure~\ref{fig:curve} shows a learning curve comparing model performance on the independent CLUE diagnostic test. Here we see that the OCLNI model reaches its highest performance at 30,000 examples while the XNLI model still shows improvements on 50,000 examples. Additionally, OCNLI reaches the same performance as the model finetuned on the full XNLI set, at around 25,000 examples. This provides additional evidence of the importance of having reliable human annotation for NLI data. \begin{table}[t] \centering\small \resizebox{0.95\textwidth}{!}{\begin{minipage}{\textwidth} \begin{tabular}{lrrrr}\toprule & \textsc{Single} & \textsc{Multi} & \textsc{MultiEnc} & \textsc{MultiCon} \\ \midrule \multicolumn{5}{l}{BERT: fine-tune on XNLI}\\\midrule dev\_full & 77.3 & 73.6 & 68.6 & 65.8 \\ easy & na. & 74.0 & 70.1 & 68.4 \\ medium &na. & 74.3 & 69.6 & 65.9 \\ hard & na.& 72.5 & 66.2 & 63.1 \\ \midrule \multicolumn{5}{l}{RoBERTa: fine-tune on XNLI} \\\midrule dev\_full & 78.9 & 77.3 & 71.3 & 70.8 \\ easy & na. & 77.2 & 72.8 & 73.5 \\ medium & na.& 78.6 & 71.7 & 70.2 \\ hard & na. & 76.2 & 69.4 & 68.7 \\ \bottomrule \end{tabular} % \end{minipage}} \caption{Accuracy of XNLI-finetuned models, tested on relabelled parts of different OCNLI subsets. \label{tab:res:4batches} } \end{table} \paragraph{Understanding the OCNLI Subsets} To better understand the effect of having three annotator hypotheses per premise, constituting three difficulty levels, and having four elicitation modes, we carried out a set of experiments with XNLI-finetuned models on the different subsets. We used XNLI to avoid imposing specific preferences on the models. Table~\ref{tab:res:4batches} shows a consistent decrease in accuracy from \textsc{Single} through \textsc{MultiConstraint}, and a mostly consistent decrease from easy to hard (exception: between easy and medium in \textsc{Multi}). Both trends suggest that \textit{multi-hypothesis} elicitation and improved instructions lead to more challenging elicited data. \section{Conclusion} In this paper, we presented the Original Chinese Natural Language Inference (OCNLI) corpus, the first large-scale, non-translated NLI dataset for Chinese. Our dataset is composed of 56,000 premise-hypothesis pairs, manually created by university students with a background in language studies, using premises from five genres and an enhanced protocol \added{from the original MNLI annotation scheme}. Results using BERT and RoBERTa show that our dataset is challenging for the current best pre-trained transformer models, the best of which is $\sim12$ percentage-points below human performance. \added{We also demonstrate the relative advantage of using our human constructed dataset over machine translated NLI such as XNLI.} \added{To encourage more progress on Chinese NLU, we are making our dataset publicly available for the research community at \url{https://github.com/CLUEbenchmark/OCNLI} and will be hosting a leaderboard in the Chinese Natural Language Understanding (CLUE) \cite{clue} benchmark (\url{https://www.cluebenchmarks.com/nli.html}). } \added{Given the wide impact that large-scale NLI datasets, such as SNLI and MNLI, have had on recent progress in NLU for English, we hope that our resource will likewise help accelerate progress on Chinese NLU. In addition to making more progress on Chinese NLI, future work will also focus on using our dataset for doing Chinese model probing (e.g., building on work such as \citet{warstadt2019investigating,probing2020,jeretic2020natural}) and sentence representation learning \cite{reimers2019sentence}, as well as for investigating bias-reduction techniques \cite{clark2019don,belinkov2019don,le2020adversarial} for languages other than English.} \section*{Acknowledgements} We thank all our annotators without whom this work wouldn't have been possible, and also Ruoze Huang, Jueyan Wu, Zhaohong Wu and Xiaojie Gong for their help in the annotation process. We are grateful for the suggestions from our anonymous reviewers and the CL colloquium at Indiana University. This work was supported by the CLUE benchmark and the Grant-in-Aid of Doctoral Research from Indiana University Graduate School. \added{Special thanks to the beaker team at AI2 for providing technical support for the beaker experiment platform. Computations on \url{beaker.org} were supported in part by credits from Google Cloud.} \bibliographystyle{acl_natbib}
{'timestamp': '2020-10-13T02:28:20', 'yymm': '2010', 'arxiv_id': '2010.05444', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05444'}
arxiv
\section{Introduction} Monocular 3D multi-person human pose estimation aims at estimating the 3D joints of several people from a single RGB image. This problem attracts great research and industrial interests, as it would make possible a number of applications in many different fields including the entertainment industry, sports technology, physical therapy and medical diagnosis. Recent works on multi-person human pose estimation usually regard different people as independent instances and estimate the poses one by one in separate bounding boxes in top-down methods. This makes all these approaches agnostic about the context information and specifically about the presence of other people \cite{lcr,3dmppe,lcr++,singleshot,kumarapu2020animepose,von2018recovering,mehta2019xnect,benzine2019deep,dabral2019multi}. However, when people interact, the pose and motion of every person is typically dependent and correlated to the body posture of the people he/she is interacting with. \newline While context information has been shown to be useful in tasks such as object detection~\cite{divvala2009empirical,pato2020seeing,barnea2019exploring}, motion prediction\cite{Corona2019ContextawareHM} or affordance estimation~\cite{corona2020ganhand}, to the best of our knowledge, it has not been \wen{well developed} before in a body pose estimation. In this paper, we investigate how these dependencies can be used to boost the performance of off-the-shelf architectures for 3D human pose estimation. \newline Concretely, we propose a pose interacting network, PI-Net, which is fed with the 3D pose of a person of interest and an arbitrary number of body poses from other people in the scene, all of them computed with a context agnostic pose detector. These poses are potentially noisy, both in their absolute position in space as in the specific representation of the body posture. PI-Net is built using a recurrent network with a self-attention module that encodes the contextual information. Since it is unclear how to rank the contextual information, that is the pose of other persons, regarding the potential impact on the pose refinement pipeline, we make the very straightforward assumption that the potential of a person to refine the pose of the person-of-interest, is inversely proportional to the square of the distance between them. \newline We thoroughly evaluate our approach on the MuPoTS dataset~\cite{singleshot}, and using the initial detections of 3DMPPE~\cite{3dmppe}, the current best performing approach on this dataset. PI-Net exhibits consistent improvement of the pose estimates provided by 3DMPPE in all sequences of the dataset, becoming thus, the new state-of-the-art (see one example in Fig.~\ref{fig:teaser}). Interestingly, note that PI-Net can be used as drop-in replacement for any other architecture that estimates 3D human pose. Additionally, the size of the network we propose is relatively small ($3.41M$ training parameters, while the baseline model has $36.25M$ parameters), enabling efficient training and introducing a marginal computational cost at test. Testing on one Geforce1070, PI-net just cost 0.007s on refining one person while the baseline cost 0.038s for detecting one root-centered pose and also extra time on obtaining the bounding boxes and roots. Our method is lightweight and consistently improves the baseline. \begin{figure*} \begin{center} \includegraphics[width=0.7\linewidth]{figures/teaser_f.png} \caption{{\bf PI-Net peformance.} An example of testing on MuPoTS dataset. Poses refined by PI-Net (in green) are closer to the ground truth (in black) than the baseline (in red). We zoom-in to several parts to clearly appreciate the difference. The error before and after PI-Net refinement for each person is shown in the table. The average 3D joint error for this example is reduced from 88.02 mm to 86.19 mm.} \label{fig:teaser} \end{center} \end{figure*} \section{Related Work} \subsection{3D Single-person pose estimation} Deep learning methods for single-person 3D pose estimation follow two different strategies. On one hand, there are algorithms that directly learn the mapping from image features to 3D poses~\cite{martinez2017simple, li20143d, pavlakos2017coarse, qiu2019cross, ci2019optimizing}. For instance, \cite{li20143d} propose a joint model for body part detectors and pose regression. Pavlakos~\etal~\cite{pavlakos2017coarse} introduce a U-Net architecture to recover joint-wise 3D heatmaps. Sun~\etal~\cite{sun2017compositional} build a regression approach using a bone-based representation that enforces human pose structure. In~\cite{sun2018integral}, a differentiable soft-argmax operation is used for efficiently training a hourglass network. Another line of work focuses on recovering 3D human pose from 2D image features by using models that enforce consistency between 3D predicted poses and 2D observations~\cite{wei2009, bogo2016, moreno20173d}. For instance, Bogo~\etal~\cite{bogo2016} fit a human body parametric model by minimising the distance between the projection of the 3D estimation and the 2D predicted joints. Moreno-Noguer~\cite{moreno20173d} propose to infer 3D pose via distance matrix regression. Yang~\etal~\cite{yang20183d} use an adversarial approach to ensure that estimated poses are antropomorphic. \begin{figure*} \begin{center} \vspace{0.2cm} \includegraphics[trim={0.6cm 0cm 1.65cm 0cm},clip=true,width=0.9\linewidth]{figures/architecture_v7b.pdf} \vspace{0cm} \caption{{\bf PI-Net Architecture}. Mask-RCNN~\cite{maskrcnn} and PoseNet~\cite{3dmppe} are used to extract the initial pose estimates $\mathbf{p}_1,\ldots,\mathbf{p}_N$. These estimates are fed into PI-Net, composed of three main blocks: Bi-RNN, Self-attention and the shared fully-connected layers. The output of PI-Net refines the initial pose estimates by exploiting the pose of the interactees, yielding $\mathbf{q}_1,\ldots,\mathbf{q}_N$. } \label{fig:pipline} \end{center} \end{figure*} \subsection{2D multi-person pose estimation} There are two main approaches for multi-person pose estimation, top-down~\cite{xiao2018simple,li2019rethinking,sun2019deep,chen2018cascaded} and bottom-up models~\cite{cao2017realtime,cao2018openpose,pishchulin2016deepcut,newell2017associative}. On the former, a human detector first estimates the bounding boxes containing the person. Each detected area is cropped and fed into the pose estimation network. The later also follows a two-stage pipeline, where a model first estimates all human body keypoints, and then groups them into each person using clustering techniques. Cao~\etal~\cite{cao2017realtime,cao2018openpose} propose a real-time bottom-up method using Part Affinity Fields to group joints of different person. The efficiency of these bottom-up approaches makes them very appropriate to be used as a backbone for later lifting the 2D joints to 3D~\cite{dabral2019multi,pavlakos2019expressive}. The performance of bottom-up methods has been recently improved by to-down strategies. Xiao~\etal~\cite{xiao2018simple} use ResNet~\cite{he2016deep} as encoder and several deconvolutional layers as decoder to formulate a simple but effective baseline. Sun\etal~\cite{sun2019deep} connect the high-to-low resolution convolution streams in parallel to maintain richer semantic information. Chen \etal~\cite{chen2018cascaded} use a cascade pyramid network to refine the hard keypoints of the initial estimated results. \subsection{3D Multi-person pose estimation \wen{and contextual information}} Similar to their 2D counterparts, 3D multi-person poses estimation methods can be split into top-down~\cite{lcr, lcr++, 3dmppe, kumarapu2020animepose, weinzaepfel2020dope} and bottom-up\cite{singleshot,mehta2019xnect,zanfir2018deepintegrated} approaches. Mehta~\etal~\cite{singleshot,mehta2019xnect} follow a bottom-up strategy, by first estimating three occlusion-robust location-maps~\cite{mehta2017vnect} and then modeling the association between body keypoints using Part Affinity Fields~\cite{cao2017realtime}. Zanfir~\etal~\cite{zanfir2018deepintegrated} formalize the problem of localizing and grouping people as a binary linear integer program and solve it by integrating a limb scoring model. Rogez~\etal~\cite{lcr, lcr++}, in contrast, propose a top-down approach, where first, each person 2D bounding box is classified into one of the anchor clustered 3D poses. These poses are then refined in a coarse-to-fine manner. Moon~\etal~\cite{3dmppe} propose an architecture that simultaneously predicts the 3D absolute position of the root joint and reconstructs the relative 3D body pose of multiple people. However, despite the fact that these works estimate the body pose of an arbitrary number of people, each person is processed using an independent pipeline that does not take into account the interactions between the rest of people or other contextual information. \wen{ Recently, some works begin to pay attention to using contextual information in 3D pose estimation problem by integrating scene constraints\cite{zanfir2018sceneconst} or considering the depth-order to resolve the overlapping problem \cite{jiang2020depthordering, li2020hmor}. Jiang~\etal~\cite{jiang2020depthordering} propose a depth ordering-aware loss to consider the occlusion relationship and interpenetration of people in multi-person scenarios. Li~\etal~\cite{li2020hmor} divide human relations into different levels and define 3 corresponding losses to tell if the orders of different people or different joints are correct or not. Though contextual information is considered in these works, they do not really explore the interaction relations between different people in the same activity. More recently, Fieraru~\etal~\cite{fieraru2020CHI3D} proposed a new dataset of human interactions with several daily interaction scenarios and proposed a framework based on contact detection over model surface regions, but this dataset is not released yet. } In this paper, we propose a method that can be used in combination with the current state-of-the-art model~\cite{3dmppe} and boost its performance by looking at the whole group of humans. The proposed model is flexible and can be stacked after any 3D pose estimation model, independently of it being top-down or bottom-up. \section{PI-Net for Multi-Person Pose Estimation} Our goal is to exploit the interaction information between $N$ people so as to improve the estimation of their pose. We assume the existence of an initial 3D pose estimate $\mathbf{p}_n\in\mathbb{R}^{J\times 3}$ of person $n=1,\ldots,N$, where $J$ is the number of estimated joints, \eg\ obtained from 3DMPPE~\cite{3dmppe}. All the $N$ poses are in absolute camera coordinates. Formally, our goal is to improve the initial pose estimates, taking into account the pose of other people: \begin{equation} [\mathbf{q}_1,\ldots,\mathbf{q}_N] = \mathbf{\Pi} (\mathbf{p}_1,\ldots,\mathbf{p}_N), \label{equ:refine} \end{equation} where $\mathbf{q}_n\in\mathbb{R}^{J\times 3}$ denotes the pose of person $n$ improved with the information of the poses of the interactees. While the idea is very intuitive, the research question is how to design PI-Net (i.e.\ $\mathbf{\Pi}$) so that it satisfies the following desirable criteria. Firstly, it shall work in environments with different number of people $N$, and not fixed to a particular scenario. Secondly, the interaction information can be efficiently exploited and learned using publicly available datasets. Finally, it has to be generic enough to work with \textit{any} 3D monocular multi-person pose estimator. \subsection{Pipeline of PI-Net} Naturally, the fact that the number of people $N$ is unknown in advance, points us towards the use of recurrent neural networks. Such RNN should input the poses estimated by a generic pose estimator, and embed the pose information into a representation learned specifically to take the cross-interactions into account. Without loss of generality, let us assume that the person-of-interest is $n=1$, and hence the pose to refine is $\mathbf{p}_1$. We consider using a bi-directionnal RNN, whose first input is $\mathbf{p}_1$, and then the rest of initial poses are provided in a given order (see below). Our intuition for using a Bi-RNN is the following. During the forward pass, and since the first input is $\mathbf{p}_1$, the network can use the information in $\mathbf{p}_1$ to extract the features of the other poses that will best refine $\mathbf{p}_1$. In the backward pass, the network accumulates all this information back to $\mathbf{p}_1$, obtaining: \begin{equation} \mathbf{e}_1 = \textrm{Bi-RNN}(\mathbf{p}_1,\ldots,\mathbf{p}_N). \end{equation} The learned embedding \wen{ $\mathbf{e}_1\in\mathbb{R}^{N\times E}$}is supposed to contain the crucial information from all other poses to refine the pose of the person-of-interest ($1$ in our example), but not only. Indeed, given that a priori we do not know which persons would be more helpful in refining the pose of interest, the computed embedding $\mathbf{e}_1$ could contain information that is not exploitable to refine the pose. In order to take this phenomenon into account, we soften the requirements of the Bi-RNN through the use of an attention mechanism as shown in Figure~\ref{fig:pipline} (bottom-left zoom). Such attention mechanism aims to improve each embedding by combining information from the embeddings of other persons. To do so, we compute a matrix of attention weights: \begin{equation} \mathbf{W}\in\mathbb{R}^{N\times N}, \qquad \mathbf{W}_{nm} = \mathbf{e}_n^\top(\mathbf{A}_{\textsc{att}}\mathbf{e}_m+\mathbf{b}_{\textsc{att}})), \end{equation} that is then normalised with a row-wise soft-max operation. $\mathbf{A}_{\textsc{att}}$ and $\mathbf{b}_{\textsc{att}}$ are attention parameters to be learned. The self-attention weights $\mathbf{W}$ encoding the residual interaction not captured by the Bi-RNN are used to update the embedding vector $\mathbf{u}_1 = {\mathbf{W}\mathbf{e}_1}$. Finally, the updated embedding is feed-forwarded through a few fully connected layers, obtaining the final refined pose $\mathbf{q}_1$. While, at test time the self-attention and fully-connected layers are used only for the person-of-interest, at training time we found it is useful to apply these two operations to all poses, and back-propagate the loss associated to everyone. This strategy eases the training. The overall pipeline depicting of PI-Net is shown in Figure~\ref{fig:pipline}. \subsection{Interaction Order} \label{sec:interaction} In the previous section we assumed that the order in which the initial pose estimates $\mathbf{p}_n$ were presented to the Bi-RNN was given. Although there is no principled rule to define the ordering, there are some requirements. For a given person $n$, the sequence of poses presented to the network $\mathbf{p}_{\rho_n(1)},\ldots,\mathbf{p}_{\rho_n(N)}$ has two constraints: (i) each pose is presented only once and (ii) the first pose is the one to be refined, i.e.\ $\rho_n(1)=n$. Intuitively, the order should represent the relevance: the more useful $\mathbf{p}_m$ is to refine $\mathbf{p}_n$, the closer $\mathbf{p}_m$ should be to $\mathbf{p}_n$ in the input sequence, i.e. the smaller $\rho_n(m)$ should be. Because finding the optimal permutation is a complex combinatorial optimisation problem for which there is no ground-truth, we opt for assuming that the relevance is highly correlated to the physical proximity between interactees. Therefore, the closer person $m$ is to person $n$, the smaller should $\rho_n(m)$ be. With this rule we order the initial pose estimates to be fed to the Bi-RNN. We also consider of using Graph Convolutional Network~\cite{kipf2016semi} to model the interaction between different person. Considering a pair of input persons, the node of the graph represents the coordinate of all the joints of these two people, and the adjacency matrix learned from the input represents interaction between these joints. This strategy does not provide any performance increase, the results will be discussed in Section~\ref{sec:ablation}. \subsection{Network Architecture} In order to build and train our PI-Net, we first extract the initial poses using~\cite{3dmppe}. In the baseline, Mask-RCNN is used to detect the people present in the image. After that, the keypoint detector is applied to each image to detect the root-based poses and then project them into absolute camera coordinates. This keypoint detector is based on ResNet50 and 3 addition deconvolutional layers, following~\cite{sun2018integral}. The set of keypoints for each person in camera coordinates $\mathbf{p}_n$, is therefore obtained. Note that this regressor gives all $J$ person joints, despite of partial occlusions, the corresponding occluded joints are hallucinated. These initial pose estimates are then normalised with their mean and standard deviation, thus obtaining the input pose estimates of our PI-Net, $\{\mathbf{p}_1,\ldots,\mathbf{p}_N\}$. For each person $n$, we feed the PI-Net with the sequence of poses in the order appropriate for person $n$ (see Section~\ref{sec:interaction}). The output $\mathbf{q}_n$ of PI-Net is the refined pose for person $n$. PI-Net is trained with the $L_1$ loss between the refined poses and the ground-truth in 3D camera coordinates, added for all detected persons in the training image. The Bi-RNN is implemented using three layers of gated recurrent units (GRU~\cite{cho2014gru}). The the self-attention layer provides a straightforward way to account for person pose interactions. After applying attention, the updated embedding goes through three fully connected layers to output the refined 3D pose in camera coordinates. These three fully connected layers are shared by all $N$ poses. Consequently, the proposed PI-Net can be trained and evaluated using images with different number of people. \begin{table*}[htbp!] \caption{Sequence-wise 3DPCK comparison with state-of-the-art methods on the MuPoTS-3D dataset. The first three methods show the reported results in the corresponding paper, the fourth method and our model is tested with ground truth bounding boxes and roots. Higher value means better performance.\vspace{-0.5cm}} \label{tab:sequencewise pck} \begin{center} \resizebox{\textwidth}{!}{\setlength{\tabcolsep}{0.7mm}{ \begin{tabular}{l c c c c c c c c c c c c c c c c c c c c c} \toprule Sequence & S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10 & S11 & S12 & S13 & S14 & S15 & S16 & S17 & S18 & S19 & S20 & AVG\\ \midrule\midrule \multicolumn{22}{l}{\textbf{Accuracy for all ground truths}} \\ LCR\cite{lcr} & 67.7 & 49.8 & 53.4 & 59.1 & 67.5 & 22.8 & 43.7 & 49.9 & 31.1 & 78.1 & 50.2 & 51.0 & 51.6 & 49.3 & 56.2 & 66.5 & 65.2 & 62.9 & 66.1 & 59.1 & 53.8 \\ Singleshot\cite{singleshot} & 81.0 & 60.9 & 64.4 & 63.0 & 69.1 & 30.3 & 65.0 & 59.6 & 64.1 & 83.9 & 68.0 & 68.6 & 62.3 & 59.2 & 70.1 & 80.0 & 79.6 & 67.3 & 66.6 & 67.2 & 66.0 \\ Xnect\cite{mehta2019xnect} & 88.4 & 65.1 & 68.2 & 72.5 & 76.2 & 46.2 & 65.8 & 64.1 & 75.1 & 82.4 & 74.1 & 72.4 & 64.4 & 58.8 & 73.7 & 80.4 & 84.3 & 67.2 & 74.3 & 67.8 & 70.4 \\ LCR++\cite{lcr++} & 87.3 & 61.9 & 67.9 & 74.6 & 78.8 & 48.9 & 58.3 & 59.7 & 78.1 & 89.5 & 69.2 & 73.8 & 66.2 & 56.0 & 74.1 & 82.1 & 78.1 & 72.6 & 73.1 & 61.0 & 70.6\\ PandaNet\cite{benzine2020pandanet} & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - & - & 72.0\\ 3DMPPE\cite{3dmppe} & 93.2 & 75.6 & 80.3 & 81.5 & 84.6 & 75.3 & \textbf{84.5} & 69.3 & 90.1 & 92.0 & 81.0 & 81.0 & 73.4 & 73.5 & 81.8 & 89.6 & 88.4 & 84.3 & 74.5 & 70.6 & 81.2 \\ PI-Net (ours) & \textbf{93.5} & \textbf{77.4} & \textbf{82.0} & \textbf{82.9} & \textbf{87.2} & \textbf{75.9} & 84.0 & \textbf{71.5} & \textbf{90.2} & \textbf{92.2} & \textbf{82.5} & \textbf{82.9} & \textbf{74.7} & \textbf{75.7} & \textbf{83.6} & \textbf{91.4} & \textbf{90.6} & \textbf{86.0} & \textbf{74.9} & \textbf{71.1} & \textbf{82.5} \\ \midrule\midrule \multicolumn{22}{l}{\textbf{Accuracy only for matched ground truths}}\\ LCR\cite{lcr} & 69.1 & 67.3 & 54.6 & 61.7 & 74.5 & 25.2 & 48.4 & 63.3 & 69.0 & 78.1 & 53.8 & 52.2 & 60.5 & 60.9 & 59.1 & 70.5 & 76.0 & 70.0 & 77.1 & 81.4 & 62.4\\ Singleshot\cite{singleshot} & 81.0 & 65.3 & 64.6 & 63.9 & 75.0 & 30.3 & 65.1 & 61.1 & 64.1 & 83.9 & 72.4 & 69.9 & 71.0 & 72.9 & 71.3 & 83.6 & 79.6 & 73.5 & 78.9 & 90.9 & 70.8\\ LCR++\cite{lcr++} & 88.0 & 73.3 & 67.9 & 74.6 & 81.8 & 50.1 & 60.6 & 60.8 & 78.2 & 89.5 & 70.8 & 74.4 & 72.8 & 64.5 & 74.2 & 84.9 & 85.2 & 78.4 & 75.8 & 74.4 & 74.0\\ Xnect\cite{mehta2019xnect} & 88.4 & 70.4 & 68.3 & 73.6 & 82.4 & 46.4 & 66.1 & 83.4 & 75.1 & 82.4 & 76.5 & 73.0 & 72.4 & 73.8 & 74.0 & 83.6 & 84.3 & 73.9 & 85.7 & 90.6 & 75.8\\ 3DMPPE\cite{3dmppe} & \textbf{93.9} & 83.0 & 80.3 & 81.5 & 85.4 & 75.3 & 84.5 & 77.2 & 90.1 & 92.0 & 81.0 & 81.0 & 74.3 & 76.0 & 81.8 & 89.6 & 88.4 & 84.3 & 75.5 & 76.2 & 82.6\\ PI-Net (ours) & \textbf{93.9} & \textbf{85.0} & \textbf{81.5} & \textbf{83.0} & \textbf{88.9} & \textbf{75.6} & \textbf{84.7} & \textbf{78.0} & \textbf{90.4} & \textbf{92.2} & \textbf{82.5} & \textbf{82.6} & \textbf{76.0} & \textbf{77.6} & \textbf{83.5} & \textbf{91.5} & \textbf{90.5} & \textbf{85.9} & \textbf{75.7} & \textbf{78.5} & \textbf{83.9}\\ \bottomrule \end{tabular}}} \end{center} \vspace{-0.5cm} \end{table*} \subsection{Implementation details} We use PoseNet of 3DMPPE~\cite{3dmppe} to generate our input 3D human pose. This model is trained on large-scale training data which includes H3.6M single-person 3D dataset~\cite{ionescu2013human3}, MPII\cite{andriluka14cvprmpii} and COCO 2D dataset~\cite{lin2014microsoftcoco}, MuCo multi-person 3D dataset~\cite{singleshot}, and extra synthetic data. PI-Net is trained on 33.4k composited MuCo data, which is contained in the training data of the baseline model. This ensures that the improvement of PI-Net comparing with the baseline model is not caused by adding extra training data. In terms of dimensions, 3DMPPE~\cite{3dmppe} outputs $J= 17$ joints in 3D, the hidden recurrent layers are of dimension $256$, and the Bi-RNN outputs an embedding vector of dimension $E = 512$. We train our PI-net using Adam optimization and the \textit{poly learning rate policy}~\cite{zhao2017pyramid}, with initial learning rate of 1e-5, final learning rate of 1e-8, and power of 0.9, for 25 epochs. Batch size is set to 4. When testing on an image with $n$ instances, we test for $n$ independent times, each time with a different ordering, and just retain the first person in each case. \vspace{0mm} \section{Experiments} We next describe the experiment section, which includes a description of the datasets, baselines and evaluation metrics. We then provide a quantitative and qualitative evaluation and comparison to state-of-the-art approaches. We finalize this section with an exhaustive ablation study of the PI-Net architecture and hyperparameters. \subsection{Datasets} \vspace{0mm} \noindent\textbf{MuCo-3DHP dataset and MuPoTS-3D dataset.} Most experiments discussed below are performed using these two well-known datasets. They were initially introduced by Mehta et al.~\cite{singleshot} and are typically used as train set and test set respectively, for the task of multi-person 3D human pose estimation. MuCo-3DHP is a multi-person 3D human pose dataset. Our PI-Net is trained on $33.4k$ MuCo images with $80.7k$ instances, without any other extra data. MuPoTS-3D test set includes $8320$ images with $23k$ instances in $20$ real scenes ($5$ indoor scenes and $15$ outdoor scenes). Each scene contains from $200$ to $800$ frames extracted from a video, with $2$ or $3$ people performing a certain common activity such as talking, shaking hands or doing sports. These two datasets are annotated using COCO format and provide both 2D image coordinates and 3D camera coordinates for each body joint. \vspace{1mm} \noindent\textbf{COCO dataset.} We also perform qualitative results using the COCO dataset. This is a large-scale multi-person human pose dataset and, even though it just provides 2D ground truth labels, it depicts challenging scenes with a large number of people performing very diverse actions. In particular, we use examples from the COCO val2017 subset \cite{maskrcnn}. \begin{table*}[htbp!] \caption{PA MPJPE (top) and MPJPE (bottom) comparisons of PI-net with the state-of-the-art method~\cite{3dmppe} used as our baseline on the MuPoTS dataset. The average value indicated image-wise average. Ground truth bounding boxes and roots are used for testing. Lower value means better performance.\vspace{-0.5cm} \label{tab:mpjpe(mm)} \begin{center} \resizebox{\textwidth}{!}{\setlength{\tabcolsep}{0.7mm}{ \begin{tabular}{l c c c c c c c c c c c c c c c c c c c c c} \toprule Sequence & S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10 & S11 & S12 & S13 & S14 & S15 & S16 & S17 & S18 & S19 & S20 & AVG\\ \midrule\midrule \multicolumn{22}{l}{\textbf{PA MPJPE (mm)}} \\\midrule 3DMPPE~\cite{3dmppe} & 67.7 & 102.6 & 82.7 & 82.5 & 79.8 & \textbf{91.1} & 70.8 & 110.1 & 72.8 & 63.5 & 88.6 & 79.6 & 105.1 & 110.5 & 77.5 & 72.2 & 73.3 & 86.8 & 91.9 & 120.0 & 88.4\\ PI-Net (ours) & \textbf{65.8} & \textbf{97.7} & \textbf{82.2} & \textbf{82.4} & \textbf{77.7} & 91.6 & \textbf{68.6} & \textbf{106.3} & \textbf{70.0} & \textbf{60.5} & \textbf{88.0} & \textbf{77.7} & \textbf{102.3} & \textbf{106.6} & \textbf{75.5} & \textbf{70.2} & \textbf{71.5} & \textbf{83.7} & \textbf{88.9} & \textbf{112.6} & \textbf{85.79}\\ \midrule\midrule \multicolumn{22}{l}{\textbf{MPJPE (mm)}}\\\midrule 3DMPPE~\cite{3dmppe} & 90.9 & 159.3 & 121.8 & 113.5 & 107.8 & \textbf{121.1} & 113.8 & 138.2 & 99.7 & 98.4 & 119.6 & 115.4 & 143.7 & 151.7 & 111.7 & 101.8 & 105.6 & 115.8 & 140.7 & 187.7 & 126.0\\ PI-Net (ours) & \textbf{87.3} & \textbf{151.3} & \textbf{117.1} & \textbf{109.9} & \textbf{103.9} & \textbf{121.1} & \textbf{108.7} & \textbf{133.9} & \textbf{95.8} & \textbf{93.0} & \textbf{117.0} & \textbf{112.2} & \textbf{141.1} & \textbf{146.2} & \textbf{108.0} & \textbf{98.0} & \textbf{102.5} & \textbf{111.8} & \textbf{136.2} & \textbf{178.4} & \textbf{121.7}\\ \bottomrule \end{tabular}}} \end{center} \vspace{-0.5cm} \end{table*} \vspace{1cm} \begin{table*}[htbp!] \caption{Joint-wise 3DPCK comparison with state-of-the-art methods on the MuPoTS-3D dataset. The first three methods show the reported results in the corresponding paper, the fourth method and our model is tested with ground truth bounding boxes and roots. All ground truths are used for evaluation. Higher value means better performance.\vspace{-0.5cm}} \label{tab:jointwise pck} \begin{center} \setlength{\tabcolsep}{3mm}{ \begin{tabular}{l c c c c c c c c c c c} \toprule Method & Hd. & Nck. & Sho. & Elb. & Wri. & Hip & Kn. & Ank. & Avg\\ \midrule\midrule LCR\cite{lcr} & 49.4 & 67.4 & 57.1 & 51.4 & 41.3 & 84.6 & 56.3 & 36.3 & 53.8\\ single-shot\cite{singleshot} & 62.1 & 81.2 & 77.9 & 57.7 & 47.2 & \textbf{97.3} & 66.3 & 47.6 & 66.0\\ 3DMPPE\cite{3dmppe} & \textbf{78.4} & \textbf{91.9} & 83.1 &79.7 & 67.0 & 93.9 & 84.3 & \textbf{75.3} & 81.2 \\ PI-Net (ours) & 78.3 &91.8 & \textbf{87.8} & \textbf{81.9} & \textbf{68.5} & 94.2 & \textbf{85.3} & 74.8 & \textbf{82.5}\\ \bottomrule \end{tabular}} \end{center} \vspace{-0.5cm} \end{table*} \subsection{Baseline and Evaluation metrics} \label{section:baseline} Our pipeline is capable of refining the poses estimated by any multi-person pose algorithm, independently of the strategy it uses. Given these initially estimated poses we refine them leveraging on the contextual information. In this paper, we use the recent 3DMPPE~\cite{3dmppe} as a baseline and demonstrate both quantitative and qualitative improvements. Note that previous state-of-art works such as PandaNet~\cite{benzine2020pandanet} or SingleShot~\cite{singleshot} do not provide codes either for training or testing, and hence, we could not use them as backbones. The baseline~\cite{3dmppe} consists of 3 main steps. Firstly, 2D bounding boxes of humans are detected using Mask-RCNN~\cite{maskrcnn}. For each detection, a deep network refines the coarse root 3D coordinates obtained from camera calibration parameters and, finally, a fully convolutional network~\cite{sun2018integral} predicts root-relative 3D pose. Using the 3D root position, all poses can be represented in a common camera-coordinates reference. \newline We evaluate the performance of all methods by reporting the percentage of keypoints detected by the network that are within 150mm or less from the ground truth labels (3DPCK@150mm). This is the usual evaluation metric on the MuPOTS-3D test set\cite{singleshot,lcr,lcr++,mehta2019xnect,benzine2020pandanet,3dmppe}. \newline Notice that the 3DPCK metric depends greatly on the chosen threshold, for completeness, we also provide MPJPE and PA-MPJPE metrics to evaluate the performances. MPJPE indicates mean-per-joint-position error after root alignment with the ground truth \cite{ionescu2013human3}, and PA-MPJPE denotes MPJPE after Procrustes Alignment\cite{gower1975generalized}. Lower MPJPE and PA-MPJPE indicates better performance. \subsection{Main results} \noindent\textbf{Quantitative results on MuPoTS-3D testset.} We report results of PI-Net on the MuPoTS-3D dataset in Table~\ref{tab:sequencewise pck}, and compare to current state-of-the-art methods. Our results are obtained using the model depicted in Fig.~\ref{fig:pipline}, which uses a bidirectional 3-GRU recurrent layer, followed by a self-attention layer. We provide results after root alignment with the ground-truth poses, on the two strategies usually used on the MuPoTs datasets. In table\ref{tab:sequencewise pck}, the top-rows \textit{Accuracy for all ground truths} evaluates all annotated persons, and the bottom rows \textit{Accuracy only for matched ground truths} evaluates only predictions matched to annotations by their 2D projections with the 2D ground truths. We got improvements on both of the two strategies. PI-Net outperforms all previous models and improves the state-of-the-art by 1.3\% 3DPCK@150mm on average. The improvement is consistent and shows a boost in performance for the majority of actions, setting a new state-of-the-art on the MuPoTS-3D dataset. Interestingly, we observe that the largest improvements are produced in those actions that require harmony and certain synchronization between people, such as practicing Taekwondo (S2) or playing a ball together (S14). We use ground truth bounding box and roots to test the baseline, so the root-relative result is comparable with the absolute result here. To avoid the redundancy, we only report root-relative results, which is widely reported in the previous works, for the comparison with the state-of-the-art methods. \newline Table~\ref{tab:mpjpe(mm)} shows the comparison of sequence-wise performance using MPJPE with root alignment and PA-MPJPE with further rigid alignment. Testing our model on the MuPoTS test dataset, we reduced the MPJPE error and PA-MPJPE error by 2.6mm and 4.3mm on average, respectively, in comparison with the baseline results~\cite{3dmppe}. Again, results are consistent across different tasks. \newline Table~\ref{tab:jointwise pck} shows a joint-wise comparison with state-of-art methods using 3DPCK@150mm after root alignment with ground truths. While we achieve similar performance with ~\cite{3dmppe} in head, neck and hip, our method consistently outperforms the rest of joints on arms and legs (shoulder, elbow, wrists and knees). Arguably, the joints on the torso have little influence on the interaction between people, which comes mostly through the limbs, for example hands and legs. Hence, it is reasonable that using the context information to refine 3D pose predictions gives the most significant boost in these joints. \newline Finally, it is worth pointing out that the results for all previous approaches reported in Tables~\ref{tab:sequencewise pck},~\ref{tab:mpjpe(mm)} and~\ref{tab:jointwise pck} are those of the respective papers. For 3DMPPE~\cite{3dmppe}, however, we tested on ground-truth bounding boxes and roots to reported these results. \vspace{1mm} \noindent\textbf{Qualitative results on COCO.} Figure~\ref{fig:coco} shows qualitative results on COCO dataset, for which 3D ground truths are not available. We also include (bottom-right) a failure case, caused by a misdetection of the baseline. This is maybe the major limitation of PI-Net, which is designed to refine poses, but so far, we have not integrated any module to deal with large deviations on the input poses. \begin{figure*} \begin{center} \includegraphics[width=0.8\linewidth]{figures/coco2.png} \vspace{-5mm} \caption{{\bf Qualitative results on the COCO dataset}. For each pose, a darker color is used to represent the left side of the person. The bottom-right example corresponds to a failure case, as the `red' and `black' persons should be located in front of the scene, behind the 'blue' and 'purple' persons. This is caused by a misdetection on the root position of the input detected poses provided by the baseline network, while our network designed for refining the poses could not refine this kind of large deviation, because this large deviation caused by the baseline network hinder our PI-net from learning the correct context information for correctly interpreting and refining the prediction.} \label{fig:coco} \end{center} \end{figure*} \subsection{Ablation Study} \label{sec:ablation} We next provide further analysis of the PI-Net architectural design and discuss/interpret the predicted adjacency matrix obtained in the self-attention layers. \begin{table}[t!] \caption{Comparison of different input orders. \textit{Intuitive} is the one described in Section~\ref{sec:interaction}, from near to far. \textit{Inverse} is the opposite. \textit{Random} means in random order.\vspace{-0.5cm}} \begin{center} \begin{tabular}{ c c c c c} \toprule Order & PA MPJPE (mm) & MPJPE (mm) \\ \midrule\midrule Reverse & 86.09 & 122.23 \\ Random & 85.87 & 121.88 \\ Intuitive & \textbf{85.79} & \textbf{121.7} \\ \bottomrule \end{tabular} \end{center} \vspace{-0.5cm} \label{tab:order} \end{table} \vspace{0mm} \noindent\textbf{Effect of the Input Order.} Table~\ref{tab:order} shows the effect of using different strategies to establish the ordering of the detected people fed into the Bi-RNN layer. We consider three different order: (i) a random ordering, (ii) our approach where we select the person of interest followed by people in order of proximity, and (iii) the inverse approach that person further away is firstly fed into the network. To estimate the distance between people, we compute the distances between the root coordinates of the input people to the target person. Even though the number of people in images of MuPoTS dataset is relatively small and therefore the results would not differ greatly, the ordering in which every person's information is processed has an effect in the performance of the model. As shown in the Table, the ordering we use provides the best performance and the inverse one results the worst. This demonstrates the importance of taking context into account. \begin{table}[t!] \caption{Importance of self-attention and bidirectionality (RNN). PI-Net uses a bidirectional RNN followed by a self-attention layer. We evaluate the impact of each of these choices: w/o Att. when removing attention, w/o Bi. considering standard RNN.\vspace{-0.5cm}} \begin{center} \setlength{\tabcolsep}{1mm}{ \begin{tabular}{ l c c c c} \toprule Method & PA MPJPE(mm) & MPJPE(mm) \\ \midrule\midrule PI-Net w/o Att., w/o Bi. & 86.69 & 122.7 \\ PI-Net w/o Bi. & 86.42 & 123.10\\ PI-Net w/o Att. & 85.92 & 122.01 \\ PI-Net & \textbf{85.79} &\textbf{121.7} \\ \bottomrule \end{tabular}} \end{center} \vspace{-0.5cm} \label{tab:attention} \end{table} \vspace{1mm} \noindent\textbf{Effect of self-attention and bidirectional RNN.} In Table~\ref{tab:attention} we analyse the effect of using the self-attention layer, which confirms that it helps to boost the performance. We also study the attention weights predicted by the self-attention layer. These weight are, as expected, large at the diagonal, which corresponds to the self-interaction. The larger the distance between two person is, the smaller the weights tend to be. Table~\ref{tab:attention} also compares our approach which employs Bi-RNN with a standard (not bidirectional) RNN. The ablation of the recurrent unit is done later one. Bi-RNN reduces 0.69mm the MPJPE error and 0.77mm the PA-MPJPE error, while the self-attention layers gives an extra improvement of 0.31mm on MPJPE and 0.13mm on PA-MPJPE. \begin{table}[t!] \caption{Ablating the unit of the interaction network: None~\cite{3dmppe}, Graph Convolutional Networks (GCN); LSTM and Gated Recursive Units (GRU), with (2,3,4) layers.\vspace{-0.5cm}} \begin{center} \setlength{\tabcolsep}{2mm}{ \begin{tabular}{ l c c c c} \toprule Interaction & PA MPJPE (mm) & MPJPE (mm) & \# Par.\\ \midrule\midrule None~\cite{3dmppe} & 88.36 & 126.0 & 133M\\ GCN & 88.67 & 126.3 & 34M\\ \midrule 2 LSTM & 86.45 & 122.5 & 2.78M\\ 3 LSTM & 86.17 & 122.3 & 4.36M\\ 4 LSTM & 86.32 & 121.7 & 5.93M\\ \midrule 2 GRU & 86.27 & 122.2 & 2.23M \\ \textbf{3 GRU} & \textbf{85.79} & \textbf{121.7} & 3.41M \\ 4 GRU & 85.96 & 122.2 & 4.59M\\ \bottomrule \end{tabular}} \end{center} \vspace{-5mm} \label{tab:lstm} \end{table} \vspace{1mm} \noindent\textbf{Interaction unit.} In Table~\ref{tab:lstm} we report results using alternative units to take the interaction into account. More precisely, Graph Convolution Network (GCN) and LSTM/GRU with different number of layers. For the experiment with GCN, we learned an adjacency matrix for every pair of persons and represented the interaction between them. We considered $4$ GCN layers to obtain the refined poses. We also ablated the recurrent unit: GRU or LSTM~\cite{gers1999lstm}. Even though the MPJPE error of $4$ LSTM layers is similar to that of $3$ GRU layers, we considered the latter because it performs better after rigid alignment, and uses much less parameters which enables it to be trained more efficiently. \vspace{-1mm} \section{Conclusion} We propose PI-Net, a pose-interacting network that takes initial 3D body poses predicted by any pose estimator, and refine them leveraging on the mutual interaction that occurs in multi-person scenes. We learn such interactions using 3 main building blocks: a bi-directional RNN, a self-attention module, and a MLP. PI-Net is very flexible, lightweight and cost-efficient, and it could improve other approaches for multi-person 3D human pose estimation, establishing the new state-of-the-art. This line of work focuses on the interaction between people to improve perception results. In the future, we plan to extend this approach to reason on other contextual information such as objects or structures to better understand human actions and explore different ways to interpret relationships in the scene. Exploiting temporal priors~\cite{hernandeziccv2019,Simo_ijcv2017} and exploring other regression techniques such as robust deep regression~\cite{lathuiliere2018deepgum} or regression adaptation~\cite{fabre2017automatic,hueber2015speaker}, are also other avenues we will explore. \vspace{-1mm} \section{Acknowledgement} We thank Yuming DU for inspiring discussions and feedback. This work has been partially funded by an Amazon Research Award and by the Spanish government under projects HuMoUR TIN2017-90086-R, Maria de Maeztu Seal of Excellence MDM-2016-0656, by the ANR JCJC ML3RI ANR-19-CE33-0008 and the ANR IDEX PIMPE ANR-15-IDEX-02. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-10-13T02:24:12', 'yymm': '2010', 'arxiv_id': '2010.05302', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05302'}
arxiv
\section{Introduction} In the last few years, deep reinforcement learning (DRL) has been widely adopted in different fields, ranging from playing video games~\cite{mnih2013DRL}, playing chess~\cite{silver2016Go}, to robotics~\cite{levine2016Robotic}. DRL provides a flexible solution for many types of problems due to the fact that it does not need to model complex systems or to label data for training. Utilizing recurrent neural networks (RNNs) in DRL, the deep recurrent Q-network (DRQN) is introduced to process the temporal correlation of input sequences in a non-Markovian environment~\cite{hausknecht2015DRQN}. Even though DRQN is a powerful machine learning tool, it faces serious issues related to training due to the following two reasons: 1) DRL requires a relatively large amount of training data and computational resources to make the learning agent converge to an appropriate policy, which is a major bottleneck for applying DRL to many real-world applications~\cite{he2017learning}. 2) The kernel of DRQN, the RNN, has issues related to vanishing and exploding gradients that make the underlying training difficult~\cite{2013RNNdifficulty}. Therefore, the difficulties of training DRL agents and RNNs make the training of DRQNs an extremely challenging problem and prevent it from being widely adopted for analyzing time-dynamic applications. In light of the training challenges, in this work we exploit a special type of RNNs, echo state networks (ESNs), to reduce the training time and the required training data~\cite{jaeger2001echo}. ESNs simplify the underlying RNNs training by only training the output weights while leaving input weights and recurrent weights untrained. Existing research shows that ESNs can achieve comparable performance with RNNs, especially in some tasks requiring fast learning~\cite{tanaka2019RC}. Accordingly, in this work, we adopt ESNs as the Q-networks in the DRL framework, which is referred to as deep echo state Q-networks (DEQN). We will show that DEQN has the benefit of learning a good policy with short training time and limited training data. Fueled by the popularity of smartphones as well as the upcoming deployment of the fifth generation (5G) mobile broadband networks, mobile data traffic will grow at a compound annual growth rate (CAGR) of 46 percent between 2017 and 2022, reaching 77.5 exabytes (EB) per month by 2022~\cite{cisco2018VNI}. A significant portion of these data traffic will be real-time or delay-sensitive. For example, live video will grow 9-fold from 2017 to 2022 while virtual reality and augmented reality traffic will increase 12-fold at a CAGR of 63 percent. This suggests that future wireless networks will likely face the pressing demand of being able to conduct real-time processing for large volume data in an efficient way. In 5G networks, massive connectivity is regarded as a primary use case with dynamic spectrum sharing (DSS) as an enabling technology. In fact, DSS has been announced as the key technology for 5G by many companies and operators around the world including Qualcomm, Ericsson, AT\&T, and Verizon~\cite{DSS19,VerizonDSA19}. Unlike the current static spectrum management policy that gives a single system exclusive right to access the spectrum, DSS has a more flexible policy by adopting a hierarchical access structure with primary users (PUs) and secondary users (SUs)~\cite{ahmad20205g}. SUs are allowed to access the licensed spectrum when PUs receive tolerable interference. Obtaining control information from the environment is costly in 5G mobile wireless networks. First, a SU cannot detect the activities of all PUs simultaneously because performing spectrum sensing is energy-consuming. Second, exchanging control information between wireless devices imposes a control overhead in wireless network operations. Therefore, the major challenge of DSS is how to optimize the system performance under limited information exchange between the secondary system and the primary system. DRL is a suitable framework for developing DSS strategies because of its abilities to adapt to unknown environment without modeling the complex 5G networks. DRL usually requires tons of training data and long training time. However, wireless networks are dynamic due to factors such as path loss, shadow fading, and multi-path fading~\cite{tse2005fundamentals}, which largely decreases the number of effective training data that reflect the latest environment. Furthermore, the performance of spectrum sharing depends on access strategies of multiple users. If one user changes its access strategy, then other users have to change their access strategies accordingly. Under these circumstances, the number of effective training samples reflected in the latest wireless environment will be extremely limited. As a result, designing an efficient DRL framework only requiring a small amount of training data will be critical for 5G and future 6G DSS networks. In this work, we introduce DEQN to learn a spectrum access strategy for each SU in a distributed fashion with limited training data and short training time in the highly dynamic 5G networks. The main contributions of our work are as follows: \begin{itemize} \item We design an efficient DRL framework, DEQN, to adapt to highly dynamic environment with limited training data and provide training strategies for the introduced DEQN. \item We apply the DEQN method in the critical problem of DSS for 5G networks where the system is highly dynamic and interactive. Compared to existing DRL-based strategies, our method can quickly adapt to real mobile wireless environment to achieve improved network performance under limited training data. \item This work is the first to formulate a DRL strategy that jointly considers spectrum sensing and spectrum sharing in the underlying DSS network for 5G. \end{itemize} \section{Problem Definition for DSS} In this section, we introduce the DSS problem and discuss its challenges. We consider a DSS system where the primary network consisting of $M$ PUs and the secondary network consisting of $N$ SUs. It is assumed that one wireless channel is allocated to each PU individually and cross-channel interference is negligible. We consider a discrete time model, where the dynamics of the DSS system, such as behaviors of users and changes of the wireless environment, are constrained to happen at discrete time slots $t$ ($t$ is a natural number). Our goal is to develop a distributive DSS strategy for each SU to increase the spectrum utilization without harming the primary network's performance. \begin{figure}[t] \centering \includegraphics[width=0.9\linewidth]{TNNLS_System_Model.png} \caption{The desired links, the interference links, and the sensing links when PU1, SU1, and SU2 are operating on the same channel. PUT/SUT represent the transmitters of PU/SU and PUR/SUR represent the receivers of PU/SU. } \label{fig:system_model} \end{figure} The data of an user are transmitted over the wireless link between its transmitter and receiver. Signal-to-interference-plus-noise ratio (SINR) is a quality measure of the wireless connection that compares the power of a desired signal to the sum of the interference power and the power of background noise. The higher value of the SINR, the better quality of the wireless connection. The SINR of the user $k$'s wireless connection on channel $m$ at time slot $t$ is written as \begin{equation} \text{SINR}^{k}_{m} [t] = \frac{P^k \cdot \left| H^k[t] \right|^2}{\sum\limits_{z \in \Phi_m^k} P^z \cdot \left| H^{zk}[t] \right|^2 + N_m} \label{eqn:sinr} \end{equation} where $P^k$ and $P^z$ are the transmit power of the user $k$ and the user $z$, respectively, $\Phi_m^k$ is the set containing all the users that are transmitting on channel $m$ except for the user $k$, $H^k[t]$ is the channel gain of the desired link of the user $k$, $H^{zk}[t]$ is the channel gain of the interference link between the user $z$'s transmitter and the user $k$'s receiver, and $N_m$ is the background noise power on channel $m$. Note that all channel gains are changing over time so SINR is also time-variant. The desired link is the link between the transmitter and the receiver of the same user. The interference link is the link between the transmitter and the receiver of two different users if these two users are transmitting on the same channel simultaneously. Figure~\ref{fig:system_model} shows the complicated association of desired links and interference links when PU1, SU1, and SU2 are operating on the same channel. Since cross-channel interference is negligible, the interference link between two users operating on different channels is out of consideration. The radio signal attenuates as it propagates through space between the transmitter and the receiver, which is referred to as the path loss. In addition to the path loss, the channel gain is affected by many factors such as shadow fading and multi-path fading. Shadow fading is caused by a large obstacle like a hill or a building obscuring the main signal path between the transmitter and the receiver. Multi-path fading occurs in any environment where multiple propagation paths exist between the transmitter and the receiver, which may be caused by reflection, diffraction, or scattering. In telecommunication society, the channel model is carefully designed to be consistent with wireless field measurements. We generate channel gains based on the WINNER II channel model~\cite{winner2}, which is widely used in industry to make fair comparisons of telecommunication algorithms. To enable the protection of the primary network, we assume that a PU will broadcast a warning signal if its data transmission experiences a low SINR. There are two possible causes for low SINR. First, the wireless connection of the desired link of the PU is in deep fade, which means the channel gain of the desired link is low. This leads to a small value of the numerator in Equation (\ref{eqn:sinr}) so SINR is low. Second, the signals from one or more SUs cause strong interference to a PU when they are transmitting over the same wireless channel at the same time. This leads to a large value of the denominator in Equation (\ref{eqn:sinr}), so SINR assumes a low value again. We called SUs "collides" with the PU in this case. The warning signal contains information related to which PU may be interfered so that the SUs transmitting on the same channel are aware of the issue. In fact, this kind of warning signal is similar to the control signals (e.g. synchronization, downlink/uplink control) used in current 4G and 5G networks. It is common to assume that the control signals are received perfectly at receivers, otherwise the underlying network will not even work. In reality, the control signal can be transmitted through a dedicated control channel. According to this mechanism, a PU will broadcast a warning signal once the received SINR is low, and this is the only control information from the primary system to the secondary system to enable the protection for PUs under DSS. Note that a PU may send a warning signal even when no collisions happen because of deep fade. The activity of a PU consists of two states: (1) \textit{Active} and (2) \textit{Inactive}. If a PU is transmitting data, it is in \textit{Active} state, otherwise it is in \textit{Inactive} state. A spectrum opportunity on a channel occurs when the licensed PU of that channel is in \textit{Inactive} state or any SU can transmit on that channel with little interference to the \textit{Active} licensed PU. Unfortunately, it is difficult for a SU to obtain the information of activity states of PUs or the interference that it will cause in the highly dynamic 5G networks. A SU has to perform spectrum sensing to detect the activity of a PU, but the accuracy of detection is based on the wireless link between the transmitters of the PU and the SU, the background noise, and the transmit power of the PU. On the other hand, the interference level caused by a SU is determined by the interference link from the SU to the PU, the desired link of the PU, transmit powers of the PU and the SU, and the background noise. Furthermore, all these factors for determining spectrum opportunities are time-variant so control information becomes outdated quickly. Since obtaining control information is costly in 5G mobile wireless networks, it is impractical to design a DSS strategy by assuming that all the control information is known. SUs should provide protection to prevent PUs from harmful interference since the primary system is the spectrum licensee. A commonly used method is that the transmitter of a SU performs spectrum sensing to detect the activity of a PU before accessing a channel. Due to the power and complexity constraints, a SU is unable to perform spectrum sensing across all channels simultaneously. Therefore, we assume that a SU can only sense one channel at a particular time. We adopt the energy detector as the underlying spectrum sensing method, which is the most common one due to its low complexity and cost. The energy detector of SU $n$ first computes the energy of received signals on channel $m$ as follows: \begin{equation} E_m^n [t] = \sum_{t'=t}^{t+T_s-1} \left| y_m^n[t'] \right|^2 \label{eqn:sensed_energy} \end{equation} where $t$ is the starting time slot of the spectrum sensing, $y_m^n[t']$ is the received signal at time slot $t'$, and $T_s$ is the number of time slots of the spectrum sensing. We consider the half-duplex SU system where a SU cannot transmit data and perform spectrum sensing at the same time. We assume a periodic time structure of spectrum sensing and data transmission as shown in Figure~\ref{fig:sensing_period}. To be specific, the $k^{th}$ sensing and transmission period contains $T$ time slots from $kT + 1$ to $(k+1)T$, the spectrum sensing contains the first $T_s$ time slots in the period from $kT + 1$ to $kT + T_s$, and the data transmission contains the subsequent $T-T_s$ time slots in the period from $kT + T_s + 1$ to $(k+1)T$. \begin{figure}[ht] \centering \includegraphics[width=1.0\linewidth]{sensing_period.png} \caption{The time structure of spectrum sensing and data transmission.} \label{fig:sensing_period} \end{figure} The received signal $y_m^n[t']$ depends on the activity state of PU $m$, the power of PU $m$, the background noise, and the sensing link between the transmitters of PU $m$ and SU $n$. When PU $m$ is in the \textit{Inactive} state, the received signal is represented as \begin{equation} y_m^n[t'] = \omega_m[t'] \end{equation} When PU $m$ is in the \textit{Active} state, the received signal is represented as \begin{equation} y_m^n[t'] = \sqrt{P^m} \cdot H^{mn}[t'] + \omega_m[t'] \end{equation} where $\omega_m[t'] \sim \mathcal{CN}(0, N_m)$ is a circularly-symmetric Gaussian noise with zero mean and variance $N_m$, $P^m$ is the transmit power of PU $m$, and $H^{mn}[t]$ is the channel gain of the sensing link between the transmitters of PU $m$ and SU $n$. If the energy computed in Equation (\ref{eqn:sensed_energy}) is higher than a threshold, the PU is considered in the \textit{Active} state, otherwise the PU is considered in the \textit{Inactive} state. The challenge of designing an energy detector is how to set the threshold properly. The value of the threshold is actually a trade-off between the detection probability and the false alarm probability. However, setting the threshold for achieving a good trade-off is related to many factors, including the channel gain of the sensing link, the transmit power of the PU, the noise variance, the number of received signals, etc. This information is difficult to obtain before deploying in the real environment and is time-variant. Furthermore, setting a threshold is difficult in some cases because of the relative positions of transmitters and receivers. As shown in Figure~\ref{fig:system_model}, the sensing link is between the transmitters of the PU and the SU, but the interference link is between the transmitter of the SU and the receiver of the PU. The discrepancy between the sensing link and the interference link may cause the hidden node problem, where the sensing link is weak but the interference link is strong. For example, the transmitters of a SU and a PU are far away from each other while the SU transmitter is close to the receiver of the PU. In this case, the transmitters of the SU and the PU are hidden nodes with respect to each other. The warning signals from PUs are designed to provide additional protection to the primary system for the case where the SU cannot detect the activity of the PU, thereby mitigating the issues caused by the hidden nodes. Meanwhile, instead of making the spectrum access decision solely based on the outcomes of the energy detector, we developed a DRL framework to construct a novel spectrum access policy: The DRL agent will use the sensed energy as the input to learn a spectrum access strategy to maximize the cumulative reward. The reward is designed to maximize the spectral-efficiencies of SUs while enabling the protection for PUs with the help of warning signals from PUs. \section{DRL Framework for DSS and DEQN} \subsection{Background on DRL} \label{subsec:background_DRL} RL is one type of machine learning method that provides a flexible architecture for solving many types of practical problems because it does not need to model complex systems or to label data for training. In RL, an agent learns how to select actions to maximize the cumulative reward in a stochastic environment. The dynamics of the environment is usually modeled as a Markov decision process (MDP), which characterized by a tuple $(\mathcal{S}, \mathcal{A}, \mathcal{P}, R, \mathcal{\gamma})$, where $\mathcal{S}$ is the state space, $\mathcal{A}$ is the action space, $\mathcal{P}$ is the state transition providing $\Pr(s_{t+1} |s_{t}, a_{t})$, $R$ is the reward function providing $r_t = R(s_{t}, a_{t})$, and $\gamma$ is a discount factor for calculating cumulative reward. Specifically, at time $t$, the state is $s_{t} \in \mathcal{S}$, the RL agent selects an action $a_{t} \in \mathcal{A}$ by following a policy $\pi(s_t)$ and receives the reward $r_t$, and then the system shifts to the next state $s_{t+1}$ according to the state transition probability. Note that the action $a_{t}$ affects both the immediate reward $r_t$ and the next state $s_{t+1}$. Consequently, all subsequent rewards are affected by the current action. The goal of RL agent is to find a policy $\pi$ to maximize the cumulative reward, $\mathbb{E}_{\pi} \left[ \sum_{t=1}^{\infty} \gamma^{t-1} r_{t} \right]$. In RL, a model-free algorithm does not require state transition probability for learning, which is useful when the underlying system is complicated and difficult to model. Q-learning~\cite{watkins1992qlearn} is the most widely used model-free RL algorithm that aims to find the Q-function of each state-action pair for a given policy, which is defined as \begin{equation} Q^{\pi}(s_t, a_t) = \mathbb{E} \left[ \sum_{t' = 1}^{\infty} \gamma^{t'-1} r_{t'} \mid s_1 = s_t, a_1 = a_t \right]. \end{equation} Q-function represents the cumulative reward when taking action $a_t$ in the state $s_t$ and then following policy $\pi$. Q-learning constructs a Q-table to estimate the Q-function of each state-action pair by iteratively updating each element of the Q-table through dynamic programming. The update rule of the Q-table is given as follows: \begin{equation} \begin{aligned} Q(s_t, a_t) & \leftarrow Q(s_t, a_t) \\ &+ \alpha \left[ r_t + \gamma \max\limits_{a} Q(s_{t+1}, a) - Q(s_t, a_t) \right], \end{aligned} \end{equation} where $\alpha \in (0,1)$ is the learning rate. The policy $\pi$ that selects action is the $\epsilon$-greedy policy as follows: \begin{equation} a_{t} = \begin{cases} \argmax_a Q(s_t, a) & \text{, with probability } 1-\epsilon, \\ \text{random action} & \text{, with probability }\epsilon, \end{cases} \end{equation} where $\epsilon \in [0, 1]$ is the exploration probability. However, Q-learning performs poorly when the dimension of the state is high because updating a large Q-table makes training difficult or even impossible. Deep Q-Networks (DQN)~\cite{mnih2013DRL} is introduced to solve high-dimensional state problems by leveraging a neural network as the function approximator of the Q-table, which is referred to as the Q-network. Specifically, the Q-network takes the state $s_t$ as input and outputs the estimated Q-function of all possible actions. One key approach of DQN to improve the training stability is by creating two Q-networks: the evaluation network $Q(s, a; \theta)$ and the target network $Q(s, a; \theta^{-})$. The target network is used to generate the targets for training the evaluation network while the evaluation network is used to determine the actions. The loss function for training the evaluation network is written as \begin{equation} \left( r_t + \gamma \max\limits_{a} Q(s_{t+1}, a; \theta^{-}) - Q(s_t, a_t; \theta) \right)^2, \end{equation} where $r_t + \gamma \max\limits_{a} Q(s_{t+1}, a; \theta^{-})$ is the target Q-value. The weights of the target network $\theta^{-}$ is periodically synchronized with the weights of the evaluation network $\theta$. The purpose is to fix targets temporarily during training to improve the training stability of the evaluation network. An improvement of DQN to prevent overestimation of Q-values is called double Q-learning~\cite{van2016ddqn}, where the evaluation network is used to select the action when computing the target Q-value, but the target Q-value is still generated by the target network. Specifically, the target Q-value for the evaluation network is calculated by \begin{equation} r_t + \gamma Q(s_{t+1}, a'; \theta^{-}), \end{equation} where $a' = \argmax\limits_{a} Q(s_{t+1}, a; \theta)$. Double Q-learning can improve the accuracy in estimating Q-function, thereby improves the learned policy. \subsection{Existing DRL-based Strategies for DSS} DRL-based methods have recently been applied in dynamic spectrum access (DSA) networks~\cite{wang2018deep,naparstek2018deep, Chang2019DSA} where the focus is exclusively on the "access" part of the problem with over-simplified network setup. To be specific, \cite{wang2018deep} considers single SU selects one channel to access in the multichannel environment, and the goal is to maximize the number of selecting good channels for access. \cite{naparstek2018deep} assumes that the available spectrum channels are known a priori and develops a centralized spectrum access algorithm for multi-user access. Both \cite{wang2018deep} and \cite{naparstek2018deep} assumes that one channel can only be used by one user at any particular time. Although \cite{Chang2019DSA} considers multiple SUs can access a channel at the same time, a SU cannot access a channel that a PU is using. \cite{Chang2019DSA} also assumes that each SU can sense all channels simultaneously and the collision between a PU and a SU can be perfectly detected. In this work, in order to provide a comprehensive study for the impact of DEQN on relevant DSS networks for 5G, we consider practical situations of DSS where 1) mobile users cannot conduct spectrum sensing perfectly. 2) mobile users cannot sense multiple channel at a particular time. 3) there are multiple PUs and multiple SUs in a DSS network. 4) A channel can be shared by multiple users if the interference between them is weak. Furthermore, unlike previous work which utilizes binary ACK/NACK feedback as the reward function, we calculate the practical reward based on the spectral-efficiency of each mobile link. To be closely in line with the real wireless environment, the spectral-efficiency of a mobile link is calculated using the transmission procedure defined in the telecommunication standard. In this way, we can train and evaluate the underlying DEQN-based DRL strategies in realistic 5G application scenarios. It is important to note that in our work we treat the unprocessed soft spectrum sensing information as the input states of the DRL agent. Soft spectrum sensing information can be directly obtained from spectrum sensing sensors. Through the soft spectrum sensing input, the DRL agent will learn an appropriate detection criterion for each SU that adapts to different mobile wireless environments, geometry of mobile users, and activities of mobile users. This is indeed the first work to study DSS that combines soft spectrum sensing information and spectrum access strategies through the DRL framework. \subsection{DRL Problem Formulation for DSS} We now formulate the DSS problem using the DRL framework, where all SUs in the secondary system learn their spectrum access strategies in a distributed fashion through the interactions with the mobile wireless environment. To be specific, we assume that each SU has a DRL agent that takes its observed state as the input and learns how to perform spectrum sensing and access actions in order to maximize its cumulative reward. The reward for each SU is designed to maximize its spectrum efficiency and to prevent harmful interference to PUs. The state of SU $n$ in the $k^{\text{th}}$ sensing and transmission period is denoted by \begin{equation} s^n[k] = \left(E^n [k], Q^n [k] \right), \label{eqn:state} \end{equation} where $k$ is a non-negative integer, $E^n[k]$ is the energy of received signals, and $Q^n[k]$ is a one-hot $M$-dimensional vector indicating the sensed channel from time slots $kT + 1$ to $kT + T_s$. If the index of the sensed channel is $m$, then the $m^{\text{th}}$ element of $Q^n[k]$ is equal to one while other elements of $Q^n[k]$ are zeros. On the other hand, $E^n [k]$ is equal to $E^n_m [kT]$ that is calculated by Equation (\ref{eqn:sensed_energy}). The action of SU $n$ in the $k^{\text{th}}$ sensing and transmission period is denoted by \begin{equation} a^n[k] = \left( q^n[k], z^n[k] \right), \end{equation} where $q^n[k] \in \{0, 1\}$ represents SU $n$ will either access the current sensed channel ($q^n[k] = 1$) or be idle ($q^n[k] = 0$) during the data transmission part of the $k^{\text{th}}$ period (from time slots $kT + T_s + 1$ to $(k+1)T$), $z^n[k] \in \{1, ..., M\}$ represents SU $n$ will sense channel $z^n[k]$ during the sensing part of the $(k+1)^{\text{th}}$ period (from time slots $(k+1)T + 1$ to $(k+1)T + T_s$). In other words, SU $n$ makes two decisions: $q^n[k]$ decides whether to conduct data transmission in the current sensed channel of the $k^{\text{th}}$ period and $z^n[k]$ decides which channel to sense in the $(k+1)^{\text{th}}$ period. Therefore, the dimension of each SU's action space is $2M$. Note that the sensed channel in the $k^{\text{th}}$ period may be different from that in the $(k+1)^{\text{th}}$ period \begin{table}[ht] \centering \caption{The SINR and CQI mapping to modulation and coding rate. } \label{tab:cqi_table} \begin{tabular}{ccccc} \toprule CQI index & SINR & modulation & code rate & efficiency \\ & ($\geq$) & & ($\times$1024) & (bits per symbol)\\ \midrule 0 & \multicolumn{4}{c}{out of range} \\ 1 & -6.9360 & QPSK & 78 & 0.1523 \\ 2 & -5.1470 & QPSK & 120 & 0.2344 \\ 3 & -3.1800 & QPSK & 193 & 0.3770 \\ 4 & -1.2530 & QPSK & 308 & 0.6016 \\ 5 & 0.7610 & QPSK & 449 & 0.8770 \\ 6 & 2.6990 & QPSK & 602 & 1.1758 \\ 7 & 4.6940 & 16QAM & 378 & 1.4766 \\ 8 & 6.5250 & 16QAM & 490 & 1.9141 \\ 9 & 8.5730 & 16QAM & 616 & 2.4063 \\ 10 & 10.3660 & 64QAM & 466 & 2.7305 \\ 11 & 12.2890 & 64QAM & 567 & 3.3223 \\ 12 & 14.1730 & 64QAM & 666 & 3.9023 \\ 13 & 15.8880 & 64QAM & 772 & 4.5234 \\ 14 & 17.8140 & 64QAM & 873 & 5.1152 \\ 15 & 19.8290 & 64QAM & 948 & 5.5547 \\ \bottomrule \end{tabular} \end{table} In our work, we use a discrete reward function which is similar to the existing DRL-based DSS methods. Compared to a simple binary reward ($0$ and $+1$, $-1$ and $+1$) in \cite{wang2018deep} and \cite{naparstek2018deep}, we consider a more relevant and comprehensive reward design that is based on the underlying achieved modulation and coding strategy (MCS) adopted in the 3GPP LTE/LTE-Advanced standard~\cite{LTE}. To be specific, a receiver measures SINR to evaluate the quality of the wireless connection and feedback the corresponding Channel Quality Indicator (CQI) to the transmitter~\cite{liu2012downlink}. In this work, we follow the method presented in~\cite{chiumento2015CQI} to map the received SINR to the CQI. After receiving the CQI, the transmitter determines the MCS for data transmission based on the CQI table specified in the 3GPP standard~\cite{LTE}. The SINR and CQI mapping to MCS is given in Table~\ref{tab:cqi_table} for reference. Accordingly, the achieved spectral-efficiency can be calculated by (bits/symbol) = (modulation’s power of 2) $\times$ (code rate) representing the average information bits per symbol. This critical metric is utilized as the reward function of our design. To jointly consider the performance of the primary and the secondary systems, the reward function corresponding to SU $n$ accessing channel $m$ depends on both the spectral-efficiency of SU $n$ and PU $m$. During time slots $kT + T_s + 1$ to $(k+1)T$, the average spectral-efficiency of SU $n$, $\bar{e}^n[k]$, and the average spectral-efficiency of PU $m$, $\bar{e}^m[k]$, are calculated by \begin{align} \begin{aligned} \bar{e}^n[k] &= \frac{1}{T-T_s} \sum_{t'=kT+T_s}^{(k+1)T-1} e_m^n[t'] \\ \bar{e}^m[k] &= \frac{1}{T-T_s} \sum_{t'=kT+T_s}^{(k+1)T-1} e_m^m[t'] \end{aligned} \label{eqn:efficiency_SU} \end{align} where $e_m^n[t']$ and $e_m^m[t']$ represent the spectral-efficiency of SU $n$ and PU $m$ on channel $m$ at time slot $t'$, respectively. The reward of SU $n$ in the $k^{\text{th}}$ transmission period is defined as \begin{equation} {r^n[k]} = \begin{cases} -2, & \text{if } \bar{e}^m[k] < 1.5 \\ -1, & \text{if SU $n$ is idle in the $k^{\text{th}}$ period}\\ 0, & \text{if } \bar{e}^m[k] \geq 1.5 \text{ and } \bar{e}^n[k] < 1 \\ 1, & \text{if } \bar{e}^m[k] \geq 1.5 \text{ and } 1 \leq \bar{e}^n[k] < 2 \\ 2, & \text{if } \bar{e}^m[k] \geq 1.5 \text{ and } 2 \leq \bar{e}^n[k] < 3 \\ 3, & \text{if } \bar{e}^m[k] \geq 1.5 \text{ and } \bar{e}^n[k] \geq 3 \\ \end{cases} \label{eqn:reward_def} \end{equation} To enable the protection for the primary system, PU $m$ will broadcast a warning signal if its average spectral-efficiency is below $1.5$, and then the reward received by SU $n$ that accesses channel $m$ is set to $-2$. To motivate SUs to explore spectrum opportunities, the reward $r^n[k]$ is set to $-1$ if SU $n$ decides to be idle in the $k^{\text{th}}$ transmission period. When PU $m$ does not suffer from strong interference (the average spectral-efficiency of PU $m$ is larger than $1.5$), we increase the reward $r^n[k]$ from $0$ to $3$ as the average spectral-efficiency of SU $n$ increases (see Equation (\ref{eqn:reward_def})). Note that the low spectral-efficiency of a PU or a SU does not necessarily mean collisions because the underlying wireless channels are changing dynamically over time. If the channel gain of the wireless link is small, the spectral-efficiency of the user will be low even if there is no collision. Therefore, the reward function and the warning signal are introduced since it is impossible to detect collisions perfectly in practical wireless environments. \subsection{Efficient Training for DEQN} To capture the activity patterns of PUs, which are usually time-dependent, applying DRQNs is a natural choice. Although DQNs are able to learn the temporal correlation by stacking a history of states in the input, the sufficient number of stacked states is unknown because it depends on PUs' behavior patterns. RNNs are a family of neural networks for processing sequential data without specifying the length of temporal correlation. However, the training of RNNs is known to be difficult that suffers from vanishing and the exploding gradients problems. Furthermore, the required amount of training data for achieving convergence is large in the DRL scheme, since there are no explicit labels to guide the training and the agents have to learn from interacting with its environment. In the wireless environment, the channel gain of a wireless link changes rapidly, which is shown in Figure~\ref{fig:wireless_channel}. Note that the environment observed by a SU is affected by other SUs' access strategies because of possible collisions between SUs, and all SUs are dynamically adjusting their DSS strategies during their training processes. As a result, in the DSS problem, the duration for a learning environment being stable is short and the available training data is very limited. \begin{figure}[ht] \centering \includegraphics[width=.9\linewidth]{wireless_channel.png} \caption{Time-variant channel gain of a wireless link.} \label{fig:wireless_channel} \end{figure} \begin{algorithm*}[t] \caption{The training algorithm for DEQN.} \begin{algorithmic} \STATE { Initialize the wireless environment with $M$ PUs and $N$ SUs. } \STATE { Set the sensing and transmission period to $T$ time slots and the sensing duration to $T_s$ time slots. } \STATE { Set the buffer size to $Z$, the training iteration to $I$, and the exploration probability to $\epsilon$. } \STATE { Randomly initialize an evaluation network $\text{DEQN}^n_{\theta}$ and a target network $\text{DEQN}^n_{\theta^{-}}$ with the same weights for each SU $n$. } \STATE { Each SU $n$ randomly selects one channel ($= z^n[0]$) to sense for $T_s$ time slots and then computes the state $s^n[1]$. } \FOR {$q = 1, ...$} \STATE { Initialize an empty buffer $B^n_q$ for each SU. } \FOR {$z = 1, ..., Z$} \STATE { Let $k = (q-1)Z + z$. } \STATE { Each SU $n$ inputs $s^n[k]$ to $\text{DEQN}^n_{\theta}$, calculates the hidden state $h^n_{\theta}[k]$, and outputs $o^n_{\theta}[k]$. } \STATE { Each SU $n$ decides action $a^n[k] = \left( q^n[k], z^n[k] \right)$ based on $\epsilon$-greedy policy, where $a^n[k]$ is the index of the maximum element of $o^n_{\theta}[k]$ with probability $1 - \epsilon$ and $a^n[k]$ is chosen randomly with probability $\epsilon$. } \STATE { Each SU $n$ accesses channel $z^n[k-1]$ if $q^n[k]=1$ or does not access if $q^n[k]=0$ for $T-T_s$ time slots. } \STATE { Each SU $n$ obtains the reward $r^n[k]$ according to Equation (\ref{eqn:reward_def}). } \STATE { Each SU $n$ senses channel $z^n[k]$ for $T_s$ time slots and then computes the state $s^n[k+1]$. } \STATE { Each SU $n$ inputs $s^n[k+1]$ to $\text{DEQN}^n_{\theta^{-}}$, calculates the hidden state $h^n_{\theta^{-}}[k]$, and outputs $o^n_{\theta^{-}}[k]$. } \STATE { Each SU $n$ stores $(s^n[k], h^n_{\theta}[k], a^n[k], r^n[k], s^n[k+1], h^n_{\theta^{-}}[k])$ in $B^n_q$. } \ENDFOR \FOR {iteration $= 1, ..., I$} \STATE { Each SU $n$ samples random training batch $(s^n[k], h^n_{\theta}[k], a^n[k], r^n[k], s^n[k+1], h^n_{\theta^{-}}[k])$ from $B^n_q$. } \STATE { Each SU $n$ inputs $s^n[k]$ and $h^n_{\theta}[k]$ to $\text{DEQN}^n_{\theta}$ to calculate $o^n_{\theta}[k]$ } \STATE { Each SU $n$ inputs $s^n[k+1]$ and $h^n_{\theta}[k+1]$ to $\text{DEQN}^n_{\theta^{-}}$ to calculate $o^n_{\theta^{-}}[k]$ } \STATE { Each SU $n$ updates $\text{DEQN}^n_{\theta}$ by performing gradient descent step on $\left( r^n[k] + \gamma o^n_{y, \theta^{-}}[k+1] - o^n_{y, \theta}[k] \right)^2$, where $y$ is the index of the maximum element of $o^n_{\theta}[k+1]$. } \ENDFOR \STATE { Each SU $n$ synchronizes $\text{DEQN}^n_{\theta^{-}}$ with $\text{DEQN}^n_{\theta}$. } \ENDFOR \end{algorithmic} \label{alg:DEQN_training} \end{algorithm*} The standard training technique for RNNs is to unfold the network in time into a computational graph that has a repetitive structure, which is called backpropagation through time (BPTT). BPTT suffers from the slow convergence rate and needs many training examples. DRQN also requires a large amount of training data because a learning agent finds a good policy by exploring the environment with different potential policies. Unfortunately, in the DSS problem, there are only limited training data for a stable environment due to dynamic channel gains, partial sensing, and the existence of multiple SUs. To address this issue, we use ESNs as the Q-networks in the DRQN framework to rapidly adapt to the environment. ESNs simplify the training of RNNs significantly by keeping the input weights and recurrent weights fixed and only training the output weights. We denote the sequence of states for SU $n$ by $\{ s^n[1], s^n[2], ...\}$. Accordingly, the sequence of hidden states, $\{ h^n[1], h^n[2], ...\}$, is updated by \begin{equation} \begin{aligned} h^n[k] = & (1-\beta) \cdot h^n[k-1] \\ &+ \beta \cdot \text{tanh} \left( W^n_{in} s^n[k] + W^n_{rec} h^n[k-1] \right), \end{aligned} \label{eqn:hidden_state} \end{equation} where $W^n_{in}$ is the input weight, $W^n_{rec}$ is the recurrent weight, $\beta \in [0,1]$ is the leaky parameter, and we let $h^n[0] = \boldsymbol{0}$. The output sequence, $\{o^n[1], o^n[2], ...\}$, is computed by \begin{equation} o^n[k] = W^n_{out} u^n[k] \end{equation} where $u^n[k]$ is a concatenated vector of $s^n[k]$ and $h^n[k]$, and $W^n_{out}$ is the output weight. Note that the output vector $o^n[k]$ is a $2M$-dimensional vector, where each element of $o^n[k]$ corresponds to the estimated Q-value of selecting one of all possible actions given the state $s^n[1], ..., s^n[k]$. The double Q-learning algorithm~\cite{van2016ddqn} is adopted to train the underlying DEQN agent of each SU. As discussed in Section \ref{subsec:background_DRL}, each DEQN agent has two Q-networks: the evaluation network and the target network. Let the output sequence from the evaluation network and the target network be $\{o^n_{\theta}[1], o^n_{\theta}[2], ...\}$ and $\{o^n_{\theta^{-}}[1], o^n_{\theta^{-}}[2], ...\}$, respectively. The loss function for training the evaluation network of SU $n$ is written as \begin{equation} \left( r^n[k] + \gamma o^n_{y, \theta^{-}}[k+1] - o^n_{y, \theta}[k] \right)^2, \end{equation} where $o^n_{y, \theta^{-}}[k+1]$ and $o^n_{y, \theta}[k]$ are the $y^{\text{th}}$ element of $o^n_{\theta^{-}}[k+1]$ and $o^n_{\theta}[k]$, respectively, $y$ is the index of the maximum element of $o^n_{\theta}[k+1]$, $r^n[k] + \gamma o^n_{y, \theta^{-}}[k+1]$ is the target Q-value. To stabilize the training targets, the target network is only periodically synchronized with the evaluation network. The input weights and the recurrent weights of ESNs are randomly initialized according to the constraints specified by the Echo State Property~\cite{luko2012ESN}, and then they remain untrained. Only the output weights of ESNs are trained so the training is extremely fast. The main idea of ESNs is to generate a large reservoir that contains the necessary summary of past input sequences for predicting targets. From Equation (\ref{eqn:hidden_state}), we can observe that the hidden state $h^n[k]$ at any given time slot $k$ is unchanged during the training process if the input weights and recurrent weights are fixed. In contrast to conventional RNNs that usually initialize the hidden states to zeros and waste some training examples to set them to appropriate values in one training iteration, the benefit of ESNs is that the hidden states do not need to be reinitialized in every training iteration. Therefore, the training process becomes extremely efficient, which is especially suitable for learning in a high dynamic environment. Compared to storing $(s[k], a[k], r[k], s[k+1])$ in conventional DRQN framework, we also store hidden states $(h[k], h[k+1])$ because hidden states are unchanged. In this way, we do not have to waste lots of training time and data to recalculate hidden states in every training iteration. It largely boosts the training efficiency in the highly dynamic environment since we can avoid using BPTT and only update the output weights of networks. Furthermore, we can randomly sample from the replay memory to create a training batch, while conventional DRQN methods have to sample continuous sequences to create a training batch. Thus the training data can be more efficiently used in our DEQN method. The training data stored in the buffer will be refreshed periodically in order to adapt to the latest environment. Therefore, our training method is an online training algorithm that keeps updating the learning agent. The training algorithm for DEQNs in the DSS problem is detailed in Algorithm~\ref{alg:DEQN_training}. \section{Performance Evaluation} \subsection{Experimental Setup} \begin{figure}[ht] \centering \includegraphics[width=.8\linewidth]{geometry.png} \caption{The DSS network geometry. PUT/SUT represent the transmitter of PU/SU. PUR/SUR represent the receiver of PU/SU.} \label{fig:geometry} \end{figure} We set the number of PUs and SUs to 4 and 6, respectively, and the locations of PUs and SUs are randomly defined in a 2000m$\times$2000m area. The distance between the transmitter and the receiver of each desired link is randomly chosen from 400m-450m. Figure~\ref{fig:geometry} shows the geometry of the DSS network, where PUT/SUT represent the transmitters of PU/SU and PUR/SUR represent the receivers of PU/SU. The channel gains of desired links, interference links, and sensing links are generated by the WINNER II channel model widely used in 3GPP LTE-Advanced and 5G networks~\cite{winner2}. In this case, there are 4 desired links for PUs, 6 desired links for SUs, 30 interference links between different SUs, 24 interference links between SUTs and PURs, 24 interference links between PUTs and SURs, and 24 sensing links between PUTs and SUTs. Totally, 112 wireless links are generated in our simulation, which establishes a more complicated scenario than existing DRL-based DSS strategies~\cite{wang2018deep,naparstek2018deep, Chang2019DSA}. Specifically, \cite{wang2018deep} considers each channel only has two possible states (good or bad) without modeling the true wireless environment; \cite{naparstek2018deep} assumes that the collision between users can be perfectly detected without considering the dynamics of interference links; \cite{Chang2019DSA} assumes that SUs are forbidden to access a channel when a PU is using without considering the actual interference links between PUs and SUs. For each channel, the bandwidth is set to 5MHz and the variance of the Gaussian noise is set to -157.3dBm. The transmit power of PUs and SUs are both set to 500mW. We set the sensing and transmission period $T$ to 10 time slots and the sensing duration $T_s$ to 2 time slots, where one time slot represents interval of 1ms. We list all the parameters to generate the wireless environment in Table~\ref{tab:parameters}. \begin{table}[ht] \centering \caption{The values of parameters for generating the wireless environment.} \label{tab:parameters} \begin{tabular}{|c|c|} \hline \textbf{Parameter} & \textbf{Value} \\ \hline number of PUs $M$ & 4 \\ \hline number of SUs $N$ & 6 \\ \hline simulation area & 2000m$\times$2000m \\ \hline distance between user pair & 400m-450m \\ \hline transmit power of PU & 500mW \\ \hline transmit power of SU & 500mW \\ \hline variance of Gaussian noise & -157.3dBm \\ \hline bandwidth of a channel & 5MHz \\ \hline interval of one time slot & 1ms \\ \hline sensing and transmission period $T$ & 10 time slots \\ \hline sensing duration $T_s$ & 2 time slots \\ \hline \end{tabular} \end{table} For the activity pattern of PUs, we let two PUs be in \textit{Active} state every $3T$ (PU1 and PU3) and two PUs be in \textit{Active} state every $4T$ (PU2 and PU4). Each SU trains its DEQN agent and updates the policy accordingly after collecting 300 samples in the buffer. The buffer will be refreshed after training so we only use training data from the latest 3 sec. The total number of training data is 60000, which requires 600 sec to collect all the training data. The initial exploration probability $\epsilon$ is set to 0.3, and then it will gradually decrease until $\epsilon$ is 0. We first train the Q-network with learning rate 0.01, and then the learning rate decreases to 0.001 when $\epsilon$ is less than 0.2. \begin{figure}[ht] \centering \includegraphics[width=1.0\linewidth]{network_architecture.png} \caption{The network architecture of DEQN.} \label{fig:network_architecture} \end{figure} \subsection{Network Architecture} As shown in Figure~\ref{fig:network_architecture}, our DEQN network consists of $L$ reservoirs for extracting the necessary temporal correlation to predict targets. The number of neurons in each reservoir is set to 32 and the leaky parameter $\beta$ is set to 0.7 in Equation (\ref{eqn:hidden_state}). During the training process, the input weights $\{ W_{in}^{(1)}, ..., W_{in}^{(L)} \}$ and the output weights $\{ W_{rec}^{(1)}, ..., W_{rec}^{(L)} \}$ are untrained. To find a good policy, only the output weight $W_{out}$ is trained to read essential temporal information from the input states and the hidden states stored in the experience replay buffer. Existing research shows that stacking RNNs automatically creates different time scales at different levels, and this stacked architecture has better ability to model long-term dependencies than single layer RNN~\cite{hermans2013DRNN,galli2017deepESN, zhou2020Reservoir}. We also find that stacking ESNs can indeed improve the performance in our experiment. \subsection{Results and Discussion} We evaluate our introduced DEQN method with three performance metrics: 1) The system throughput of PUs. 2) The system throughput of SUs. 3) The required training time. The throughput represents the number of transmitted bits per second, which is calculated by (spectral-efficiency) $\times$ (bandwidth), and the system throughput represents the sum of users' throughput in the primary system or secondary system. A good DSS strategy should increase the throughput of SUs as much as possible, while the transmissions of SUs do not harm the throughput of PUs. Therefore, each SU has to access an available channel by predicting activities of other mobile users. We compare with conventional DRQN method that uses Long Short Term Memory (LSTM)~\cite{hochreiter1997LSTM} as the Q-network. For a fair comparison, we also set the number of neurons in each LSTM layer to 32. The training algorithm of DRQNs is BPTT and double Q-learning with the same learning rate as DEQNs. Since each SU updates its policy for every 300 samples, we show all of our curves in figures by calculating the moving average of 300 consecutive samples for clarity. \begin{figure}[ht] \centering \includegraphics[width=1.0\linewidth]{PU_throughput.png} \caption{The system throughput of PUs.} \label{fig:PU_throughput} \end{figure} \begin{figure}[ht] \centering \includegraphics[width=1.0\linewidth]{SU_throughput.png} \caption{The system throughput of SUs.} \label{fig:SU_throughput} \end{figure} DEQN1 and DEQN2 are our DEQN method with one and two layers, respectively, and DRQN1 and DRQN2 are the conventional DRQN method with one and two layers, respectively. The system throughput of PUs is shown in Figure~\ref{fig:PU_throughput} and the system throughput of SUs is shown in Figure~\ref{fig:SU_throughput}. We observe that DEQNs have more stable performance than DRQNs, which empirically proves that the DEQN method can learn efficiently with limited training data. Note that one experience replay buffer only contains 300 latest training samples. After updating the learning agent of each SU using the 300 data in the buffer, DSS strategy of each SU changes so the environment observed by one SU also changes. Therefore, we have to erase the outdated samples from the buffer and let SUs collect new training data from the environment. Figure~\ref{fig:average_reward} shows the average reward of SUs versus time. We observe extremely unstable reward curves of both DRQN1 and DRQN2 so it proves that DRQNs cannot adapt to this dynamic 5G scenario well with few training data. \begin{figure}[ht] \centering \includegraphics[width=1.0\linewidth]{average_reward.png} \caption{The average reward versus time.} \label{fig:average_reward} \end{figure} We observe that DEQN2 has better performance than DEQN1 in both the system throughput of PUs and SUs, which shows that deep structure (stacking ESNs) indeed improves the capability of the DRL agent to learn long-term temporal correlation. As for DRQNs, we observe that DRQNs do not have improved performance as we increase the number of layers in the underlying RNN. The main reason is that more training data are needed for training a larger network but even DRQN with one layer cannot be trained well. \begin{figure}[ht] \centering \includegraphics[width=0.9\linewidth]{warning_PU.png} \caption{The average warning frequency of each PU versus time.} \label{fig:warning_PU} \end{figure} The top priority of designing a DSS network is to prevent harmful interference to the primary system. To analyze the performance degradation of the primary system after allowing the secondary system to access, we show the system throughput of PUs when there is no SU exist in Figure~\ref{fig:PU_throughput}. We observe that DEQN2 can achieve almost the same performance of the system throughput of PUs. A PU broadcasts a warning signal if its spectral-efficiency is below a threshold. For each PU, we record the frequency of (the PU sends a warning signal and it is received by some SUs) / (number of the PU's access), which is called as the warning frequency. Figure~\ref{fig:warning_PU} shows the average warning frequency of each PU versus time. We observe that the every PU decreases its warning frequency over time, meaning that each SU learns not to access the channel that will cause harmful interference to PUs. \begin{table}[ht] \centering \caption{The comparison of training time of different network architectures.} \label{tab:training_time} \begin{tabular}{|c|c|} \hline \textbf{Network} & \textbf{Training time (sec)} \\ \hline DEQN1 & 161 \\ \hline DEQN2 & 178 \\ \hline DRQN1 & 3776 \\ \hline DRQN2 & 7618 \\ \hline \end{tabular} \end{table} We compare the training time of different approaches in Table~\ref{tab:training_time} when implemented and executed on the same machine with 2.71 GHz Intel i5 CPU and 12 GB RAM. The required training time for DRQN1 is 23.4 times the training time for DEQN1, and the required training time for DRQN2 is 42.8 times the training time for DEQN2. This huge difference shows the training speed advantage of our introduced DEQN method against the conventional DRQN method. DRQN suffers from high training time because BPTT unfolds the network in time to compute the gradients, but DEQN can be trained very efficiently because the hidden states can be pre-stored for many training iterations. \section{Conclusion} In this paper, we introduced the concept of DEQN, a new RNN-based DRL strategy to efficiently capture the temporal correlation of the underlying time-dynamic environment requiring very limited amount of training data. The DEQN-based DRL strategies largely increase the rate of convergence compared to conventional DRQN-based strategies. DEQN-based spectrum access strategies are examined in DSS, a key technology in 5G and future 6G networks, showing significant performance improvements over state-of-the-art DRQN-based strategies. This provides strong evidence for adopting DEQN for real-time and time-dynamic applications. Our future work will be focused on developing methodologies for the design of neural network architectures tailored to different applications. \ifCLASSOPTIONcaptionsoff \newpage \fi
{'timestamp': '2020-10-13T02:28:31', 'yymm': '2010', 'arxiv_id': '2010.05449', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05449'}
arxiv
\section{Introduction} \label{sec:introduction} Physical-layer authentication relies on detecting and identifying unique characteristics embedded in over-the-air radio signals, thus enabling the identification of the hardware of the transmitting source~\cite{wang2016_commag,xiao2007_icc}. Wireless Physical-layer authentication is also known as radio fingerprinting when referring to the challenge of both detecting and extracting features from the received signal (fingerprint), which can uniquely identify the transmitting source~\cite{xu2016_comst, ibrahim2020_tecs}. Physical-layer authentication can significantly enhance the security and privacy of wireless channels in two adversarial scenarios: (i) spoofing; and, (ii) replay attacks. The former involves a rogue transmitting source attempting to impersonate a legitimate one, while the latter assumes the adversary being able to re-transmit previously eavesdropped messages~\cite{schmidt2016_csur}. Despite spoofing detection can be achieved by authenticating the transmitting source with standard cryptographic techniques (e.g., digital signatures), in many scenarios involving massive deployments (e.g., IoT), difficult to reach devices (e.g., satellites), or when the cryptography-induced overhead is considered excessive, digital signatures might be inefficient~\cite{soltanieh2020_jrfi}. Alternative solutions could involve crowd-sourcing, i.e., cross-checking context information to validate the transmitting source~\cite{oligeri_wisec_2019,oligeri_wisec_2020}. Replay attacks can be even more difficult to detect, being dependent on specific protocol flaws: the adversary re-transmits encrypted information, which will be considered as valid if not timestamped. Both spoofing and replay attacks can be prevented if the receiver can authenticate the hardware of the transmitting source~\cite{zhou2019_cns}. Many researchers have already undertaken the challenge of extracting fingerprints and developing effective detection algorithms to extract and match the fingerprints (see Sec.~\ref{sec:related_work} for an overview). The cited tasks have been mainly achieved by resorting to dedicated hardware at the receiver side, featuring high sampling resolution and better signal quality. Indeed, \acp{SDR} played a major role as an enabling technology for radio fingerprinting. Specifically, \acp{SDR} provide both high-resolution bandwidth (thus exposing the features of the transmitting source) and high signal-to-noise ratio (thus facilitating the extraction of the features to the back-end algorithms). Unfortunately, radio noise still represents the major issue for all the state-of-the-art solutions. Indeed, the fingerprint of the transmitting source is mixed---drown, in many cases---with the noise of the radio channel. Therefore, discriminating between the needed features and the noise brings back the problem of developing effective algorithms to achieve the cited objective. Recently, \acp{CNN} have been adopted for radio fingerprinting in several scenarios, such as ADS-B, WiFi, and Zigbee, to name a few~\cite{yu2019_wimob,sankhe2020_tccn,ying2019_cns,shawabka2020_infocom}. The idea behind the adoption of \acp{CNN} relies on exploiting their multidimensional mapping during the learning process to detect and extract reliable radio fingerprints. However, all of the recent contributions took into account terrestrial links, only. Although achieving interesting performance, there are still some open fundamental questions related to \acp{CNN}, such as the intrinsic time-stationarity nature of the \acp{CNN} and how the wireless channel (in terms of attenuation and fading) affects the learning and detection processes~\cite{shawabka2020_infocom}. Recent results~\cite{shawabka2020_infocom} based on real measurements on terrestrial wireless links confirmed that the wireless channel significantly impacts the classification accuracy (up to $80\%$), thus confirming the need for more effective classification techniques. It is worth noting that no prior contribution has been made up to date to physical layer authentication of satellite transmitters (in particular the IRIDIUM constellation), given their intrinsic challenges. Indeed, LEO satellites, which IRIDIUM constellation is part of, are characterized by unique features: the satellite transmitter is at around 800Km from earth, and moves at about 7Km/s with a pass duration of about 8 minutes~\cite{oligeri_wisec_2020}---involving a radio link (quality) that significantly changes over the time. Indeed, we observe that attenuation and multi-path fading can significantly change when the satellite is either on top of the receiver or far away, just over the horizon (before disappearing). Therefore, the noise affecting the satellite link makes radio fingerprinting in satellite a unique, more challenging scenario, requiring additional research. {\bf Contribution.} This paper provides the following contributions: \begin{itemize} \item We push further the current state-of-the-art in physical-layer authentication, by proposing PAST-AI, i.e., a set of new methodologies specifically designed to perform radio fingerprinting over LEO satellite links. \item We propose a new technique to represent IQ samples in input to AI classification algorithms. \item We prove that \acf{CNN} and autoencoders can be effectively adopted to fingerprint radio satellite transmitters. \item We propose two different classification scenarios, i.e., \emph{intra-constellation satellite authentication} and \emph{satellite authentication in the wild}, which fit the adopted classification algorithm and their assumptions. \item We provide several insights to properly calibrate the algorithm parameters, achieving overwhelming performance, i.e., an accuracy greater than 0.8 for the former scenario and average \ac{AUC} equal to 1 for the latter (vast majority of the satellites). \end{itemize} {\bf Paper organization.} The rest of this paper is organized as follows. Section~\ref{sec:related_work} reviews related work on physical-layer fingerprinting; Section~\ref{sec:background} introduces background details on IQ modulation, AI techniques, and the IRIDIUM satellite constellation; Section~\ref{sec:iq_processing} illustrates the data acquisition campaign and the initial data processing; Section~\ref{sec:satellite_authentication} introduces the PAST-AI\ methodology; Section~\ref{sec:intra-satellites} focuses on the intra-constellation satellite authentication scenario; Section~\ref{sec:satellite_authentication_inthe_wild} details the authentication scenario with minimal satellites' knowledge; and, finally, Section~\ref{sec:conclusion} tightens the conclusions. \section{Related Work} \label{sec:related_work} Physical-layer authentication solutions based on the analysis of raw IQ samples have gained significant popularity in the last years, and have been adopted in a variety of scenarios and communication technologies. For instance, in the context of mobile cellular networks, the authors in~\cite{zhuang2018_asiaccs} proposed \emph{FBSLeuth}, a framework able to identify rogue 2G mobile cellular base stations by analyzing the hardware impairments of the transmitting devices, such as the error vector magnitude of the signals, the phase error, the frequency error, the IQ offset, the IQ quadrature skew, and the IQ imbalance. To identify the rogue base stations, they used supervised \ac{ML} techniques, specifically the \ac{SVM} classification algorithm. In the same context, the authors in~\cite{wang2020_infocom} relied on \ac{DCTF}-based features and \acp{CNN} to identify mobile phones. Specifically, the authors used image discrimination techniques to discriminate among six ($6$) different mobile phones, with outstanding accuracy and a reduced observation window. In the context of WiFi, the authors in~\cite{sankhe2019_infocom} first were able to distinguish among \ac{COTS} WiFi devices and \acp{SDR} emitting similar WiFi-compliant signals. Specifically, using a \ac{CNN}-based architecture operating on raw IQ samples, they could identify precisely among sixteen ($16$) \acp{SDR}s. The authors further extended their work in~\cite{sankhe2020_tccn}, showing how the classification accuracy can reach over $99$\% by smartly removing the noise effects of the wireless channel. The impact of the wireless channel on wireless radio fingerprinting has been specifically studied by the authors in~\cite{shawabka2020_infocom}. They evaluated the accuracy of \ac{CNN}-based methods in several operating conditions, i.e., in an anechoic chamber, in the wild, and using cable connections, investigating both WiFi and \ac{ADS-B} signals (employed in the aviation domain). They revealed that the wireless channel can severely affect the accuracy of the radio fingerprinting, degrading the classification accuracy up to the $85$\% in low-\ac{SNR} regime. At the same time, they showed that equalizing IQ data can slightly enhance the quality of the fingerprinting, when possible. Similar results and findings were achieved also by the authors in~\cite{jian2020_iotmag}. By working on the same dataset, the authors confirmed that partial equalization of the samples can improve the accuracy of the \ac{CNN}-based architecture in identifying the transmitter, while the accuracy generally decreases with the decrease of the \ac{SNR}. \ac{ADS-B} signals have been investigated also by the authors in~\cite{ying2019_cns}, by using an autonomously-made dataset. Specifically, the authors compared the performance of three different \acp{DNN}s, characterized by a different number of hidden layers and nodes (i.e., neurons), and they showed that the performance of the classifiers slightly decreases when the number of considered aircraft increases, as well as by reducing the training set ratio. The IQ fingerprinting technique is particularly promising for the \ac{IoT} domain, as it could avoid the installation of dedicated cryptography techniques on memory-limited and computationally-constrained devices. These considerations motivated several studies, applying IQ fingerprinting techniques on \ac{IoT} devices. For instance, the authors in~\cite{jafari2018_milcom} relied on multiple deep learning models, i.e., \ac{CNN}, \ac{DNN}, and \ac{RNN}, to discriminate among six ($6$) identical Zigbee devices, showing that the \ac{DNN} model slightly outperforms the others, especially with short windows sizes. The same number of devices has been adopted also by the authors in~\cite{bassey2019_fmec}, which used \acp{CNN}, dimensionality reduction, and de-correlation to further improve the performance of the classification task for \ac{IoT} devices. Recently, the authors in~\cite{yu2019_wimob} demonstrated that stacked autoencoders can be used to enhance the performance of \ac{CNN}-based methods for IQ fingerprinting, especially in low-\ac{SNR} scenarios. To verify their findings, they used twenty-seven ($27$) CC2530 micro-controllers, and they were able to distinguish each of them with accuracy over $90$~\% starting from $5$~dB \ac{SNR}. Another recent contribution is provided in~\cite{balakrishnan2020_tifs}, where the authors identified mm-WAVE transmitters operating at the frequency of $60$~GHz by analyzing the spatio-temporal information of the beam patterns created by the antennas in the array. Despite the significant number of contributions in the field of IQ fingerprinting, the satellite scenario has not yet been considered, thus still representing a challenging research problem. Indeed, being the satellite located at a significant altitude from the ground, the signals are typically characterized by a low \ac{SNR} and a significant noise level, thus making the fingerprinting task more challenging. At the time of this writing, the only contribution working on the fingerprinting of satellites is~\cite{foruhandeh2020_wisec}. The authors argue to be able to identify \ac{GPS} spoofing attacks by analyzing the received IQ samples, by using a statistical approach based on scores computed over characterizing Multi-Variate Normal (MVN) distributions. However, they extracted the IQ samples after the IQ demodulation at the \ac{RF} front-end, and specifically after the E-P-L correlators in the receiving chain. Therefore, their solution does not act on raw IQ samples, and applies only to US \ac{GPS} satellites. Finally, note that the authors focused on the detection of GPS spoofing attacks, and they distinguish \acp{SDR} from legitimate satellites, not the specific transmitting satellite. Conversely, in this paper we identify the specific satellite transmitting an IRIDIUM signal, considering \emph{raw} IQ samples, before any demodulation operation. As a result, our methodology applies to a wider set of scenarios than spoofing attacks, and it is potentially applicable to all \ac{LEO} satellites constellations adopting \ac{PSK} modulation techniques. \section{Background} \label{sec:background} In this section we revise the technical background providing the needed information that will be leveraged in next sections. \subsection{IQ (de)modulation} \label{sec:background_iq} Digital modulation schemes involve the processing of a (low frequency) baseband signal, i.e., a bit sequence $b_i \in \{0, 1\}$ with $i \in [1, N]$, to make it suitable for the transmission virtually anywhere in the RF spectrum (high frequency). Several techniques have been developed to achieve the aforementioned result, but \emph{IQ modulation} is the most adopted due to practicality: efficient IQ (de)modulators are available as inexpensive System on Chip (SoC) technology. Figure~\ref{fig:txrxiq} shows the block diagram of a typical communication system involving IQ modulation, RF transmission, and IQ demodulation. According to the scheme, a sequence of bits should be preliminary converted into \emph{IQ symbols}, i.e., $i(t)$ and $q(t)$ in Fig.~\ref{fig:txrxiq}. Different families of modulation schemes are possible, e.g., Amplitude Shift Keying (ASK), Frequency Shift Keying (FSK), or Phase Shift Keying (PSK), depending on how the sequence of bits is converted to the {\em in-phase} $i(t)$ and {\em quadrature} $q(t)$ components (recall Fig.~\ref{fig:txrxiq}). \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/txrxiq.pdf} \caption{Modulation and Demodulation of a digital signal represented by its phase $i(t)$ and quadrature $q(t)$ components.} \label{fig:txrxiq} \end{figure} As a toy example, we consider the Quadrature Phase Shift Keying (QPSK or 4-PSK)---the one adopted by Iridium is very similar and we will discuss it in the next sections. QPSK maps pair of bits into (four) IQ symbols, i.e, $\{1, 1\} \rightarrow s_0$, $\{0, 1\}\rightarrow s_1$, $\{0, 0\}\rightarrow s_2$, and $\{1, 0\}\rightarrow s_3$, as depicted by Fig.~\ref{fig:bits_to_symbols}. It is worth noting that the aforementioned mapping can be easily achieved by setting $i(t) = \{-1, 1\}$ and $q(t) = \{-1, 1\}$, as depicted in Fig.~\ref{fig:bits_to_symbols}. For instance, the bit string $b:[0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1]$ becomes the sequence of symbols $[s_1, s_1, s_2, s_1, s_3, s_1, s_1, s_0]$, thus obtaining the in-phase $i(t)$ and quadrature $q(t)$ signal components. For the sake of completeness, we highlight that both $i(t)$ and $q(t)$ should be subject to other filtering stages and they cannot be directly used as mentioned in Fig.~\ref{fig:txrxiq}, since the sharp level changes will eventually cause $s(t)$ to have a very large bandwidth \cite{rappaport}. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/bits_to_symbols.pdf} \caption{Quadrature Phase Shift Keying (QPSK) mudulation example: from bit sequence $b$ to the in-phase $i(t)$ and quadrature $q(t)$ components.} \label{fig:bits_to_symbols} \end{figure} Let us now complete the discussion about the IQ (de)modulation previously introduced by Fig.~\ref{fig:txrxiq}. $i(t)$ and $q(t)$ components are \emph{modulated} adopting an in-phase ($\cos{2\pi f_c t}$) and a quadrature ($\sin{2\pi f_c t}$) signal at the reference frequency $f_c$ (\emph{carrier}). The resulting signals are summed up to obtain $s(t)$, the actual RF signal. Figure~\ref{fig:txrxiq} takes into account any propagation phenomena, such as fading and attenuation, that may affect the received signal, and therefore $r(t) \neq s(t)$. The demodulation block is the reciprocal of the modulator. Indeed, the received signal $r(t)$ is multiplied by both an in-phase and a quadrature signal at frequency $f_c$, and then, low pass filtered in order to remove the unwanted upper sidebands. The final result consists of $i'(t)$ and $q'(t)$ that can be arbitrarily different from the original $i(t)$ and $q(t)$ signal components. The greatest source of difference usually comes from RF propagation, which can affect $i(t)$ and $q(t)$ so badly to make the symbol recovery impossible. When the \emph{signal-to-noise ratio} is large enough, the symbols are evenly distributed and the information recovery becomes feasible. Further, there are also minor effects that introduce small offset in the IQ symbols. A typical example is constituted by impairments and biases introduced by small differences in the electronics components, that, although being mass produced by controlled and standardized assembly lines, are still characterized by imperfections at nano-scale, that affect the displacement of the symbols. The analysis introduced in latter sections proves that the symbols' displacement is systematic, thus being at least theoretically possible to detect it, measure it, and eventually leverage it to identify the hardware causing it. We moved from theory to practice, showing a viable method leveraging AI to achieve the cited objective. \subsection{Deep Learning classifiers and Transfer Learning} \label{sec:background_ai} In this subsection, the Deep Learning classifiers adopted in this study are introduced, together with the transfer learning technique, that allowed us to notably improve the accuracy during the multi-class classification task. \subsubsection{Autoencoders} \label{sec:autoencoders} An autoencoder is defined as an artificial neural network whose goal is to learn an optimal representation (i.e., encoding) of a training set from which it is possible to accurately reconstruct the input data. Although it may seem trivial (i.e., the mere copy of the input data to the output may easily lead to an outstanding accuracy), to identify useful features, the internal function responsible for the research of good encoding candidates is usually constrained. For instance, the autoencoder may be forced to find an encoding smaller than the input data (i.e., undercomplete autoencoder). Traditionally, this unsupervised technique has been widely adopted to perform dimensionality reduction and feature learning, since it may be tuned to generate smaller encodings as similar as possible to the original input, while recently autoencoders are also being put to the forefront of generative modeling~\cite{goodfellow_deep_learning}. The more similar the output reconstructed starting from such encoding is to the training set, the more likely the autoencoder is said to be able to represent input data. In case the encoding is (parametrically) smaller than the input data, the feature reduction phase is successful. The basic autoencoder model has been quickly followed by many variants, each one forcing the learned encoding to boast a different property. Valuable examples are the regularized autoencoders, able to learn the most salient features of the data distribution~\cite{goodfellow_deep_learning}, and variational autoencoders, able to provide a framework to learn deep latent-variable models as well as the corresponding inference models~\cite{kingma2019introduction}. An autoencoder usually consists of four main components: (i) an encoder, that allows the model to learn how to represent the features of the input data; (ii) a bottleneck, identified as the layer containing the encoding of the training set; (iii) a decoder, that allows the model to learn how to reconstruct the input data from the encoding; and, (iv) the reconstruction error function, useful to measure the performance of the model during the whole training. The performance offered by the autoencoders positively impacted their wide applications, which now range from intrusion detection tasks~\cite{ieracitano2020neurocomputing}, to anomaly detection~\cite{nazir2020autoencoder}, and DDoS attack detection~\cite{yang2020ieeeifip}. In this paper, we rely on autoencoders to perform the one-class classification task on the IRIDIUM satellites. The intuition behind the adoption of autoencoders to face such a challenge is the following: starting from a distribution (i.e., class) $X$, the reconstruction of input data drawn from the same distribution $X$ is easier (i.e., the error metric is reduced) than the reconstruction of input data drawn from any other distribution $Y$, with $Y \ne X$. \subsubsection{Convolutional Neural Networks} \label{sec:cnn} A \ac{CNN} is defined as a \ac{DNN} that boasts at least one convolutional layer, i.e., a layer performing convolutional operations. A convolutional operation, in turn, is the mathematical combination of two functions that produces a third function, being the expression of the change of shape caused by the application of one function to the other. In the case of \ac{CNN}, a convolution consists of a slide of a parametric-sized filter (also known as operator) over the input representation. Being the filter smaller compared to the input representation, it is applied to different overlapping portions of the input, thus generating a feature map. Different filters allow to catch different patterns within the input representation (i.e., in case the input is represented as an image, operators can be used to highlight edges, corners, and possibly other patterns). A typical \ac{CNN} is composed of three types of layers: (i) convolutional layers, to build the feature map of the input representation; (ii) pooling layers, to reduce the number of learnable parameters and discretize the input; and, (iii) fully connected layers, usually representing the last layers of the architecture, to hold the high-level features found during the convolutions and to learn non-linear combinations of them. When compared to multi-layer perceptrons, \acp{CNN} present characteristics that discourage the learning of too complex and expensive models, thus being recognized as their regularized version (i.e., a version that allows containing overfitting by construction). Indeed, while in multi-layer perceptrons several fully connected layers (i.e., layers whose neurons are fully connected to the ones of the next layer) are employed to perform classification, \ac{CNN}s exploit a hierarchical structure able to learn complex patterns by relying on the combination of small and simple ones~\cite{raponi2020sound}. The reduced number of connections and parameters made \ac{CNN}s extremely appreciable in several domains due to their ability to be trained quickly and more accurately than previous feed-forward models. Specifically, applications can be found in handwriting recognition, face detection, behavior recognition, recommendation systems, speech recognition, image classification, and Natural Language Processing~\cite{liu2017survey}. \subsubsection{Transfer Learning} \label{sec:transfer_learning} Until a few years ago, conventional machine learning algorithms have been designed to work in isolation, trained from scratch every single time to solve specific tasks. However, training a network from scratch may be cumbersome, since the available datasets may not be rich enough to effectively capture the features. As a result, the resulting classifier could not generalize properly when applied in the wild. With the introduction of transfer learning, however, the learning phase of the algorithms has been completely revolutionized. The general idea of transfer learning is to take advantage of the knowledge learned while solving a task of a particular domain to simplify the learning phase for a related domain task. In this paper, in order to perform multi-class classification on the IRIDIUM satellites, we exploited the knowledge of the Resnet-18 \ac{CNN}, pre-trained on the popular ImageNet dataset. Resnet, introduced by Microsoft researchers in 2015, proved to be the most performant \ac{CNN}, since it is structured in such a way to allow achieving deeper architectures with a reduced number of parameters~\cite{he2016_cvpr}. Details on the ResNet-18 \ac{CNN} and the transfer learning methodology adopted in this study (e.g., fine-tuning or freezing-layers) are detailed in Section~\ref{sec:convolutional_neural_networks}. \subsection{Iridium Satellite Constellation} \label{sec:iridium_constellation_and_data_acquisition} The IRIDIUM satellite constellation was conceived in 1987, and first operated in 1993 by IRIDIUM SSC, founded by Motorola~\cite{pratt1999_comst}. The constellation is constituted by a set of \ac{LEO} satellites, orbiting $800$~km above the Earth surface, and arranged so that they can guarantee full Earth coverage at any time. The name of the satellite constellation is inspired by the originally-planned number of satellites, i.e., $77$, coincident with the atomic number of the IRIDIUM chemical element. However, to minimize deployment costs while still guaranteeing Earth coverage, only $66$ satellites are operational nowadays. IRIDIUM radio signals are transmitted in the L-band, in the frequency range $[1,616 - 1,626.5]$~MHz. At the ground, IRIDIUM subscribers can receive such signals as well as transmitting by using dedicated mobile satellite devices, provided by companies such as Motorola and Kyocera. Today, IRIDIUM is mainly used on-board of vessels, to initiate and receive calls when located off-shore. In this context, starting from January 2020, the \ac{IMO} has certified IRIDIUM as an approved \ac{GMDSS} service provider for vessels. However, IRIDIUM transceivers are also used in the aviation, railway, and critical infrastructures domain, and recently they have received significant attention also in the emerging satellite-\ac{IoT} application domain~\cite{iridium_iot}. Each IRIDIUM satellite includes an array of antennas, hereby referred to as \emph{beams}, that widens the transmission range of the satellite at the ground. Overall, each satellite has $48$~beams and an additional antenna dedicated to the identification of the satellite. Note that the transmission power adopted by the \emph{satellite} antenna is higher than the one used by the \emph{beams}, so that any receiver that could decode the signal emitted by a beam can also receive the information about the satellite itself. Overall, two channels categories are available, i.e., \emph{system overhead channels} and \emph{bearer service channels}. In this paper, we focus our attention on one of the \emph{system overhead channels}, i.e., the \ac{IRA} broadcast channel. It is a broadcast, unencrypted, downlink-only channel, operating at the center frequency $1,626.27$~MHz, and used to deliver information useful for handover operations at the ground. \ac{IRA} messages are characterized by a $12$~bytes preamble, encoded according to the \ac{BPSK} modulation scheme, while the rest of the information ($103$~bytes) follows the \ac{DQPSK} modulation. Such information include the ID of the satellite emitting the packet, the specific transmitting beam (the beam ID is $0$ in the case the transmitter is the one identifying the satellite), the position of the satellite (expressed in latitude, longitude, and altitude), and further information used for handover, e.g., the \ac{TMSI} of any user subject to handover. Note that \ac{IRA} packets can have different sizes, depending on the amount of \acp{TMSI} included in the message, as well as the presence of additional specific paging information. Previous contributions such as~\cite{oligeri_wisec_2020} used the information included into the IRA messages to reverse-engineer several system parameters of the IRIDIUM constellation, such as the speed of the satellites, the coverage at the ground, the arrangement of the beams, and the satellite pass duration. In this paper, we further extend those results, by providing additional hints on the time needed to \emph{observe} a specific satellite, the distribution of IQ samples, the effect of the noise, and the expected number of IQ samples per satellite pass (see Section~\ref{sec:iq_processing}. All these information are instrumental to the scope of our work, i.e., the authentication of the IRIDIUM satellite at the physical-layer, by using raw IQ samples. \section{IRIDIUM Data Acquisition and Processing} \label{sec:iq_processing} In this section, we first describe the equipment (hardware and software) that has been adopted for our measurement campaign, later we depict how we reverse-engineered the architectural parameters of the IRIDIUM satellite constellation and, finally, we introduce how we exploited the IQ samples to authenticate the satellite transmitters. \subsection{Measurement Set-up} \label{sec:measurement_setup} The measurement setup is illustrated in Figure~\ref{fig:scenario}. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/measurement_setup.pdf} \caption{Measurement Setup: we adopted an active (pre-amplified) Iridium antenna (Beam RST740) connected to a USPR X310 Software Defined Radio.} \label{fig:scenario} \end{figure} The hardware used to acquire IRIDIUM signals consists of a dedicated L-Band IRIDIUM antenna, connected to a general-purpose Ettus Research X310 \ac{SDR}. The antenna is an IRIDIUM Beam Active Antenna, model RST740, commonly used by commercial IRIDIUM transceiver~\cite{iridium_antenna}. The antenna is connected through an SMA cable to the Ettus X310 SDR~\cite{ettus}, integrating the UBX160 daughterboard~\cite{ubx}. In turn, the SDR is connected via Ethernet to a Laptop Dell XPS15 9560, equipped with 32GB of RAM and 8 Intel Core i7700HQ processors running at 2.80 GHz. On the software side, we used the well-known GNURadio development toolkit. Specifically, we adopted the \emph{gr-iridium} module to detect and acquire IRIDIUM messages~\cite{iridiumgr}. In addition, we used the \emph{iridium-toolkit} tool to parse \ac{IRA} messages~\cite{iridium-toolkit}. In detail, we modified the \emph{gr-iridium} module in a way to log the IQ samples of all the \emph{valid} IRIDIUM packets, i.e., the ones containing the 12~bytes BPSK-modulated preamble, typical of the IRIDIUM messages. For each of these packets, we logged the values of the IQ samples after the filtering and synchronization performed by the \ac{PLL}. Next, we used the \emph{iridium-toolkit} tool to log only valid \ac{IRA} packets. Our measurement campaign has been carried out in very harsh conditions, i.e., by exposing the IRIDIUM antenna out of the window of an apartment. This is a worst-case scenario, since part of the open sky is obstructed by the wall of the building, attenuating and deviating the signal coming from the satellites. However, we highlight that this is not a limitation of our study. Conversely, the high-level performance achieved in such a disadvantaged scenario paves the way for further improvement. Overall, we continuously acquired IRIDIUM signals for about $589$~hours (24 days), gathering a total number of $102,318,546$ IQ samples ($1,550,281$ per satellite, on average). An excerpt from the dataset is reported in Table~\ref{table:excerpt}. Specifically, for each received IRA packet we log the reception timestamp on the SDR, both in seconds and in milliseconds, the satellite ID, the beam ID, the latitude, longitude, and altitude coordinates of the emitting satellite, and the raw IQ samples included in the IRA packet. As recently discussed by the authors in~\cite{oligeri_wisec_2020}, any IRIDIUM satellite is equipped with a total number of $49$~radios, where $48$ represent the radio of the beams and the remaining one reports the whole satellite ID, characterized by the beam numbered $0$. For our work, we further restricted the analysis to \emph{satellite} IRA packets, i.e., the one having beam ID $0$. \begin{table*}[htbp] \footnotesize \centering \caption{Excerpt of the collected dataset. Latitude and Longitude information anonymized for peer-review.} \begin{tabular}{ccccccc} \textbf{Time (s)} & \textbf{Time (ms)} & \textbf{\begin{tabular}[c]{@{}c@{}}Satellite \\ ID\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}Beam \\ ID\end{tabular}} & \textbf{Latitude} & \textbf{Longitude}& \textbf{\begin{tabular}[c]{@{}c@{}}IQ \\ Samples\end{tabular}} \\ \hline 1580712040 & 000000739 & 115 & 0 & ? & ? & 0.03+0.3j, ... \\ 1580712040 & 000004519 & 115 & 0 & ? & ? & 0.02-0.4j, ... \\ 1580712040 & 000005059 & 115 & 0 & ? & ? & -0.07+0.8j, ... \\ 1580712040 & 000005599 & 115 & 0 & ? & ? & -0.2-0.4j, ... \\ 1580712040 & 000008839 & 66 & 0 & ? & ? & 0.03+0.3j, ... \\ 1580712040 & 000013159 & 66 & 0 & ? & ? & 0.03+0.3j, ... \\ 1580712040 & 000013699 & 66 & 0 & ? & ? & 0.03+0.3j, ... \end{tabular} \label{table:excerpt} \end{table*} Finally, we implemented the proposed classification algorithms (\acf{CNN} and autoencoders) in MATLAB R2020a. The training, validation, and testing have been carried out by a server featuring 64 cores, 512GB RAM, and 4 GPUs Nvidia Tesla M40. The collected data will be released open source once the paper will be accepted. \subsection{Reverse-Engineering IRIDIUM Constellation Parameters} \label{sec:iridium_parameters} In this section, we derive important parameters of the IRIDIUM satellite constellation, functional to the subsequent analysis. We consider the \ac{SNR} associated with the collected IQ samples, the waiting time between two consecutive passes of a specific satellite and, finally, the number of IQ samples that can be collected during a single satellite pass. {\bf Signal-to-Noise Ratio (SNR).} We start the analysis by considering the quality of the collected samples, in terms of \ac{SNR}. Firstly, we compute the received power $P_{rx}$ associated with the IQ samples as in Eq.~\ref{eq:p_rx}: \begin{equation} \label{eq:p_rx} P_{rx}[dBm] = 10 \cdot \log_{10}(10 \cdot (I^2 + Q^2)), \end{equation} where $I$ and $Q$ are the in-phase and quadrature component of the signal, respectively. Conversely, we evaluated the noise power as in Eq.~\ref{eq:n_dbm}. \begin{equation} \label{eq:n_dbm} N[dBm] = 10 \cdot \log_{10}(10 \cdot \textrm{var}(I^2 + Q^2)), \end{equation} where $\textrm{var}(\circ)$ is the statistic variance. Finally, the SNR has been computed as in Eq.~\ref{eq:snr}. \begin{equation} \label{eq:snr} \textrm{SNR}[dB] = P_{rx} - N. \end{equation} Black dots in Fig.~\ref{fig:rss} represent the probability density associated with the SNR for all the collected IQ samples, independently of the satellite transmitting source, while the solid red line depicts the best-fit interpolation. We also computed the associated cumulative density function (CDF), as depicted in the inset of Fig.~\ref{fig:rss}. We highlight that the peak is represented by an SNR of about 45dBm, while $90\%$ of the collected samples experience an SNR in the range 40---60 dBm. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/rss.pdf} \caption{SNR of all the collected measurements. Black dots represent the real SNR values, while the solid red line depicts the best-fit interpolation.} \label{fig:rss} \end{figure} {\bf Waiting time between consecutive satellite passes.} We also investigate the time an observer (on the ground) has to wait to see again the same satellite. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/waiting_time.pdf} \caption{Waiting time among consecutive satellite passes.} \label{fig:waiting_time} \end{figure} We can explain these results by recalling that a satellite can pass over a specific location in two directions, either north-south or south-north. Indeed, each satellite passes over the same location twice every $90$~minutes: up to two consecutive passes can be detected from the same position. Subsequently, after a full Earth revolution, the satellite returns on the same location after about $560$~minutes with opposite direction. Higher waiting times (in Fig.~\ref{fig:waiting_time}), e.g., $560+90 \approx 650$~minutes, are due to passes that have not been detected by the receiver. {\bf IQ samples per satellite pass.} Another important parameter for the subsequent analysis is the number of collected IQ samples per satellite pass, i.e., the number of IQ samples that can be collected by a receiver during a single satellite pass. Firstly, we consider the inverse cumulative distribution function associated with the number of received IQ samples ($N$) per satellite pass, as depicted in Fig.~\ref{fig:iq_sample_per_pass}, i.e., $P(N > x)$, where $x$ represents a predefined value of IQ samples. The overall trend is linear up to $50,000$~samples: it is worth noting a probability of $0.7$ and $0.5$ to have at least $10,000$ and $20,000$ samples per satellite pass. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/iq_sample_per_pass.pdf} \caption{Probability to experience at least $x$ IQ samples in a single satellite pass.} \label{fig:iq_sample_per_pass} \end{figure} The inset of Fig.~\ref{fig:iq_sample_per_pass} shows the time required to collect the IQ samples. For instance, $10,000$ and $20,000$ IQ samples can be collected by satellite passes lasting for $7$ and $8$ minutes, respectively. The satellite passes last for a maximum time of $9$ minutes (median value of the maxima); during this period, we were able to collect between $30,000$ and $80,000$ IQ samples. We explain this wide range of values due to the varying noise conditions during the measurement campaign. Finally, it is worth noting the trend between $0$ and $30,000$ IQ samples, characterized by satellite pass length between $3$ and $8$ minutes. We consider these events to be associated to passes close to the horizon, where the satellite appears just for a short amount of time. \subsection{Transmitting-source Authentication via IQ samples} \label{sec:real_iq_samples} Figure~\ref{fig:iq_example} shows the received In-Phase $i'(t)$ and Quadrature $q'(t)$ components of $679,740$ samples gathered from the Satellite with ID $7$. It is worth noting that the ideal IQ constellation (recall Fig.~\ref{fig:bits_to_symbols}) is significantly different from the one experienced in real down-link satellite communications. Red circles in Fig.~\ref{fig:iq_example} highlight the ideal positions of the IQ samples and identify the four Cartesian quadrants adopted for the decision (recall Fig.~\ref{fig:bits_to_symbols}), i.e., received IQ sample (black dot) is mapped to the corresponding red circle as a function of the Cartesian quadrant on which it lies. The received IQ samples are affected by different phenomena that displace their original positions. As for the bit error rate, as long as the samples remain in their intended quadrants, the error rate remains zero. In this contribution, we are not interested in the link error rate; instead, we focus on the phenomena behind the IQ samples' displacement. In general, a received (satellite) signal is affected by the following phenomena: \begin{itemize} \item {\em Fading.} Iridium satellites are \ac{LEO} satellites, hence located at an height of approximately $780$~Km , thus being affected by a significant signal attenuation. Note that Fig.~\ref{fig:iq_example} is the result of a post-processing amplification, where the samples are stretched to fit the Cartesian plane $[-1, 1] \times [-1, 1]$. \item {\em Multipath.} Multipath is caused by multiple replicas of the transmitted signal reaching out the receiver through different paths, thus summing up at the receiver, albeit with different phases. Since the phase shift is random, the attenuation can be arbitrarily large, causing a destructive interference that can significantly affect the signal decoding. \item {\em Doppler shift.} Doppler shift represents the change of frequency (shift) of the received signal as a function of the relative speed between the transmitter and the receiver at the ground. The satellite scenario is particularly challenging, since the Doppler shift is maximum when the satellite is at the receiver's horizon, while becoming minimum at the receiver's zenith. \item {\em Hardware impairments.} Although mass produced, any two radio transceivers and their electronic components are not identical. Indeed, such discrete components can be affected by small physical differences at micro and nano scale (e.g. material impurity) that are reflected in variations of capacitance, resistance, and inductance, eventually leading to small (almost undetectable) signal artifacts and IQ unbalances. While the cited imperfections do not affect communication performance, they make the transmitted signal unique, thus (theoretically) enabling the identification of the transmitting source. Unfortunately, this is not an easy task, since such small IQ unbalances are hidden by all the previously-discussed phenomena---each of them having a sensitive impact in the IQ unbalancing. In the following, we will discuss an AI-based methodology to detect and extract such imperfections, and we will prove our approach being robust to noise, and able to identify a specific satellite transmitter among the $66$ that make up the Iridium constellation---thus enabling the physical authentication of the transmitting source. \end{itemize} \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/iq_example.pdf} \caption{Received In-Phase $i'(t)$ and Quadrature $q'(t)$ components of 679,740 samples from Satellite with ID 7.} \label{fig:iq_example} \end{figure} \subsection{IQ Samples Pre-processing} \label{sec:iq_samples_preprocessing} Noise represents a major challenge when the receiver aims at identifying the transmitting source via the IQ unbalances produced by hardware impairments of the the transmitting device. Over the years, several techniques have been developed to address the above issue, and the vast majority of them achieve great performance. Nevertheless, none of the mentioned techniques considered noisy radio links, e.g., like the satellite wireless channel. Indeed, recalling Fig.~\ref{fig:iq_example}, it can be observed that IQ samples do not appear just around the ideal points (red circles), but they spread all over the IQ plane. The ``cross''-like shape can be explained by the lack of signal amplitude normalization in the demodulation chain~\cite{saviogithub}. We will prove how the aforementioned issue does not affect our solution, being effective also for small values of the \ac{SNR} (like the ones of a satellite link). \begin{figure*} \centering \subfloat[Histogram of the IQ samples.]{\includegraphics[width=6.6cm]{figures/iqtoimage.pdf}} \qquad \subfloat[Contour plot (magnified) associated with the histogram of the IQ samples.]{\includegraphics[width=6.6cm]{figures/iqtoimage_countour.pdf}} \caption{Image representation of IQ samples.} \label{fig:iqtoimage} \end{figure*} Our solution involves the adoption of \ac{AI} techniques specifically designed for pattern detection and recognition from images. Our approach relies on applying state-of-the-art image pattern recognition techniques to synthetically generated \emph{images of IQ samples}. As previously discussed, hardware impairments generate (consistent, though low intensity) anomalies in the distribution of the IQ samples. Therefore, our intuition is to discriminate between the noise and the anomalies by relying on the more powerful classifiers in the literature. The aforementioned methodology requires an effective representation of the IQ samples in the image domain. Figure~\ref{fig:iqtoimage} shows how we pre-processed the IQ samples to graphically represent them as images. In particular, we sliced the IQ plane into $224 \times 224$ tiles (details on this will be clarified later on), and then we evaluated the deployment of different amounts of IQ samples ($679,740$ from the satellite with ID=7 in Fig.~\ref{fig:iqtoimage}). Subsequently, we computed the bivariate histogram over the aforementioned tiles, i.e., the number of IQ samples belonging to the same tile. Finally, we mapped each value into a grey-scale, i.e., $[0, 255]$, constituting one pixel of our grey image. Therefore, pixels with higher values (white color) represent the tiles with a high number of IQ samples, while pixels with small values (black color) represent tiles with no IQ samples. A few remarks about Fig.~\ref{fig:iqtoimage}. The figure represents the bipartite histogram associated with the IQ constellation when overlapping multiple IRA messages, each one being constituted by $12$ BPSK symbols (the unique word at the beginning of the frame), $103$ DQPSK symbols (frame content), and $21$ trailing additional DQPSK symbols. Two symbols (second and fourth quadrant) are more likely to appear than the others, due to the modulation overlapping and the trailing sequence (repetition of the same bit values). Finally, Fig.~\ref{fig:iqtoimage}(b) represents the contour plot of the magnification of Fig.~\ref{fig:iqtoimage}(a), where we highlighted the IQ samples density: about $5,500$ samples per tile at the two peaks. \section{Satellite Authentication Methodologies} \label{sec:satellite_authentication} In this section, we describe the proposed methodology to authenticate satellite transmitters. Specifically, we split the whole IQ samples dataset in three subsets, i.e., \emph{training} ($\mathcal{T}$), \emph{validation} ($\mathcal{V}$), and \emph{testing} ($\mathcal{S}$), each subset accounting for the 60\%, 20\%, and 20\% of the whole dataset, respectively. Moreover, it is worth noting that the number of IQ samples for each satellite is evenly distributed in each subset (i.e., the dataset is balanced by construction). Let us define $\mathcal{D}_s$ the subset of IQ samples from satellite $s$, with $s \in C$ and $C = \{1, \ldots, 66\}$ being the set of satellites in the IRIDIUM constellation. Moreover, let $\mathcal{D}_s$ be the subset of IQ samples from satellite $s$ and $\mathcal{D}_s = \mathcal{T}_s \cup \mathcal{V}_s \cup \mathcal{S}_s$ where $\mathcal{T}_s$, $\mathcal{V}_s$ and $\mathcal{S}_s$ are the training, validation, and testing subsets associated with the IQ samples from satellite $s$. We addressed the physical-layer satellite-authentication problem along two dimensions: \begin{itemize} \item {\bf Multi-class classification.} We aim at being able to correctly authenticate all the satellites in the constellation. This scenario represents the worst case, involving $66$ equivalent classes. We assume prior knowledge on $\mathcal{T}_s, \forall s \in C$. Moreover, we assume the test subset $\mathcal{S}_x$ to be constituted by IQ samples from the satellite constellation, i.e., $x \in C$---although we do not know to which satellite $s$ the IQ samples belong to. \item {\bf Binary classification - One-vs-Rest.} We consider a candidate satellite $s$, and we combine all the remaining IQ samples (from all the satellites belonging to the constellation), thus obtaining two classes: the class containing the reference satellite $s$, and the one being constituted by all the IQ samples belonging to all the remaining satellites, i.e., $C \setminus \{s\}$. Compared to the previous scenario, this one involves limited prior knowledge, i.e., only $\mathcal{T}_s$, with $s$ being the reference satellite. Moreover, we assume $\mathcal{S}_x$ to be any test subset. Indeed, the algorithm adopted for this categorization returns a \emph{similarity score}, e.g., root mean square, which is used to estimate the similarity of the test subset $\mathcal{S}_x$ against the reference training subset $\mathcal{T}_s$. \end{itemize} \begin{table}[] \caption{Classification strategies.} \centering \begin{adjustbox}{width=\columnwidth} \begin{tabular}{lll} \multicolumn{1}{l|}{} & \multicolumn{1}{c|}{\textbf{Prior Knowledge}} & \multicolumn{1}{c}{\textbf{Test Subset}} \\ \hline \multicolumn{1}{l|}{\textbf{Multi-class}} & \multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}\emph{All satellite} \\ training subsets\end{tabular}} & \multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}\textit{Any test subset} of satellites \\ belonging to the constellation\end{tabular}} \\ \hline \multicolumn{1}{l|}{\textbf{One vs Rest}} & \multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}\emph{Only the reference} \\ training subsets\end{tabular}} & \multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}\textit{Any test subset} of satellites \\ belonging to the constellation\end{tabular}} \\ \hline \end{tabular} \end{adjustbox} \label{table:ai_algorithm} \end{table} Table~\ref{table:ai_algorithm} summarizes our assumptions on the adopted categorization strategies. In the remainder of this paper, we refer to \emph{intra-constellation satellite authentication} as the problem of identifying and authenticating a satellite by resorting to a multiclass classification tool (see Section~\ref{sec:intra-satellites}). Conversely, we refer to \emph{satellite authentication in the wild} when applying the one-vs-rest classification model (see Section~\ref{sec:satellite_authentication_inthe_wild}). \section{Intra-Constellation Satellite Authentication} \label{sec:intra-satellites} In this section, we focus on the intra-constellation satellite authentication scenario. Specifically, Section~\ref{sec:convolutional_neural_networks} shows and motivates the deployed CNN, Section~\ref{sec:satellite_authentication_via_cnn} reports details on the application of the described CNN to authenticate IRIDIUM satellite transmitters, while Section~\ref{sec:authentication_subsets} investigates the \ac{CNN} classification performance on subsets of the satellite constellation. \subsection{Convolutional Neural Network Setup} \label{sec:convolutional_neural_networks} In this paper, the multi-class classification task is supported by a \ac{DCNN} based on a Residual Network with $18$ layers (i.e., \emph{ResNet-18}). The original \emph{ResNet-18} has its last fully connected layer composed of $1,000$ neurons (followed by a \textit{softmax} activation function), since it was pretrained on \emph{ImageNet}, a $1,000$-class dataset. Given that our task is to classify $66$~satellites, we replaced the last fully connected \emph{softmax} layer with a fully connected layer composed of 66 neurons only, the number of classes of our dataset. Then, we transferred the set of parameters of the \emph{ResNet-18} convolutional layers to the convolutional layers of our \ac{DCNN}. As mentioned above, although there were many architectures available in the literature, \emph{ResNet} proved to be the most performing \ac{CNN} by construction, since its structure allows to achieve a higher number of layers, while keeping low the number of parameters~\cite{he2016_cvpr}. There are mainly two ways to perform transfer learning in deep neural networks: (i) the fine-tuning approach; and, (ii) the freezing layers approach~\cite{yosinski2014how}. The fine-tuning approach requires to retrain (i.e., unfreeze) the whole network parameters, with the classification errors coming from the new training backpropagating to the whole network. The freezing layer approach, instead, leaves unchanged (i.e., frozen) most of the transferred feature layers. Generally speaking, when the dataset is small compared to the original one (i.e., the dataset on which the network was pre-trained), the freezing layers approach is suggested, otherwise the fine-tuning approach is the most suitable. However, Yosinki et al. in~\cite{yosinski2014how} showed that the freezing layers approach may lead to a drop in performance, while the co-adaptation of the features re-learned with the fine-tuning approach prevents this effect. Since it has been observed that the lower layers of a \ac{CNN} are able to detect features that are usually general for each image recognition task (e.g., curves and edges), and that fine-tuning allows to prevent accuracy drops, in this study we rely on a combination of the two approaches. Indeed, instead of retraining the network from scratch (i.e., fine-tuning approach) or keeping the layers frozen (i.e., freezing layers approach), we fine-tune the layers of the network with a monotonically increasing learning rate: the deeper the layer in the \ac{CNN}, the higher the learning rate. In this way, the parameters of the first layers can still detect common features in images, and we opportunely tune the parameters of the deeper layers in a way to guarantee high accuracy. Figure~\ref{fig:resnet-18} summarizes the proposed architecture. \begin{figure*}[htbp] \centering \includegraphics[width=\textwidth]{figures/resnet.pdf} \caption{Overview of the proposed architecture. \emph{ResNet-18} pre-trained layers are transferred to our \ac{DCNN}, with the replacement of the fully connected layer (i.e., from $1,000$ neurons to $66$), and the fine-tuning with monotonically increasing learning rate.} \label{fig:resnet-18} \end{figure*} \subsection{Satellite Authentication via CNN} \label{sec:satellite_authentication_via_cnn} In this section, we address the problem of authenticating a satellite by classifying the received IQ samples. As discussed in Section~\ref{sec:iq_samples_preprocessing}, IQ samples are pre-processed and converted to $224 \times 224$ greyscale images. Grouping the IQ samples into images involves the following trade-off: on the one hand increasing the number of IQ samples enriches the information possibly conveyed by a single image; on the other hand, the number of available images is reduced smaller, this latter one being the actual input for the classification algorithm that typically performs better as the size of its input increases.\\* Figure~\ref{fig:valacc_samplesimag} shows the validation accuracy as a function of the number of IQ samples per image (or the number of images per satellite). Each circle in the figure represents the result of a single training and validation process while varying the number of IQ samples per image. Moreover, we recall that for each satellite IQ samples subset 60\% of them have been used for training and 20\% for validation. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/valacc_samplesimag.pdf} \caption{Validation accuracy as a function of the number of IQ samples per image (or number of images per satellite).} \label{fig:valacc_samplesimag} \end{figure} The number of IQ samples per image is an important parameter that should be compared with Fig.~\ref{fig:iq_sample_per_pass}. Indeed, the number of IQ samples per image should be matched to a single satellite pass. We could consider waiting for multiple satellites passes, but this approach would involve long waiting times, i.e., at least 92 minutes for the satellite to appear again (recall Fig.~\ref{fig:waiting_time}. Therefore, as a reference parameter, we decided to consider $10,000$ IQ samples per image (leading to 155 images per satellite), guaranteeing a validation accuracy of about $0.83$. Note that the probability to experience at least $10,000$ IQ samples is about $0.7$. {\bf Testing.} We run $30$ iterations of the training, validation, and testing sequence by randomly choosing the images from the dataset. We computed the mean of the resulting confusion matrices from the testing procedure---results in Appendix. The confusion matrix is sorted according to the values in the diagonal, i.e., best performance ($31$) in the top left part of the matrix), being $31$ images ($20\%$ of total 155 images per satellite) the size of the test set for each satellites' image. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/cm_10000_acc_err.pdf} \caption{Hit and Miss rates (mean values) for 30 runs of the \ac{CNN} classification algorithm. For each run, we consider the whole training, validation, and testing procedures.} \label{fig:cm_10000_acc_err} \end{figure} Let us define as the \emph{hit rate} the ratio between the total number of hits (true positive) and the total number of instances (test subset cardinality), yielding: $$ \textrm{hit\ rate} = \frac{TP}{TP+FN}$$ Moreover, let us define as \emph{miss rate} the ratio between the total number of misses (false negative) and the total number of instances (test subset cardinality), yielding: $$ \textrm{miss\ rate} = \frac{FN}{TP+FN}$$ Figure~\ref{fig:cm_10000_acc_err} shows the hit and miss rates for each satellite in the IRIDIUM constellation, extracted from the data associated with the aforementioned testing procedure (recall the confusion matrix in Appendix). We observe that $24$ satellites (more than $36$\% of the constellation) experience a hit rate higher than $0.9$, while only $4$ satellites have a hit rate less than 0.5. \subsection{Authentication of satellite subsets} \label{sec:authentication_subsets} Driven by the results of Section~\ref{sec:intra-satellites}, we investigate the \ac{CNN} classification performance on subsets of the satellite constellation. The intuition relies on removing satellites characterized by high miss rates, which are intrinsically difficult to classify, thus constituting a source of mis-classification for the remaining ones. Therefore, we systematically removed the worst satellites (in terms of hit rate) from the dataset, and we subsequently re-evaluated the performance of the classifier. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/accuracy_exsatellite.pdf} \caption{Testing accuracy as a function of the number of excluded satellites. The removed satellites are the ones with worst performance in terms of hit rate. } \label{fig:accuracy_exsatellite} \end{figure} Figure~\ref{fig:accuracy_exsatellite} shows the accuracy associated with the testing procedure as a function of the number of excluded satellites (the next satellite to be removed is the one with the poorest hit rate among the ones left). The analysis confirms that image-based classification of IQ samples is an effective solution. Indeed, \ac{CNN} classification guarantees a baseline accuracy above $0.82$, which can be made arbitrarily high by removing a few satellites---for instance, removing the worst 9 satellites, the accuracy is higher than $0.9$. \section{Satellite Authentication in the Wild} \label{sec:satellite_authentication_inthe_wild} In this section, we undertake the challenge of authenticating a satellite with minimal prior knowledge, i.e., only a training subset from the satellite to be authenticated. Our intuition is to train a model with a reference training subset, and subsequently, to challenge it with a random test subset. Subsequently, we define a metric, i.e., \emph{reproduction error}, and we estimate the deviation of a synthetically-generated subset from the original one. The reproduction error implies a threshold, under which all the samples are considered as belonging to the satellite to be authenticated. The most suitable class of algorithms for implementing the aforementioned strategy are \emph{autoencoders}. Indeed, after the training phase, the autoencoders will be biased towards the training subset. Therefore, we expect that a synthetically-generated test subset will be characterized by a higher reproduction error, thus being discarded as not belonging to the satellite to be authenticated. We selected the reproduction error as coincident with the \ac{m.s.e.}. In the remainder of this section, we first discuss the architecture of the deployed autoencoders (Section~\ref{sec:autoencoders_auth}). Then, we consider two scenarios: One-vs-Rest (Section~\ref{sec:one-vs_rest}) and One-vs-One (Section~\ref{sec:one-vs_one}). The former undertakes the challenge of authenticating the IQ samples from a reference satellite when compared with IQ samples coming from a set of sources (the other satellites from the constellation). The latter refers to the classification of IQ samples coming from two different sources, i.e., the satellite to be authenticated and another (random) one from the constellation. We stress that our test subset is constituted by IQ samples belonging to the IRIDIUM constellation, only. We consider this assumption the worst-case scenario for our detection algorithms, i.e., the test subset has the same characteristics of the training subset, in terms of technology, scenario, and noise pattern. Moreover, our solution is agnostic to both the content of the messages (bit-string) and the appearance order of the IQ samples, since we collect and classify the IQ samples independently of their mapping to the bit values. \subsection{Satellite Authentication via Autoencoders} \label{sec:autoencoders_auth} \begin{table}[htbp] \caption{Training options of our autoencoder.} \label{table:training_options} \centering \begin{tabular}{|c|c|} \hline \textbf{Parameter} & \textbf{Value} \\ \hline \emph{HiddenSize} & 1,024 \\ \hline \emph{MaxEpochs} & 100 \\ \hline \emph{EncoderTransferFunction} & \emph{logsig} \\ \hline \emph{DecoderTransferFunction} & \emph{logsig} \\ \hline \emph{L2WeightRegularization} & 0.001 \\ \hline \emph{SparsityRegularization} & 1 \\ \hline \emph{SparsityProportion} & 0.05 \\ \hline \emph{LossFunction} & \emph{msesparse} \\ \hline \emph{TrainingAlgorithm} & \emph{trainscg} \\ \hline \emph{ScaleData} & \emph{true} \\ \hline \end{tabular} \end{table} In this study, we relied on the MATLAB implementation of the \emph{Sparse Autoencoder} to perform the \emph{one-vs-rest} and \emph{one-vs-one} IRIDIUM satellites classification. A sparse autoencoder is an autoencoder whose training involves a penalty (also known as sparsity penalty). Several previous works, such as~\cite{makhzani2013k}, observed that classification tasks may see their performance considerably improved when the representations are learned in a way that encourages sparsity (e.g., by adding a regularizer to the cost function). In the following, we motivate the choice of the training options of our autoencoder---training options are summarized in table~\ref{table:training_options}. \\ \textbf{HiddenSize.} It represents the number of neurons in the hidden layer of the autoencoder. The higher the number of neurons, the higher the risk of overfitting, while the lower the number of neurons, the higher the risk of underfitting. We empirically set the number of neurons to $1,024$ since, for our problem, it was a satisfactory trade-off between the two cited conflicting dimensions.\\ \textbf{MaxEpochs.} It is defined as the maximum number of training epochs or iterations. An epoch is defined as a single pass through the training set for all the training examples. We empirically selected the value $50$, since none of the subsequent epochs brought any benefit to the accuracy of our model. \\ \textbf{EncoderTransferFunction.} It represents the linear transfer function of the encoder, i.e., the activation function of the neurons in the hidden layer. In this study, we empirically chose the standard logistic sigmoid function, whose formula is reported in Eq.~\ref{eq:logistic}: \begin{equation} \label{eq:logistic} f(x) = \frac{1}{1 + e^{-x}} \end{equation} \textbf{DecoderTransferFunction.} We relied on the same logistic sigmoid function as activation function of the decoders neurons. \\ \textbf{L2WeightRegularization.} Generally speaking, regularization is a technique that discourages a model from becoming too complex, so as to avoid overfitting. It works on the assumption that smaller weights generate simpler models, and it requires to add a regularization term on the weights of the cost function, to prevent them from growing uncontrollably. The L2 regularization term is defined according to Eq.~\ref{eq:reg}. \begin{equation} \label{eq:reg} \Omega_{w} = \frac{1}{2}\sum\limits_l^L \sum\limits_j^n \sum\limits_i^k w_{ji}^{(l)}, \end{equation} where $L$ is the number of hidden layers, $n$ is the number of samples, and $k$ is the number of variables in the input data, respectively. This term is added to the loss function of the autoencoder with a multiplicator $\lambda$, that we empirically set to $0.001$. \\ \textbf{SparsityRegularization.} Sparsity regularization methods attempt to leverage the assumption that, to be learned, an output variable can be described by a reduced number of variables in the feature space. The goal of these methods is to select the input variables that best describe the output. In the autoencoder context, the sparsity regularization term is represented by the Kullback-Leibler divergence, reported in Eq.~\ref{eq:div}. \begin{equation} \label{eq:div} \Omega_{s} = \sum\limits_{i=1}^{D^{(1)}}KL(\rho || \hat{\rho_i}) = \sum\limits_{i=1}^{D^{(1)}} \rho log\left(\frac{\rho}{\hat{\rho_i}}\right) + (1-\rho)log\left(\frac{1 - \rho}{1 - \hat{\rho_i}}\right), \end{equation} where $\rho$ and $\hat{\rho}$ represent two distributions. The Kullback-Leibler divergence allows to measure the differences of two distributions. Since this term is inserted within the loss function, minimizing the cost function allows to minimize the term, thus eventually forcing the distributions to be similar. \\ The sparsity regularization parameter (namely, $\beta$) allows to control the impact that the sparsity regularizer $\Omega_{s}$ has in the cost function. The higher the parameter, the more impact the regularizer has on the cost function. We empirically set this value to $1$. \\ \textbf{SparsityProportion.} It represents the proportion of training examples a neuron reacts to. The lower the value of this parameter, the more each neuron will be specialized (i.e., by giving high output only for a small number of training examples). Generally speaking, the lower the sparsity proportion, the higher the degree of sparsity is. We empirically set the parameter to $0.05$. \\ \textbf{Loss Function.} We relied on the standard mean squared error performance function, with L2 weight and sparsity regularizers loss function ($msesparse$), defined as in Eq.~\ref{eq:mean}. \begin{equation} \label{eq:mean} E = \frac{1}{N}\sum\limits_{n=1}^N \sum\limits_{k=1}^K {(x_{kn} - \hat{x}_{kn})}^2 + \lambda * \Omega_{w} + \beta * \Omega_{s}, \end{equation} where the first term in the addition represents the mean squared error, $\lambda$ is the coefficient controlling the impact of the $L_2$ regularization term (i.e., $0.001$ in our case), and $\beta$ is the coefficient controlling the impact of the sparsity regularization term (i.e., $1$ in our case). \\ \textbf{TrainingAlgorithm.} We relied on the scaled conjugate gradient descent~\cite{moller1993scaled} ($trainscg$) learning algorithm to train our autoencoder. The algorithm is based on a class of optimization techniques known as conjugate gradient methods, and proved to be more effective and one order of magnitude faster than the standard backpropagation algorithm. \\ \textbf{ScaleData.} This parameter allows to control the rescaling of the input data. For the training to be effective, the range of the input data has to match the one of the transfer function for the decoder. By setting this value, the autoencoder scales the data whenever there is a need for, to optimize the algorithm learning capabilities. \subsection{One-vs-Rest} \label{sec:one-vs_rest} In this section, we consider the \emph{One-vs-Rest} scenario: the reference satellite (to be authenticated) versus the rest of the constellation. Figure~\ref{fig:mse25} resumes the results of our methodology for the case of the satellite with $s=25$. We trained the autoencoder with the training subset, constituted by the $80$\% of the subset samples from satellite $25$. Then, we used the trained autoencoder to generate a training subset and we estimated the \ac{m.s.e.} between the two subsets, i.e., the original one and the generated one. The circles in Fig.~\ref{fig:mse25} identifies the probability density function associated with the \ac{m.s.e.} computed over the original training subset and the generated one. We performed the same procedure on the validation subset (remaining $20$\% of the samples from satellite $25$), and we computed the probability density function associated with the \ac{m.s.e.} between the original validation subset and the generated one, as depicted by the distribution identified by the crosses in Fig.~\ref{fig:mse25}. It is worth noting that the two distributions (the one associated to the training subset and one associated to the validation subsets) are characterized by the same \ac{m.s.e.}, in the range between $0.2$ and $0.5$. We applied the same process to a test set. The test set has been constructed by considering all the satellites from the IRIDIUM constellation, but the one with ID $25$. We consider the previous one as the worst-case scenario, since we considered the IQ samples originated from transceivers belonging to the same owner, all of them deployed within a short time delay, and hence very likely featuring the same hardware. Asterisks in Fig.~\ref{fig:mse25} identifies the distribution associated with the \ac{m.s.e.} computed between the generated test and training subset. The test subset is characterized by \ac{m.s.e.} values in the range between $0.7$ and $1.4$, with only a few values less than $0.5$. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/mse25.pdf} \caption{Distribution of the \ac{m.s.e.} for the training, validation, and testing procedures with autoencoders (\emph{One-vs-Rest} scenario for satellite with ID 25). The inset figure highlights the \ac{ROC} curve and the optimal point.} \label{fig:mse25} \end{figure} By defining a threshold $thr$ in the range between $0.2$ and $1.5$, and assuming as legitimate the \ac{m.s.e.} values less than $thr$, we can experience different \ac{FP} and \ac{FN} events. The trade-off between FP and FN can be evaluated by resorting to the associated \ac{ROC} curve, as shown in in the inset of Fig.~\ref{fig:mse25}, where the \ac{TPR} is evaluated as a function of the \ac{FPR}, with TPR and FPR being $\frac{TP}{TP+FN}$, and $\frac{FP}{FP+TN}$, respectively. In optimal conditions, i.e., $TPR = 1$ and $FPR=0$, the \ac{AUC} should be equal to $1$; in our case, for the developed example related to the satellite with ID $25$, we report an AUC of about $0.98$. Finally, we considered the optimal ROC curve, i.e., the best cut-off with the highest TPR and lowest FPR, and we reported this value as the red circle in the inset of Fig.~\ref{fig:mse25}, with coordinates $[0.048, 1]$. We applied the aforementioned procedure for all the satellites in the constellation, thus evaluating the optimal operating point in the ROC curve for each of the investigated satellites. We report the results of our analysis in Fig.~\ref{fig:optimal_point_roc_heatmap}, via a heat-map which reports the minimum distance between each coordinate in the TPR-FPR plane to the optimal points (from the ROC curves). The $66$ red dots identifying the optimal operating points of the ROC curves (one per satellite) are very close to each other, and in turn, very close to the optimal point $TPR = 1,~ FPR = 0$. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/optimal_point_roc_heatmap.pdf} \caption{Optimal operating point of the ROC curve for each satellite when testing (with autoencoders) one satellite against the features extracted from the whole constellation dataset (\emph{one-vs-rest}).} \label{fig:optimal_point_roc_heatmap} \end{figure} Finally, we conclude the discussion of the \emph{one-vs-rest} scenario by considering the AUC for each of the satellite in the constellation. Figure~\ref{fig:auc} shows the sorted AUC values for all the satellites in the IRIDIUM constellation. AUC values are characterized by very high values (greater than $0.93$), proving the effectiveness of the proposed solution. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/auc.pdf} \caption{\ac{AUC} for each satellite in the constellation when performing One-vs-Rest classification.} \label{fig:auc} \end{figure} \subsection{One-vs-One} \label{sec:one-vs_one} In this section, we consider the \emph{One-vs-One} scenario: the reference satellite (to be authenticated) versus each one of the satellites in the constellation. We followed the same methodology of Section~\ref{sec:one-vs_rest}, by considering the generation of a training and test subset and their comparison in terms of \ac{m.s.e.} values. Finally, we considered different thresholds, and we evaluated the AUC for each satellite pair in the IRIDIUM constellation. Indeed, for each considered reference satellite, we evaluated $66$ classifications and the related AUC. Figure~\ref{fig:autoencoders} shows the error-bars (quantile $95$, $50$, and $5$) associated with each considered reference satellite. We adopted the same order as before, i.e., satellites are sorted by performance (best on the left) considering the median value. We observe that the quantile $95$ and the median are coincident and equal to $1$ for almost all the satellites, while only few satellites are characterized by a quantile $5$ below $0.99$. This is due to a few satellite-to-satellite classifications experiencing lower performance, but still characterized by AUC values greater than $0.96$. \begin{figure}[htbp] \centering \includegraphics[width=\columnwidth]{figures/autoencoders_o2o.pdf} \caption{Error-bars (quantile $5$, $50$, and $95$) associated with the \ac{AUC} for each satellite in the constellation, when performing \emph{One-vs-One} classification.} \label{fig:autoencoders} \end{figure} \section{Conclusion} \label{sec:conclusion} We presented PAST-AI, a methodology to achieve physical-layer authentication of satellite transmitters by harnessing the power of deep learning classifiers, such as \acp{CNN} and autoencoders, applied to the IQ samples generated by transmitters. We are the first ones, to the best of our knowledge, to prove that radio fingerprinting can be achieved even in the satellite domain---in particular, for LEO constellations---characterized by high attenuation, multi-path fading, strong Doppler effect, and short link duration. We investigated the challenges associated with two scenarios: (i) intra-satellite classification; and, (ii) satellite classification in the wild. We validated our methodology on a dataset generated from a real measurement campaign, involving more than 100M IQ samples collected from the IRIDIUM constellation. Through a careful adaptation and tuning of the discussed deep learning classifiers, we are able to achieve a classification accuracy that spans between $0.8$ and $1$, depending on the scenario assumptions. We believe that the novelty of the introduced scenarios, the detailed methodology, the performance achieved by our solution and, finally, the publicly-available dataset, will pave the way for future research in the area. \balance \bibliographystyle{IEEEtran}
{'timestamp': '2020-10-13T02:29:04', 'yymm': '2010', 'arxiv_id': '2010.05470', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05470'}
arxiv
\section{Introduction} \label{sec:intro} This paper examines stochastic decentralized resource optimization in the context of a multi-agent, multi-target surveillance mission. The resources we consider are mobile/unmanned agents which are capable of selecting their own motion. The setting of this problem is deliberately generic, so these unmanned agents could, for example, be aerial or underwater. The mission of these agents is to learn as much as possible about the kinetic states (position and velocity) of the nearby targets. They do this by iteratively (one agent at-a-time) minimizing a loss function which is stochastically measured. This loss function decreases with growing information of the targets, and by minimizing this loss function, the agents end up tracking the targets. This idea was initially explored in \cite{Peterson1} and \cite{Botts1}, but these studies were done in two dimensions. This paper builds on those results by extending the study to three dimensions, implementing a more accurate and stable estimation method, and considering the applicability of this swarming algorithm for a large number of agents. We even investigate how multiple groups of agents (each group containing several agents and working independently of any other group) track and follow several targets. This section begins by giving details of the problem, discussing the assumptions we make, and comparing these aspects of our study with those that are currently in the swarming literature. This is done in Section \ref{sec:intro_probDescription}. Some brief details regarding the loss function are then given in Section \ref{sec:intro_lossFunction}. In Section \ref{sec:Centralized_vs_Decentralized}, we discuss the various methods that can be used to minimize such a loss function. \subsection{Problem Description and Assumptions} \label{sec:intro_probDescription} The problem discussed in this paper is how to configure several mobile sensing agents over time and 3D space so that their awareness of the targets is optimized. We say that an agent's ``awareness'' of a target increases if the uncertainty in its estimates of the target's states decreases. We assume that some aspects of the agents and targets are unpredictable in time, including target motion and sensing reliability. Since aspects such as these change with time, no steady-state solution exists; any optimal solution at a particular time may not be optimal in the immediate future. The agents optimize their configuration and orientation using decentralized motion planning. In decentralized motion planning, each agent decides on its heading and vertical displacement at each time step via minimization of a loss function. For each agent, this minimization is attempted analytically, i.e., it is done in one step and it is done by taking the gradient of the stochastic loss function. These are the two primary features of our proposed algorithm that distinguish it from other swarming-type algorithms: (1) the loss function we are minimizing changes at each time step, which necessitates a quick (analytical and one-step) solution, and (2) the loss function being minimized is stochastic. The efficacy of other swarming algorithms in optimizing a stochastic function is still not clear, while certain studies have shown that CSO does converge when optimizing noisy functions (see Ref. \cite{Hernandez}). Many of the most common swarming optimization algorithms are also derivative-free and require multiple steps in optimizing a single function. Such algorithms would be impractical in the setting we consider, and some of these algorithms are reviewed below. Genetic algorithms are swarming optimization algorithms which begin by considering a set, or an initial population, of possible solutions. The feasibility or fitness of each solution in this set is then examined, and the set is then accordingly refined into a new set of possible solutions. This new set can be thought of as the next generation of the population. This refinement is done using an action that is modeled after genetic/evolutionary processes, such as mutation, crossover, or reproduction. Genetic algorithms continue to refine this set/population until they find the optimal solution. Genetic algorithms have been successfully applied to many problems including those in operations management (see Ref. \cite{Lee}) and health (see Refs. \cite{Reddy, Devarriya}). Differential evolution is another swarming optimization algorithm similar to genetic algorithms. It too begins with an initial population, or set of possible solutions. From these solutions, a new set of candidate solutions are created, and if a candidate is superior to its parents, it replaces its parents in the set of solutions. Variations of it have also been successfully applied to many problems (see Refs. \cite{Chai, Sickel, Jebaraj}). The Artificial Bee Colony (ABC) algorithm (see Refs. \cite{Karaboga, KarabogaAkay}) is a swarming optimization algorithm inspired by the food-seeking behavior of honey bees. In the ABC algorithm, the optimal solution is found by ``employed" bees exploring solutions/sources of food, communicating their findings to ``onlooking" bees, after which the onlooking bees select a source of food (a solution) that is better than the current one. Particle Swarm Optimization (PSO) is yet another swarming optimization algorithm modeled after animal behavior (bird flocking). Like the other swarming algorithms, PSO begins with a set of candidate solutions/particles. These particles swarm towards the optimal solution by iteratively evaluating the feasibility of the particles in the set, and flocking towards those particles which have good (or better) solutions. Just as with genetic algorithms and differential evolution, ABC and PSO have been successfully applied to solve a myriad of problems (see Refs \cite{Mac, Bansal, Jadhav}). In some cases, different types of swarming algorithms are combined into one overall optimization algorithm. In Fares et al. (Ref. \cite{Fares}), for example, a recently developed swarming algorithm called the whale optimization algorithm (see Ref. \cite{Mirjalili}) is initially used to explore spaces of the function to be optimized. The PSO then acts on the feedback from the whale optimization algorithm to finally optimize the function. Even if convergence of these swarming algorithms in the presence of a noisy objective function was guaranteed, applying algorithms such as these to our problem would be impractical. In our case, the agents are not swarming to the same point that minimizes the loss function. They are seeking the optimal spatial arrangement, and they are doing this at each time point. To apply any of the algorithms mentioned above, multiple configurations of the agents would have to be considered and repeatedly acted upon to find the optimal one. This procedure would also have to happen at each time point since the loss function at each time point is different. A more efficient strategy is preferred, and that is why we consider minimizing the loss function as we do. This loss function is discussed in the section below. \subsection{The Loss Function} \label{sec:intro_lossFunction} As in \cite{Botts1}, the loss function is information-based, stochastic, and time-varying. By information-based, we mean that the function to be minimized quantifies the expected information gain resulting from agents making specific motions. Having agents or sensors select motions or actions to maximize some measure of information on targets has been done before. In Sinha et al. (Ref. \cite{Sinha}), for example, UAVs make decisions to optimize an objective function which optimizes the detectability and information on the kinetic states of ground-based targets. Kreucher et al. (Ref. \cite{Kreucher}) has sensors select actions (where to move and what direction to emit energy, for example) to maximize information gain on targets, and Yang et al. (Ref. \cite{Yang}) even studied sensor resource management when information gain is optimized yet defined in alternative ways. The loss function we employ is also stochastic since it is a function of the agent's measurements of the targets. These measurements are random, making the loss function random. Randomness (or stochasticity) in the loss function changes the minimization process because the algorithm often gets misleading information about the fitness of the solution. Finally, the loss function is time-varying since the agents and targets move at every time step, and the motion of the targets may be entirely unpredictable. As the agents and targets move, the detectability of the targets, the view geometries of the agents, and the agents' ability to communicate change. These changes affect the loss function. The subsection below discusses two ways in which the loss function can be minimized. \subsection{Centralized vs. Decentralized Optimization} \label{sec:Centralized_vs_Decentralized} Centralized and decentralized optimization methods each have a role in resource optimization. In centralized optimization, the action of all agents are optimized simultaneously, whereas in decentralized optimization, each agent selects its optimal move separately. Because our agents do not perfectly communicate, they can not always share information, and their decisions are often based on limited data. Each agent must thus act individually. If communications were not a problem, all agents would simultaneously have the exact same information of all the targets, and all the agents would coordinate together to arrive at a globally optimal solution. This globally optimal solution is identical to centralized optimization. Some literature has recently emerged on cooperative control of multiple agent systems (see Ref.~\cite{Gazi} for a current and broad overview). Tang et al. (Ref. \cite{Tang}), for example, studied how agents can cooperate to minimize the average amount of time between target detections. Jin et al. (Ref. \cite{Jin}) investigated how effectively agents cooperate if the number and location of the targets are known {\it a priori}, and DeSena et al. (Ref. \cite{DeSena13}) studied the effectiveness of multi-agent decentralized collaboration as a function of communication connectivity. It is still unclear, however, exactly how the decentralized optimization process degrades the centralized solution when the function being optimized is stochastically measured. Some preliminary theoretical results have recently emerged, though, regarding convergence conditions on the cyclic optimization of stochastic functions (see Ref. \cite{Hernandez}). In Section \ref{sec:joint-estim-ctrl-prob}, more details of the decentralized control problem are described. In Section \ref{sec:EKF}, we describe how each agent estimates the states of the targets, and in Sections \ref{sec-lossFunctionFormulation} and \ref{sec:cso-seesaw}, we describe the details of how an agent minimizes this loss function. In Section \ref{sec:simulations}, the results of some simulations are given, and in Section \ref{sec:conclusions}, conclusions and areas of future work are discussed. \section{Decentralized Control Problem Definition} \label{sec:joint-estim-ctrl-prob} We have a decentralized control problem in which each agent decides its actions according to its estimates of targets and its information communicated to it by other agents. We refer to each agent's iterative estimation and control process as its \emph{perception-action cycle} (PAC) (see, e.g., Ref.~\cite{Haykin}). For the agents considered in this paper, the PAC consists of the following steps: sense, communicate, infer, decide, and move. This process is illustrated in Figure~\ref{fig:per-agent-planning-cycle}, and a description of the steps follows. In the description, the true state of target $i$ at time $k$ will be denoted as $${\bf x}_{k;i} = \left( x_{k;i}^E, x_{k;i}^N, x_{k;i}^U, \dot{x}_{k;i}^E, \dot{x}_{k;i}^N, \dot{x}_{k;i}^U \right),$$ where $x_{k;i}^E$ is the east coordinate of target $i$ at time $k$, $x_{k;i}^N$ is its north coordinate, $x_{k;i}^U$ is its up (or vertical) coordinate, ${\dot{x}}_{k;i}^E$ is its velocity in the east direction, ${\dot{x}}_{k;i}^N$ is its velocity in the north direction, and ${\dot{x}}_{k;i}^U$ is its velocity in the up direction. And in the simulations we conducted in this study, the procedure described below was executed for each agent at each time step. \begin{figure}[th] \begin{center} \begin{tabular}{c} \includegraphics[width=0.4\textwidth]{perception-action-cycle.pdf} \end{tabular} \end{center} \caption[example] { \label{fig:per-agent-planning-cycle} Per-agent perception-action planning cycle. } \end{figure} \begin{enumerate} \item SENSE: The agent measures the range, azimuth angle and polar angle to all the targets that it senses. The range, azimuth angle and polar angle that agent $j$ measures to target $i$ at time $k$ will be denoted $r_{k;i;j}$, $\phi_{k;i;j}$ and $\theta_{k;i;j}$, respectively, where \begin{eqnarray*} r_{k;i;j} & = & \sqrt{( \Delta_{k;i;j}^E )^2 + (\Delta_{k;i;j}^N)^2+ (\Delta_{k;i;j}^U)^2} \\ \phi_{k;i;j} & = & \tan^{-1} \left[ (\Delta_{k;i;j}^N ) / ( \Delta_{k;i;j}^E ) \right], \\ \theta_{k;i;j} & = & \cos^{-1} \left[ \left. \left( \Delta_{k;i;j}^U \right) \right/ r_{k;i;j} \right], \\ \Delta_{k;i;j}^E & = & x_{k;i}^E - y_{k;j}^E, \\ \Delta_{k;i;j}^N & = & x_{k;i}^N - y_{k;j}^N, \\ \Delta_{k;i;j}^U & = & x_{k;i}^U - y_{k;j}^U, \end{eqnarray*} and $ \left( y_{k;j}^N, y_{k;j}^E, y_{k;j}^U \right)$ are the north, east, and up coordinates of agent $j$. \item COMMUNICATE: The agent sends state estimates, Fisher information matrices, and its most recent motion decision to peer agents. The reliability and latency of these communications vary with the type of vehicle considered and the environment in which they are operating. Pantelimon et al. (Ref. \cite{Pantelimon}) review the communication strategies and hardware involved in various types of unmanned vehicle deployments. For aerial vehicles, Wi-Fi modules are the most common hardware. They have a communication range close to 100m and a communication latency on the order of one millisecond. The size and the necessary programming involved in setting up such Wi-Fi hardware is a drawback, however. Bluetooth is a less reliable alternative and has a smaller communication range, but it may be preferable to Wi-Fi as it is lower in weight and complexity. Acoustic communications are the best for underwater vehicles, but the weight, complexity and cost of the hardware involved in such communications is relatively high. The latency is also quite large (close to 0.67 ms/m, see Ref. \cite{Burrowes}). The simulations we conduct in this study incorporate a model for gradual attenuation of communication over distance, and this is consistent with real-world performance. \item INFER: Given the information sensed, the agent updates the state estimate for each detected target via a second order extended Kalman filter. The state estimate agent $j$ has of target $i$ at time $k$ given all the data up until (and including) time $k$ will be denoted as \begin{eqnarray*} {\hat {\bf x}}_{k|k;i; j} & = & \left( {\hat {x}}_{k|k;i;j}^E, {\hat{ x}}_{k|k;i;j}^N, {\hat{ x}}_{k|k;i;j}^U, \right. \\ & &~~ \left. {\widehat {\dot{x}}}_{k|k;i;j}^E, {\widehat {\dot{x}}}_{k|k;i;j}^N, {\widehat {\dot{x}}}_{k|k;i;j}^U \right). \end{eqnarray*} The state estimate agent $j$ has of target $i$ at time $k$ given all the data up until (but not including) time $k$ will be denoted as \begin{eqnarray*} {\hat {\bf x}}_{k|k-1;i; j}& = & \left( {\hat {x}}_{k|k-1;i;j}^E, {\hat{ x}}_{k|k-1;i;j}^N, {\hat{ x}}_{k|k-1;i;j}^U, \right. \\ & &~~ \left. {\widehat {\dot{x}}}_{k|k-1;i;j}^E, {\widehat {\dot{x}}}_{k|k-1;i;j}^N, {\widehat {\dot{x}}}_{k|k-1;i;j}^U \right). \end{eqnarray*} With these estimates and the other information communicated to it from peer agents, the agent estimates the loss function. The details of this loss function are given in Section \ref{sec-lossFunctionFormulation}. \item DECIDE: The agent selects its next action (its heading and vertical displacement) by minimizing its estimated loss function. The details of this step are given in Section \ref{sec:cso-seesaw}. \item MOVE: Each agent updates its state according to its selected action (its selected heading and vertical displacement). It is assumed that the time scale is large enough that rotational dynamics are negligible, and the vehicle can instantaneously change direction. In this paper, the state of agent $j$ at time $k$ will be denoted as ${\bf y}_{k;j} = \left( y_{k;j}^E, y_{k;j}^N, y_{k;j}^U, \dot{y}_{k;j}^E, \dot{y}_{k;j}^N, \dot{y}_{k;j}^U \right)$, and the heading of agent $j$ at time $k$ will be denoted $\gamma_{k;j}$. The relation between $\gamma_{k;j}$ and ${\bf y}_{k;j}$ is $\gamma_{k;j} = \tan^{-1} \left( \left. \dot{y}_{k;j}^N \right/ \dot{y}_{k;j}^E \right)$. \end{enumerate} As mentioned earlier, these steps are meant to occur sequentially in agents and among agents, implying that an agent will execute the entirety of these steps, then another agent will, then another will, etc. The time difference between agents executing the PAC steps thus has to account for communication latency and the time it takes an agent to do the necessary processing and computing. Section \ref{sec:EKF} gives the details on Steps 2 - 4, i.e., it discusses how the agents sense and estimate the state of the targets. Section \ref{sec-lossFunctionFormulation} then gives details on how each agent estimates and attempts to minimize the loss function (Steps 3-4). \begin{comment} An agent's optimization of its motion is subject to a number of constraints, primarily consisting of physical motion limits, Bayesian update laws, data available via target detections governed by sensor detection range (and therefore by spatial configuration of agents relative to targets), and data available from peer agents governed by communications range (and therefore by spatial configuration of agents). The evaluation of the loss in the DECIDE step requires predicting target and agent states and uncertainties forward in time. These prediction steps are separate from the time predict steps executed by the Bayesian filter in the INFER step, and in general, may use lower fidelity models to reduce computational complexity since they are applied a very large number of times within a combinatorial optimization. We assume that the agents apply Bayesian updating to incorporate new information into local state estimates. Therefore, with $\hat{X}^{(j)}_{k}$ representing agent $j$'s knowledge of $X$ (e.g., a vector of target positions, own position, and other agent positions) at time step $k$, $Z^{(j)}_{1:k}$ representing agent $j$'s aggregated data from sensor measurements and communications from other agents for all previous and current time steps, and $P^{(j)}_{k}(\hat{X}^{(j)}_{k}|Z^{(j)}_{1:k})$ representing agent $j$'s probability or belief density of the state given the available information, we have \begin{equation} P^{(j)}_{k}(\hat{X}^{(j)}_{k}|Z^{(j)}_{1:k}) = K P^{(j)}_{k}(\hat{X}^{(j)}_{k}|Z^{(j)}_{1:k}) P^{(j)}_{k}(\hat{X}^{(j)}_{k-1}) \end{equation} where $ P^{(j)}_{k}(\hat{X}^{(j)}_{k})$ represents a likelihood function defined in the standard way and $K$ denotes a normalizing constant. We note that the available information $Z^{(j)}_{1:k}$ may contain contributions from other agents’ local state estimates. The Bayesian recursion above provides the basis for computing the updated estimate that is needed in carrying out the improvement (or optimization) process at iteration $k+1$. We further assume that, in the general case, the agents determine control actions by approximately optimizing a partially observable Markov decision process (POMDP) (Bellman1957, Puterman2005; Powell2011) over multiple time steps. The recursion to solve a POMDP computes a sequence of loss functions that converge toward the optimum (solution of Bellman’s equation). The recursion has two steps, traditionally referred to as value update and policy update. Both of the value update and the policy update steps in standard POMDP require evaluation of the loss function $L$. Even when $L$ is known, the value and policy recursions over infinite or long time horizons are computationally intractable in general. Moreover, we have only a noisy value of $L$ in the stochastic setting. A goal, therefore, is to use decentralization to help break the curse of dimensionality and to use techniques that produce feasible control policies that are stochastically convergent ($k \to \infty$) and reasonable approximations to the optimum in a finite number of iterations (finite $k$). It is acceptable for agents to compute approximate or suboptimal solutions, but there should be a means by which the degree of approximation or sub-optimality can be quantified. For the simulations presented in this paper, we simplify by optimizing only over a single action, which reduces the POMDP to a standard optimization. \end{comment} \section{Estimating the State of the Target} \label{sec:EKF} This section describes how an agent estimates the states of a target that it senses. We begin by letting $S_{k;i;j} = 1$ if agent $j$ senses target $i$ and $S_{k;i;j} = 0$ otherwise. Each agent also assumes that the motion of target $i$ can be characterized with the state equation \begin{equation} \label{eqn:TrgtMotion} {\bf x}_{k;i} = \Phi {\bf x}_{k-1; i} + {\bf w}_{k;i}, \end{equation} where ${\bf w}_{k;i} \sim N \left( {\bf 0}_{6 \times 1}, {\bf Q} \right),$ and \begin{equation} \label{eqn:PhiMatrix} \Phi = \left( \begin{array}{cccccc} 1 & 0 & 0 & \Delta t & 0 & 0 \\ 0 & 1 & 0 & 0 & \Delta t & 0 \\ 0 & 0 & 1 & 0 & 0 & \Delta t \\ 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 \end{array} \right). \end{equation} The coordinates in Equation \ref{eqn:TrgtMotion} are in East, North, and Up, yet the agents sense range, azimuth and polar angle. The measurements agent $j$ makes of target $i$ are thus $$ {\bf z}_{k;i;j} = h \left( {\bf x}_{k;i} \right) + {\bf v}_{k;i;j} = \left( r_{k;i;j}, \phi_{k;i;j}, \theta_{k;i;j} \right)^T + {\bf v}_{k;i;j},$$ where ${\bf v}_{k;i;j} \sim N \left( {\bf 0}_{3 \times 1}, {\bf R} \right),$ and ${\bf R} = {\rm diag} \left( \sigma^2_r, \sigma^2_\phi, \sigma^2_{\theta} \right).$ The agent then applies a second order extended Kalman filter to obtain estimates of ${\bf x}_{k;i}$. A second order extended Kalman filter is used rather than a first order extended Kalman filter since it produces more accurate state estimates and the additional computational cost of using it is negligible. The details of how agent $j$ calculates these estimates of target $i$ are given in the text box labeled ``The Second Order Extended Kalman Filter." With the estimates calculated in the extended Kalman filter, an agent estimates a loss function. The motion it takes at time $k$ is selected to minimize this loss function. The details of the loss function and its minimization are given in the section below. \section{Formulation and Minimization of the Loss Function} \label{sec-lossFunctionFormulation} As mentioned earlier, in each DECIDE step an agent selects a heading and vertical displacement. This is done to minimize a loss function which measures information over the targets. The more information on the targets, the smaller the loss function. In performing its local minimization, however, each agent can only approximate the loss function using estimates of target states and predictions of peer agent actions. We define the ``information'' about target $i$ using the Fisher information matrix (FIM) of the state estimates on target $i$. We denote the total pre-action FIM of target $i$ at time $k$ as ${\bf F}_{k|k-1;i}^{\rm Total}$, where ${\bf F}_{k|k-1;i}^{\rm Total}$ is the sum of every agent's knowledge (or ``information'') about target $i$ before data at time $k$ has been processed. It is meant to measure the entire information of target $i$ before time $k$, and it is mathematically written as \begin{equation} \label{eqn:preactionFisher} {\bf F}_{k|k-1;i}^{\rm Total} = \sum_{j=1}^A {\bf F}_{k|k-1;i;j}, \end{equation} where $A$ is the total number of agents, and ${\bf F}_{k|k-1;i;j}$ is the pre-action FIM that agent $j$ has on target $i$'s states at time $k$, i.e., ${\bf F}_{k|k-1;i;j} = {\bf P}_{k|k-1;i;j}^{-1}$. The total pre-action FIM of target $i$ at time $k$ (as calculated in (\ref{eqn:preactionFisher})) would be equivalent to the true total Fisher information on target $i$ if all measurements and estimates on the target were independent, which they are not. Independence of these measurements and estimates is an assumption we are making in this study. \begin{tcolorbox} \begin{center} \begin{large} The Second Order Extended Kalman Filter \end{large} \end{center} Let ${\hat {\bf x}}_{{k|k-1};i;j}$ be the predicted state estimate of target $i$ by agent $j$, and let ${\bf P}_{k|k-1;i;j}$ be the corresponding predicted error covariance of ${\hat {\bf x}}_{{k|k-1};i;j}$. That is, $${\bf P}_{k|k-1;i;j} = {\mathbbm E} \left[ \left( {\hat {\bf x}}_{{k|k-1};i;j} - {\bf x}_{{k};i} \right) \left( {\hat {\bf x}}_{{k|k-1};i;j} - {\bf x}_{k;i} \right)^T \right].$$ Then$${\hat {\bf x}}_{k|k;i;j} = {\hat {\bf x}}_{{k|k-1};i;j} + {\bf K}_{k;i;j} {\bf u}_{k;i;j} {\mathbbm 1} \left( S_{k;i;j} = 1 \right),$$ and $${\bf P}_{k|k;i;j} = \left[ {\bf I}_{6 \times 6} - {\bf K}_{k;i;j} {\bf H}_{k;i;j} {\mathbbm 1} \left( S_{k;i;j} = 0 \right) \right] {\bf P}_{k|k-1;i;j},$$ where \begin{eqnarray*} {\bf K}_{k;i;j} & = & {\bf P}_{k|k-1;i;j} {\bf H}_{k;i;j}^T {\bf S}_{k;i;j}^{-1}, \\ {\bf H}_{k;i;j} & = & \left. {\frac{\partial h}{\partial x}} \right|_{{\bf x} = {\hat {\bf x}}_{k|k-1;i;j}}, \\ {\bf S}_{k;i;j}[l,m] & = & {\bf H}_{k;i;j} {\bf P}_{k|k-1;i;j} {\bf H}_{k;i;j}^T + {\bf R} + \\ & & \left[ {\frac{1}{2}} {\rm tr} \left( \nabla_x^2 h_l \left( {\hat {\bf x}}_{k|k-1;i;j} \right){\bf P}_{k|k-1;i;j} \cdot \right. \right. \\ & & \left. \left. \nabla_x^2 h_m \left( {\hat {\bf x}}_{k|k-1;i;j} \right){\bf P}_{k|k-1;i;j} \right) \right] \\ {\bf u}_{{k};i;j}[l] & = & {\bf z}_{{k};i;j} - \left \{ h \left( {\hat {\bf x}}_{{k|k-1};i;j} \right) + \right. \\ & & \left. {\frac{1}{2}} {\rm tr} \left[ \nabla_x^2 h_l \left( {\hat {\bf x}}_{k|k-1;i;j} \right){\bf P}_{k|k-1;i;j} \right] \right \}. \end{eqnarray*} With ${\hat {\bf x}}_{k|k;i;j}$ it is straight-forward for agent $j$ to obtain the predicted value of ${\bf x}$ for target $i$ at time $k+1$. This is ${\hat {\bf x}}_{k+1|k;i;j} = {\pmb \Phi} {\hat {\bf x}}_{k|k;i;j}$ and the predicted error covariance associated with this estimate is ${\bf P}_{k+1|k;i;j} = \Phi {\bf P}_{k|k;i;j} \Phi^T + {\bf Q}$. The detailed calculations of ${\bf H}_{k;i;j}$ are given in the Appendix. \end{tcolorbox} We specifically use the log determinant of the pre-action Fisher information, $\log | {\bf F}_{k|k-1;i}^{\rm Total} |$, to quantify information about target $i$ before new data is acquired, and the log determinant of the post-action Fisher information, $\log | {\bf F}_{k|k;i}^{\rm Total}({\pmb \xi}_k^{\rm all}) |$, to quantify information about target $i$ after new data is acquired. This new data is obtained as a consequence of all the agents executing actions ${\pmb \xi}_k^{\rm all}$ at time $k$, where ${\pmb \xi}_k^{\rm all} = \left( {\pmb \xi}_{k;1}, {\pmb \xi}_{k;2}, \ldots, {\pmb \xi}_{k;A} \right)$, ${\pmb \xi}_{k;j}$ is the action taken at time $k$ by agent $j$, ${\pmb \xi}_{k;j} = \left( \gamma_{k;j}, y^U_{k;j} \right)^T,$ $\gamma_{k;j}$ is the bearing agent $j$ takes at time $k$, and $y^U_{k;j}$ is the vertical position it chooses at time $k$. Mathematically, $\gamma_{k;j}$ can be written as \begin{equation*} \gamma_{k;j} = \tan^{-1} \left( {\frac{y_{k;j}^N - y_{k-1;j}^N}{y_{k;j}^E - y_{k-1;j}^E}} \right). \end{equation*} The information gain on the states of target $i$ at time $k$ as a result of the agents taking actions ${\pmb \xi}^{\rm all}_k$ is then defined as the difference between these measures of information, \begin{equation} \label{eqn:InfoDifference} \log | {\bf F}_{k|k;i}^{\rm Total} ( {\pmb \xi}_k^{\rm all} ) | - \log | {\bf F}_{k|k-1;i}^{\rm Total} |. \end{equation} With regard to these quantities, observe that the post-action Fisher information ${\bf F}_{k|k;i}^{\rm Total}( {\pmb \xi}_k^{\rm all})$ is random. It is random since it depends on knowing which agents will detect target $i$ after all actions are executed at time step $k$. The post-action Fisher information in turn depends on the unknown positions of the targets and each agent's imperfect detection capability. Any loss function depending on ${\bf F}_{k|k;i}^{\rm Total} ({\pmb \xi}_k^{\rm all})$ will thus be stochastic. The loss function each agent hopes to minimize at time $k$ will be denoted as $L_k \left( {{\pmb \xi}}_k^{\rm all} \right)$. This loss function is defined as the negative of the total information gain written in (\ref{eqn:InfoDifference}), summed over the total number of targets, $T$. \begin{equation} L_k({\pmb \xi}_k^{\rm all})= - \sum_{i=1}^T \left( \log \left| {\bf F}_{k|k;i}^{\rm Total} ({\pmb \xi}_k^{\rm all}) \right| - \log \left| {\bf F}_{k|k-1;i}^{\rm Total} \right| \right). \label{eqn:TrueLoss} \end{equation} The total information gain resulting from the actions ${\pmb \xi}_k^{\rm all}$ cannot be known in advance of (i) all of the agents carrying out their respective actions, (ii) all targets moving (randomly) over the time step interval, and (iii) all agent sensors imperfectly detecting and measuring targets. The agents must thus minimize $L_k$ while only being able to calculate estimated and stochastic values of the loss function. To execute the optimization within their respective DECIDE steps, each agent needs to predict the loss function. Each agent must therefore first predict the post-action Fisher information, ${\bf F}_{k|k;i}^{\rm Total}({\pmb \xi}_k^{\rm all}).$ It does this by replacing ${\pmb \xi}_k^{\rm all}$ with its predicted values of these components. It is specifically using its knowledge of the other agents' positions, orientations, and FIMs (communicated to it at time $k-1$) to arrive at a sensible guess of what actions the other agents will take at time $k$. With this prediction, each agent will have a prediction of the post-action Fisher information. The post-action Fisher information of target $i$ predicted by agent $j$ as a function of agent $j$'s actions at time $k$ will be denoted as ${\hat {\bf F}}_{k|k;i;j}^{\rm Total} \left( {\pmb \xi}_{k;j} \right),$ and this will be calculated as $${\hat {\bf F}}_{k|k;i;j}^{\rm Total} \left( {\pmb \xi}_{k;j} \right) = {\bf F}_{k|k;i}^{\rm Total} \left. \left( {\pmb \xi}_k^{\rm all} \right) \right|_{{\pmb \xi}_{k}^{{\rm all}\backslash j} = {\hat {\pmb \xi}}_{k;j}^{{\rm all}\backslash j}},$$ where ${\pmb \xi}_{k}^{{\rm all} \backslash j} = \left( {\pmb \xi}_{k;1}, \ldots, {\pmb \xi}_{k;j-1}, {\pmb \xi}_{k;j+1}, \ldots, {\pmb \xi}_{k;A} \right)$, ${\hat {\pmb \xi}}_{k;j}^{{\rm all} \backslash j} = \left( { {\pmb \xi}}_{k;1;j}, \ldots, { {\pmb \xi}}_{k;j-1;j}, {\hat {\pmb \xi}}_{k;j+1;j}, \ldots, {\hat {\pmb \xi}}_{k;A;j} \right)$, and ${\hat {\pmb \xi}}_{k;l;j}$ is the action agent $j$ predicts of agent $l$ at time $k$ . A more detailed formula for ${\hat {\bf F}}^{\rm Total}_{k|k;i;j}$ is given below in (\ref{eqn:EstimatedFHat}). \begin{eqnarray} \nonumber \lefteqn{ {\hat{\bf F}}_{k|k;i;j}^{\rm Total} \left( {\pmb \xi}_{k;j} \right) } \\ \label{eqn:EstimatedFHat} & = & {\bf F}_{k|k-1;i;j} + \\ \nonumber & & {\hat {\pi}}^d_{k;i;j} \left( {\pmb \xi}_{k;j} \right) ~ \left[ {\hat {\bf H}}_{k; i;j} \left( {\pmb \xi}_{k;j} \right) \right]^T {\bf R}^{-1} {\hat {\bf H}}_{k; i;j} \left( {\pmb \xi}_{k;j} \right) + \\ \nonumber & & + \sum_{l=1; l \neq j}^A \left \{ {\bf F}_{k|k-1;i;l} {\mathbbm 1} \left( C_{k-1;l;j} = 1 \right) + {\hat \pi}^d_{k;i,l;j} \left( {\hat {\pmb \xi}}_{k;l;j} \right) \right. \\ \nonumber & & \times \left. \left[ {\hat {\bf H}}_{k; i;l; j} \left( {\hat {\pmb \xi}}_{k;l;j} \right) \right]^T {\bf R}^{-1} {\hat {\bf H}}_{k; i;l;j} \left( {\hat {\pmb \xi}}_{k;l; j} \right) \right \}, \end{eqnarray} where $C_{k-1;l;j}$ is 1 if agents $l$ and $j$ communicate at time $k-1$ and 0 otherwise, ${\hat \pi}^d_{k;i;l;j} \left( {\hat {\pmb \xi}}_{k;l;j} \right)$ is the probability that agent $l$ detects target $i$, as predicted by agent $j$, and the matrix $\hat{\bf{H}}_{k;i;l;j}( {\hat {\pmb{\xi}}}_{k;l;j})$ is the measurement sensitivity Jacobian computed by agent $j$ using its predicted positions of agent $l$ and target $i$. Note that the first two terms on the right-side of the equality in (\ref{eqn:EstimatedFHat}) measure agent $j$'s contribution to the FIM of target $i$. The first term is agent $j'$s pre-action Fisher and the second is the additional information resulting from action ${\pmb \xi}_{k;j}$. The last two terms on the right of (\ref{eqn:EstimatedFHat}) estimate the other agents' contribution to the Fisher of target $i$ (as predicted by agent $j$). The second-to-last term is agent $l$'s pre-action Fisher on target $i$ and the fourth is the additional information on target $i$ resulting from agent $l$ taking the action agent $j$ would expect it to. We would like to remind the reader, again, that this estimate of the post-action Fisher assumes independence among the measurements. With the estimated FIM calculated as it is in (\ref{eqn:EstimatedFHat}), agent $j$ calculates a predicted post-action loss value by summing the information losses over all of the targets. This predicted post-action loss of agent $j$'s is denoted as ${\hat L}_{k;j} \left( {\pmb \xi}_{k;j} \right)$ and is calculated as \begin{equation} \hat{L}_{k;j} \left( {\pmb \xi}_{k;j} \right) = - \sum_{i=1}^T \left( \log \left| \hat{{\bf F}}_{k|k;i;j}^{\rm Total} \left( {\pmb \xi}_{k;j} \right) \right| - \log | {\bf F}_{k|k-1;i}^{\rm Total} | \right). \label{eqn:biased_Lhat} \end{equation} Recall this is an approximation to the actual loss. The value of $\hat{L}_{k;j}$ can be thought of as $L_k$ conditioned on agent $j$'s predicted positions of all targets and agents. Hernandez (Ref. \cite{Hernandez}) gives the conditions on Eqn. (\ref{eqn:biased_Lhat}) which guarantee convergence of the CSO when trying to minimize such a function. These conditions do not necessarily apply and can be severely relaxed in our situation, however. If each agent were iteratively making multiple moves to minimize one stochastically measured loss function, the conditions on Eqn. (\ref{eqn:biased_Lhat}) given in Ref. \cite{Hernandez} would apply. This is not the case, however. Recall that at each time step, each agent only has the time to make one move (not several moves), and all that is necessary is that this move sufficiently goes in the right direction towards minimizing the loss function. Before we discuss how the loss function at each time step is minimized, it is important that we mention that ${\hat L}_{k;j}$ is a biased predictor of $L_k$. The estimated loss and/or its gradient must be an unbiased predictor of the true (unknown) loss or gradient (see Ref. \cite{Spall_Book}, Chaps. 4--7) for classic stochastic optimization results to hold. If the probability distributions of $L_k$ and ${\hat L}_{k;j}$ are the same, then $ {\mathbbm E} \left( L_k - {\hat L}_{k;j} \right) = 0$, making ${\hat L}_{k;j}$ unbiased. We discuss an approximate resolution to this issue below. Note that the only distinction between $L_k$ and $\hat{L}_{k;j}$ is the different form for the updated Fisher information. For $L_k$, we use ${\boldsymbol{F}}_{k\vert k;i}^{\rm Total} (\boldsymbol{\xi }_k)$, while for $\hat{L}_{k;j}$, we use ${\hat{\boldsymbol{F}}}_{k\vert k;i;j}^{\rm Total} $. The probability distributions of $L_k$ and $\hat{L}_k$ will therefore be identical if the distributions of ${\boldsymbol{F}}_{k\vert k;i}^{\rm Total} (\boldsymbol{\xi }_k)$ and ${\hat{\boldsymbol{F}}}_{k\vert k;i;j}^{\rm Total} ({\hat{\boldsymbol{\xi}}}_k)$ are identical. We now describe a method by which we attempt to mitigate the bias issue. We first discuss the method in the idealized case of a linear state-space model with Gaussian randomness. We then offer comments relative to our more practical nonlinear setting. From standard orthogonality properties and notation of the generic Kalman filter, it is known that with linear state-space models and Gaussian randomness, the one-step ahead prediction ${\hat{\boldsymbol{x}}}_{k\vert {k-1}}$ is independent of the estimation error $ {\boldsymbol \epsilon}_{k|k-1} = {\boldsymbol{x}}_{k}-{\hat{\boldsymbol{x}}}_{k\vert {k-1}}$. The standard one-step-ahead error-covariance matrix calculated in the Kalman filter, ${\bf P}_{k|k-1}$, is the covariance of this estimation error, i.e., \begin{equation} \label{epsDstn} {\boldsymbol \epsilon}_{k|k-1} \sim N \left( {\bf 0}, {\bf P}_{k|k-1} \right). \end{equation} And with the distribution given in (\ref{epsDstn}), one can create a simulated true state by adding a simulated value of ${\boldsymbol{\epsilon}}_k$ to the prediction, ${\hat{\boldsymbol{x}}}_{k\vert {k-1}}$. In the case of the linear state-space model with Gaussian errors, this simulated true state has a distribution identical to the unknown true state, ${\bf x}_k$. In the context of the problem discussed here, we let ${\bf x}_{k|k-1;i;j}$ be agent $j$'s simulated true state of target $i$ at time step $k$. That is, each of these will be states formed by adding the above-mentioned Monte Carlo randomness to the corresponding one-step ahead filter estimates. To state this mathematically, \begin{equation}\label{eqn:MC_adjstmnt} {\bf x}_{k|k-1;i;j} = {\hat {\bf x}}_{k|k-1;i;j} + {{\boldsymbol \epsilon}}_{k|k-1;i;j}, \end{equation} where ${\boldsymbol \epsilon}_{k|k-1;i;j} \sim N \left( {\bf 0}_{6 \times 1}, {\bf P}_{k|k-1;i;j} \right).$ Although the adjustment in (\ref{eqn:MC_adjstmnt}) makes ${\mathbbm E} \left( L_k- \hat{L}_{k;j} \right)$ = 0 when the state-space model is fully linear, the actual case of interest here involves a nonlinear measurement equation. The Monte Carlo adjustment to produce a simulated true state is thus an approximation that is valid to the extent that the EKF acts like a standard Kalman filter. Now that each agent can estimate a loss function, it can decide (in its DECIDE step) which heading to take and how to vertically displace itself at time $k$. As mentioned earlier, this involves agent $j$ minimizing ${\hat L}_{k;j} \left( {\pmb \xi}_{k;j} \right)$ with respect to $\gamma_{k;j}$ and $y^U_{k;j}$. Agent $j$ selects its heading and vertical displacement at time $k$ by taking the stochastic gradient of ${\hat L}_{k;j} $ with respect to $\gamma_{k;j}$ and $y^U_{k;j}$, respectively. The heading and vertical displacement agent $j$ select at time $k$ are calculated as \begin{eqnarray} \label{eqn:gammaDeriv} \gamma_{k;j} & = & \gamma_{k-1;j} - a_k \left. {\frac{ \partial {\hat L}_{k;j} \left( \gamma,~y^U \right)}{\partial \gamma}} \right|_{\gamma = {\gamma_{k-1;j}}, y^U = y^U_{k-1;j}}, \\ \nonumber {\rm and} & & \\ \label{eqn:uDeriv} y^U_{k;j} & = & y^U _{k-1;j} - b_k \left. {\frac{ \partial {\hat L}_{k;j} \left( \gamma,~y^U \right)}{\partial y^U}} \right|_{\gamma = {\gamma_{k;j}}, y^U = y^U_{k-1;j}}, \end{eqnarray} where $a_k$ and $b_k$ are predefined sequences of numbers selected by the user. This is done iteratively (using the seesaw method), until some convergence threshold or fixed maximum number of iterations is reached. The details of the seesaw method are given in the next section, and the actual calculations for the derivatives in (\ref{eqn:gammaDeriv}) and (\ref{eqn:uDeriv}) are given in Sections \ref{sctn:Appendix_H} - \ref{sctn:Appendix_uDeriv} of the Appendix. \begin{comment} An agent's optimization of its motion is subject to a number of constraints, primarily consisting of physical motion limits, Bayesian update laws, data available via target detections governed by sensor detection range (and therefore by spatial configuration of agents relative to targets), and data available from peer agents governed by communications range (and therefore by spatial configuration of agents). The evaluation of the loss in the DECIDE step requires predicting target and agent states and uncertainties forward in time. These prediction steps are separate from the time predict steps executed by the Bayesian filter in the INFER step, and in general, may use lower fidelity models to reduce computational complexity since they are applied a very large number of times within a combinatorial optimization. We assume that the agents apply Bayesian updating to incorporate new information into local state estimates. Therefore, with $\hat{X}^{(j)}_{k}$ representing agent $j$'s knowledge of $X$ (e.g., a vector of target positions, own position, and other agent positions) at time step $k$, $Z^{(j)}_{1:k}$ representing agent $j$'s aggregated data from sensor measurements and communications from other agents for all previous and current time steps, and $P^{(j)}_{k}(\hat{X}^{(j)}_{k}|Z^{(j)}_{1:k})$ representing agent $j$'s probability or belief density of the state given the available information, we have \begin{equation} P^{(j)}_{k}(\hat{X}^{(j)}_{k}|Z^{(j)}_{1:k}) = K P^{(j)}_{k}(\hat{X}^{(j)}_{k}|Z^{(j)}_{1:k}) P^{(j)}_{k}(\hat{X}^{(j)}_{k-1}) \end{equation} where $ P^{(j)}_{k}(\hat{X}^{(j)}_{k})$ represents a likelihood function defined in the standard way and $K$ denotes a normalizing constant. We note that the available information $Z^{(j)}_{1:k}$ may contain contributions from other agents’ local state estimates. The Bayesian recursion above provides the basis for computing the updated estimate that is needed in carrying out the improvement (or optimization) process at iteration $k+1$. We further assume that, in the general case, the agents determine control actions by approximately optimizing a partially observable Markov decision process (POMDP) (Bellman1957, Puterman2005; Powell2011) over multiple time steps. The recursion to solve a POMDP computes a sequence of loss functions that converge toward the optimum (solution of Bellman’s equation). The recursion has two steps, traditionally referred to as value update and policy update. Both of the value update and the policy update steps in standard POMDP require evaluation of the loss function $L$. Even when $L$ is known, the value and policy recursions over infinite or long time horizons are computationally intractable in general. Moreover, we have only a noisy value of $L$ in the stochastic setting. A goal, therefore, is to use decentralization to help break the curse of dimensionality and to use techniques that produce feasible control policies that are stochastically convergent ($k \to \infty$) and reasonable approximations to the optimum in a finite number of iterations (finite $k$). It is acceptable for agents to compute approximate or suboptimal solutions, but there should be a means by which the degree of approximation or sub-optimality can be quantified. For the simulations presented in this paper, we simplify by optimizing only over a single action, which reduces the POMDP to a standard optimization. \end{comment} \section{Cyclic Stochastic Optimization and the Seesaw Method} \label{sec:cso-seesaw} When the number of parameters is large, the problem of jointly minimizing a loss function with respect to multiple parameters can incur excessively high computational cost. This computational cost can be reduced, however, using conditional optimization methods. In such methods, the loss function is minimized with respect to a subset of the parameters while the rest of the parameters are held fixed. Cyclic optimization seeks to combine algorithms for performing conditional optimization with the hopes of obtaining a solution to the joint optimization problem \cite{Spall}. A specific case of cyclic optimization is CSO, which applies when the loss function to be minimized is random or measured with error. The CSO technique employed in this project is the seesaw method. In the seesaw method, each agent selects an action in an attempt to minimize its contribution to the loss function. The agent does this given knowledge (possibly imperfect knowledge) of other agents. Before attempting to minimize the loss function, however, each agent iteratively incorporates the other agents’ information and decisions. A desired feature of any algorithm we use is that each agents' local estimates and control actions converge to the global optimum. This convergence should occur under reasonable conditions, and these conditions are usually related to how well the agents communicate. Two desirable aspects of the seesaw method are: (i) it is a hybrid technique that can operate in either a centralized or decentralized mode, and (ii) the formal structure lends itself to rigorous empirical and theoretical analysis. The seesaw method specifically divides the entire parameter (or decision) vector into at least two subvectors. Each subvector corresponds to the parameters/decisions associated with one of the agents. As an example, consider a special case where two agents cooperate to minimize a loss function. In this example we will assume this loss does not depend on time (and will thus not be indexed by $k$). We will write this loss function as $L$, and $L$ will depend on the decisions of the two agents, ${\pmb \beta}^{\rm all}$, where $${\pmb \beta}^{\rm all} = \left( {\pmb \beta}_1^T, {\pmb \beta}_2^T \right)^T,$$ and ${\pmb \beta}_j$ is the decision vector associated with agent $j$. Mathematically we write the loss function as $$L = L \left( {\pmb \beta}^{\rm all} \right).$$ In the seesaw process, iteration by iteration, subvector ${\pmb \beta}_1$ is improved (possibly optimized) conditioned on the most recent value of ${\pmb \beta}_2$ and, likewise, ${\pmb \beta}_2$ is improved (possibly optimized) based on the most recent value of $ {\pmb \beta}_1$. The estimate at the very end of seesaw iteration $t$ thus has the form $$\hat{\pmb \beta}^{{\rm all,~ssaw}_t} \equiv \left[ \left( \hat{\pmb \beta}_1^{{\rm ssaw}_t} \right)^T ~ \left( \hat{\pmb \beta}_2^{{\rm ssaw}_t} \right)^T \right]^{T},$$ with ${\hat{\pmb \beta}}_1^{{\rm ssaw}_t}$ a function of $\hat{\pmb \beta}_1^{{\rm ssaw}_{t-1}}$ and $\hat{\pmb \beta}_2^{{\rm ssaw}_{t-1}}$, and $\hat{\pmb \beta}_2^{{\rm ssaw}_t}$ a function of $\hat{\pmb \beta}_2^{{\rm ssaw}_{t-1}}$ and $\hat{\pmb \beta}_1^{{\rm ssaw}_t}$. While this scheme allows for the localized (decentralized) optimization of each subvector, it does not allow for the optimization of the overall decision vector ${\pmb \beta}$. This is not always true when the loss function is not stochastic. The above ideas apply directly to an $M$-agent process, where $M > 2$. In the case of $M$ agents, suppose that $${\pmb \beta}^{\rm all} = \left[ {\pmb \beta}_1^T,~{\pmb \beta}_2^T,~{\pmb \beta}_3^T,~\cdots~{\pmb \beta}_M^T \right]^T,$$ where ${\pmb \beta}_1, {\pmb \beta}_2, \ldots, {\pmb \beta}_M$ are subevectors, each subvector corresponding to one agent's decision variables, and each processed in the exact same sequential manner as the two-stage algorithm described above. That is, the vectors are processed sequentially such that \begin{equation} \begin{aligned} L(\hat{\pmb \beta}^{{\rm all,~ ssaw}_{t+1}}) & \leq \ldots \\ & \leq L(\hat{\pmb \beta}_1^{{\rm ssaw}_{t+1}}, \hat{\pmb \beta}_2^{{\rm ssaw}_{t+1}}, \hat{\pmb \beta}_3^{{\rm ssaw}_t}, \ldots, \hat{\pmb \beta}_M^{{\rm ssaw}_n}) \\ & \leq L(\hat{\pmb \beta}_1^{{\rm ssaw}_{t+1}}, \hat{\pmb \beta}_2^{{\rm ssaw}_t}, \ldots, \hat{\pmb \beta}_M^{{\rm ssaw}_t}) \\ & \leq L(\hat{\pmb \beta}^{{\rm all,~ssaw}_t}) \end{aligned} \end{equation} subject to $\hat{\pmb \beta}^{{\rm all,~ssaw}_{t+1}} \neq \hat{\pmb \beta}^{{\rm ssaw}_t}$ only if $L(\hat{\pmb \beta}^{{\rm all,~ ssaw}_{t+1}}) < L(\hat{\pmb \beta}^{{\rm ssaw}_t})$. Because of the imperfect information each agent has about the entire system, the seesaw process we employ in this problem has to work with a stochastic loss function. In particular, each agent will have a “noisy” estimate of the global loss $L$. This noisy estimate of $L$ can be generically written as ${\hat L} \left( {\pmb \beta}^{\rm all} \right)$, where \begin{equation} \hat{L}({\pmb \beta}^{\rm all}) \equiv L({\pmb \beta}^{\rm all}) + \varepsilon({\pmb \beta}^{\rm all}) \label{eqn:GenericLHat} \end{equation} and $\varepsilon({\pmb \beta}^{\rm all})$ represents the error due to random quantities such as imperfect state estimates. At each iteration of the seesaw process, each agent selects an action (a value of ${\pmb \beta}_j$) in an attempt to minimize its contribution to $\hat{L}({\pmb \beta}^{\rm all})$. The overall aim is to minimize the unknown (ideal) loss $L$ while only using information that is associated with the available $\hat{L}$. In our surveillance problem, the true loss in (\ref{eqn:TrueLoss}) and the noisy loss in (\ref{eqn:biased_Lhat}) play the role of $L$ and ${\hat L}$, respectively, in (\ref{eqn:GenericLHat}). At each iteration of the process, the contribution of each agent may only be improved, versus being optimized. Ref.~\cite{Spall} shows that convergence to a centralized solution is possible with improvement at the per-agent level. In fact, convergence is guaranteed if, at each iteration, only one of the $M$ agents improves a sufficient amount. In the simulations, the agents execute the seesaw within the DECIDE step at time $k$ as follows: the agents alternately choose an action by trying to minimize their respective loss functions using their respective current estimates of target states and their predicted actions of peer agents they have yet (or failed) to communicate with. Each agent predicts each target to move with the same heading and speed as estimated in the previous time step, and each peer agent it has not communicated with is projected to move in the same direction and speed it did in the previous time step. The seesaw process continues for a prescribed number of iterations, at which point the final decisions are executed. The process is then repeated for each time step $k$. We investigated the performance of our proposed CSO algorithm with simulation studies. These simulation studies are described in the next section. \begin{comment} A major focus in this research is to extend seesaw to properly account for noisy loss measurements. That is, we must create and analyze a stochastic seesaw process that is implementable in real-world problems of naval resource allocation while having formal performance guarantees to ensure convergence and a quantification of error due to both decentralization and stochastic effects. A stochastic gradient method (e.g., Spall, 2003a, Chap. 5) is expected to form the basis of the improvement process at each iteration. Subsection 3.2 provides comments on how the state estimation can be carried out via Bayesian recursions. The state estimation will contribute towards the stochastic gradient used in the update step for each agent at each iteration of the seesaw process. Typically, THETA has components representing both continuous and discrete parameters or variables that are to be optimized. Further, given the complexity of the overall system, there may be no simple equations that express the relationship between the alternatives (e.g., sensor actions) and the Navy’s ability to achieve the mission objectives in surveillance. Hence, carefully chosen runs of Monte Carlo simulations (with a simulation that has passed appropriate tests of validity) may be used in concert with stochastic gradient and sequential decision methods to determine optimal choices of operational factors. Computationally powerful and theoretically sound methods exist for such simulation-based optimization and estimation (e.g., Fu, 2011; Spall, 2003a, Chaps. 14−15; Spall, 2003b). Most stochastic optimization methods for handling noisy function measurements are designed for continuous problems, but there exist some methods for discrete problems (e.g., Andradóttir, 1995; Hannah and Powell, 2010; Li et al., 2009; Spall, 2003a, Chap. 12; and Wang and Spall, 2011). It is expected that simulations will play a role in solving the decision problems of the next two subsections, as well. In turn, the results from the sequential decision problems will go into the stochastic gradient expressions used in update steps within seesaw. A key part of the research will be to explore these connections. Spall gives a set of convergence conditions for a cyclic version of stochastic gradient and simultaneous perturbation stochastic approximation. A numerical experiment is performed to analyze the behavior of cyclic vs. non-cyclic stochastic optimization on the Rosenbrock function with Gaussian noise. The cyclic (or alternating or block coordinate) approach to optimization and identification has been used in a number of control applications. In such problems, the full parameter vector to be optimized is divided into two or more subvectors and the optimization process proceeds by sequentially optimizing the criterion of interest with respect to each of the subvectors while holding the other subvectors fixed. In most such applications, the method of solution is based on deterministic optimization methods such as steepest descent. While deterministic algorithms are acceptable in some applications in identification and control, they are not valid when considering stochastic optimization problems with only noisy measurements of the loss function and/or the gradient of the loss. This paper considers the use of cyclic methods in stochastic optimization problems. In particular, we consider the cyclic extension of stochastic approximation (SA) in both the stochastic gradient and simultaneous perturbation SA (SPSA) cases. cases where cyclic methods have been used. In particular, one critical limitation in many practical applications is the fact that we will not know the loss function $L(\boldsymbol{\uptheta})$ exactly for any given value of the parameters to be optimized, $\boldsymbol{\uptheta}$. Rather, the values (``measurements'') of $L$, and its gradients, will only be available with noise. This, of course, is the classical setting of stochastic approximation. For example in some multi-agent problems, there will be uncertainty in what each agent (analogous to a subvector) knows about the full system, as reflected in $L$. (Note that use of a standard optimization method, such as steepest descent, simulated annealing, or a genetic algorithm, without properly treating noise can lead to non-convergent and highly suboptimal solutions; e.g., Spall, 2003, pp. 9, 26, 50--55, 214--216, and 248--249.) Because of the noise in the $L$ evaluations, ``standard'' cyclic methods, as applied to the deterministic optimization setting, do not directly apply. Hence, this paper presents methodology and theory related to the use of cyclic optimization in the stochastic setting. We are concerned with the minimization of a real-valued and differentiable loss function $L(\bm\uptheta)$ when only noisy measurements are available. In particular, one may obtain instantaneous observations of a random variable: $Q(\bm\uptheta,V)$ where: \begin{align} \label{eq:oneone} E[Q(\bm\uptheta,V)]=L(\bm\uptheta), \end{align} \noindent this can be rewritten as: \[ Q(\bm\uptheta,V)=L(\bm\uptheta)+\upvarepsilon(\bm\uptheta,V). \] \noindent Finally, $\bf{\theta}=\mathbb{R}^{p}$ and $\Lambda$ will be the domains of $\bm\uptheta$ and $V$ respectively. In our focus on cyclic optimization, $\bm\uptheta$ will be represented in terms of two subvectors: \[ \bm\uptheta=\left[\begin{array}{c}\bm{\uptheta}^{(1)} \\\bm{\uptheta}^{(2)}\end{array}\right]\in \mathbb{R}^{p}, \] \noindent where the subvector $\bm{{{{\uptheta}}}}^{(1)}$ has length $p'<p$. The idea is to update each subvector individually while holding the other fixed. One would then proceed to repeat this process until a certain stopping criterion has been satisfied. When $\bm\uptheta$ is divided into two subvectors we will refer to this as cyclic seesaw optimization; considering more than two subvectors of $\bm\uptheta$ is a simple extension and will not be discussed here. A formal definition of the cyclic seesaw algorithm is presented next. For simplicity, we introduce the following notation: ${\bm{g(\bm\uptheta)}}\equiv\partial L(\bm\uptheta)/\partial \bm\uptheta$ and the vectors ${\bm{g}}^{(1)}(\bm\uptheta)$ and ${\bm{g}}^{(2)}(\bm\uptheta)$ result from replacing the last $p-p'$ coordinates or the first $p$ coordinates of ${\bm{g(\bm\uptheta)}}$ with zeros, respectively. We now introduce the general cyclic seesaw algorithm. For an given $\bm{{\hat{\uptheta}}}_{k}$, the following recursion defines the cyclic seesaw algorithm: \begin{equation} \label{eq:biased1} \begin{split} \bm{{\hat{\uptheta}}}_{k}^{(I)}&\equiv\bm{{\hat{\uptheta}}}_{k}-a_{k}^{(1)}\left({\bm{g}}^{(1)}(\bm{{\hat{\uptheta}}}_{k})+{\bm{\upbeta}}_{k}^{(1)}+{\bm{\upxi}}_{k}^{(1)}\right),\\ \bm{{\hat{\uptheta}}_{\ell+1}}&\equiv\bm{{\hat{\uptheta}}}_{k}^{(I)}-a_{k}^{(2)}\left({\bm{g}}^{(2)}(\bm{{\hat{\uptheta}}}_{k}^{(I)})+{\bm{\upbeta}_{k}^{(2)}}+{\bm{\upxi}_{k}^{(2)}}\right); \end{split} \end{equation} \noindent here $\{a_{k}^{(1)}\}$ and $\{a_{k}^{(2)}\}$ are sequences of positive scalars, $\bm{\upbeta}_{k}^{(j)}$ is a deterministic vector (referred to as the bias term) and $\bm{\upxi}_{k}^{(j)}$ is a random vector for $j=1,2$. In the following section we give convergence conditions for this cyclic algorithm.\newline \end{comment} \section{Simulation Studies} \label{sec:simulations} To test whether the cyclic stochastic optimization algorithm we propose in this paper is effective, we conducted several simulation studies. In the first simulation study, we considered two agents and two targets. In the second and third study, we considered three agents and two targets. In the fourth simulation study, we show how two groups of two agents simultaneously track two targets (note that these two groups of agents are independent of one another, and no communication takes place between the two groups), and in the fifth study, two groups of four agents independently and simultaneously track four targets. The trajectory of the agents and targets in these simulations are shown in Figures \ref{fig:Simulation1_part1} - \ref{fig:Simulation5_part2}. A small number of agents were selected for these five simulation studies so that the reader can get a clear understanding of how our algorithm performs. Visually inspecting the trajectories of more than eight agents is difficult to do. In our final studies, however, we do examine the performance of our algorithm when many agents (many more than four) are tracking a set of targets. In each simulation, the starting location of both the agents and the targets was random (each location was uniformly drawn within an 8 $\times$ 8 $\times$ 8 cube centered at the origin). The motion of the targets throughout each simulation was random and meant to mimic Brownian motion. At each time point during a simulation, each target randomly selected a heading (uniformly between $0$ and $2 \pi$) and then moved .1 units of distance in that direction. Each target also selected a vertical displacement at each time point. This was randomly drawn from a uniform distribution on [-.15, .15]. This motion of the targets, however, is a significant departure from their motion as assumed by the agents.\footnote{As mentioned in the introduction, the setting of this problem is deliberately generic. If the unmanned agents were drones, which have a maximum speed of approximately 65mph $\approx$ 10ft/.1sec = 30ft/.3sec, the units of distance could be 100 feet and the time units could be one second, or the units of distance could be 300 feet and the time units could be 3 seconds. If the agents were undersea vehicles, which travel at a maximum speed of over 15 knots (approximately 20mph $ \approx $ 10 yards/sec = 20 yards/2sec), the units of distance could be 100 yards and the units of time 10 seconds, or the units of distance could be 200 yards yards and the units of time could be 20 seconds.} As stated in Section \ref{sec:EKF}, the agents assumed the targets followed the motion model of ${\bf x}_{k;i} = \Phi {\bf x}_{k-1;i} + {\bf w}_k$, where $\Phi$ is given in (\ref{eqn:PhiMatrix}), $ \Delta t = .1, $ and ${\bf w}_k \sim N \left( {\bf 0}_{6 \times 1}, {\bf Q} \right)$ with ${\bf Q} = {\rm diag} \left( .03, .03, .03, .01, .01, .01 \right).$ The probability of detection, $\pi^d$, decays with the distance between agent and target according to the function given in (\ref{eqn:piEqn}) \begin{eqnarray} \label{eqn:piEqn} \pi^d_{k;i;j} & = & \exp \left \{ - \left[ \left( \Delta_{k;i;j}^E \right)^2 + \left( \Delta_{k;i;i}^N \right)^2 \right. \right. \nonumber \\ & & ~~~~~~~~~~~+ \left. \left. \left. \left( \Delta_{k;i;i}^U \right)^2 \right] \right/100 \right \}. \end{eqnarray} The probability agent $j$ successfully communicates with agent $l$ at time $k$ is calculated as \begin{eqnarray} \nonumber \rho_{k;j \rightarrow l} &= & \exp \left \{ - \left. \left[ \left( y_{k;j}^E - y_{k;l}^E \right)^2 + \left( y_{k;j}^N - y_{k;l}^N \right)^2 \right. \right. \right. \\ & & \left. \left. \left. ~~~~~~~~~~+ \left( y_{k;j}^U - y_{k;l}^U \right)^2 \right] \right/200 \right \}. \label{eqn:communic_Prob} \end{eqnarray} We select this communication probability to illustrate that our methodology is robust to non-ideal communications. The communications are non-ideal since, at a specific distance, the probability of two agents successfully communicating is only slightly larger than the probability of an agent detecting an adversarial vehicle. This is shown in Figure \ref{fig:ProbDtctAndCmnct}. In Section \ref{sctn:CmnctProb} of the Appendix, we illustrate how the algorithm would perform with more reliable communications. { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 2cm, scale = 0.45]{ProbDetectionAndCommunication.pdf}} \caption{The probability of detection, $\pi^d_{k;i;j},$ and the probability of communication, $\rho_{k;j\rightarrow l}(200),$ as a function of distance.} \label{fig:ProbDtctAndCmnct} \end{center} \end{figure} } The values of $\sigma_{\theta}$, $\sigma_{\phi}$, and $\sigma_r$ are all .01, and the step-sizes in the stochastic gradient calculation, $a_k$ and $b_k$, were set to 1 and 0.1, respectively, for all values of $k$. Images of the first five simulation studies are given in Figures \ref{fig:Simulation1_part1} - \ref{fig:Simulation5_part2}. The paths of both targets are given in different shades of black (in the North-East plots their starting positions are circles and their final positions are squares), and the trajectories of the agents are given in red, blue, and green. Just as with the agents, in the North-East plots their starting positions are circles and their final positions are squares. { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 2cm, scale = 0.45]{North_vs_East_plot_seed11423.pdf}} \caption{The North-East motion of two targets and two agents across time (1500 time points). } \label{fig:Simulation1_part1} \end{center} \end{figure} } { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 7cm, scale = 0.45]{Up_vs_Time_plot_seed11423.pdf}} \caption{The vertical motion of two targets and two agents across time (1500 time points).} \label{fig:Simulation1_part2} \end{center} \end{figure} } { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 2cm, scale = 0.45]{North_vs_East_plot_seed17568_ver2.pdf}} \caption{The North-East motion of two targets and three agents across time (2000 time points). } \label{fig:Simulation2_part1} \end{center} \end{figure} } { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 7cm, scale = 0.45]{Up_vs_Time_plot_seed17568_ver2.pdf}} \caption{The vertical motion of two targets and three agents across time (2000 time points).} \label{fig:Simulation2_part2} \end{center} \end{figure} } { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 2cm, scale = 0.45]{North_vs_East_plot_seed17510.pdf}} \caption{The North-East motion of two targets and three agents across time (1500 time points). } \label{fig:Simulation3_part1} \end{center} \end{figure} } { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 7cm, scale = 0.45]{Up_vs_Time_plot_seed17510.pdf}} \caption{The vertical motion of two targets and three agents across time (1500 time points).} \label{fig:Simulation3_part2} \end{center} \end{figure} } { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 2cm, scale = 0.45]{North_vs_East_plot_seed7567.pdf}} \caption{The North-East motion of two targets and two groups of two agents across time (1500 time points). } \label{fig:Simulation4_part1} \end{center} \end{figure} } { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 7cm, scale = 0.45]{Up_vs_Time_plot_seed7567.pdf}} \caption{The vertical motion of two targets and two groups of two agents across time (1500 time points).} \label{fig:Simulation4_part2} \end{center} \end{figure} } { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 2cm, scale = 0.45]{North_vs_East_plot_seed13522.pdf}} \caption{The North-East motion of four targets and two groups of four agents across time (1500 time points). } \label{fig:Simulation5_part1} \end{center} \end{figure} } { \begin{figure}[h] \begin{center} {\includegraphics[trim = 1cm 7cm 1cm 7cm, scale = 0.45]{Up_vs_Time_plot_seed13522.pdf}} \caption{The vertical motion of four targets and two groups of four agents across time (1500 time points).} \label{fig:Simulation5_part2} \end{center} \end{figure} } Figures \ref{fig:Simulation1_part1} - \ref{fig:Simulation1_part2} show the results of the first simulation. In these figures it is clear that the agents effectively track and go in the direction of the targets. The red agent loops around the other vehicles to eventually track the black target which is moving west. The blue agent travels northeast to track the grey target. These agents seem to stick with the targets they are following vertically as time progresses as well. In Figure \ref{fig:Simulation2_part1} - \ref{fig:Simulation2_part2} we have three agents and two targets. Observe how the green agent starts at roughly the same vertical position as the grey target and travels southwest to track it, while the blue agent starts at roughly the same vertical position as the black target and travels northeast to track it. Also observe that the red agent departs and circles the scene; since both targets have been tracked by the other agents, any additional information the red agent will gain by moving closer to the any of the two targets is negligible. The red agent thus keeps its distance. This same story is told in Figures \ref{fig:Simulation3_part1} and \ref{fig:Simulation3_part2}; in this case the green agent departs and circles the scene. In Figures \ref{fig:Simulation4_part1} - \ref{fig:Simulation4_part2}, we see what happens when two groups of two agents independently and simultaneously track two targets. One group of agents is in red and the other is in blue. In this case, the phenomenon observed in Figures \ref{fig:Simulation2_part1} - \ref{fig:Simulation2_part2} and Figures \ref{fig:Simulation3_part1} - \ref{fig:Simulation3_part2} (one agent departing and circling around the other vehicles) does not occur. This is because the agents that are following the same target are operating independently and not communicating with one another. Each target is thus very closely followed by two agents. The same story is told in Figures \ref{fig:Simulation5_part1} - \ref{fig:Simulation5_part2} which illustrate our fifth simulation study. In this case, two groups of four agents (a total of eight agents) independently and simultaneously track four targets. Another set of simulation studies were done to uncover the average behavior of multiple agents against a set of targets. One hundred simulations were done in each study, and the median minimum distance to an agent from each target was calculated at each time point. We denote this distance at time $k$ as $m_k$. The results in Figure \ref{fig:medianDist_T2} are when $T$, the total number of targets, is 2, and the result in Figure \ref{fig:medianDist_T4} is when $T = 4$. Figure \ref{fig:medianDist_T2} shows that when $A = 2$, i.e., when there are two agents communicating with each other, the agents converge towards the targets. This convergence is more pronounced when there are 5 agents tracking two targets. An additional five agents (for a total of 10) only provides a slight improvement, and this is mostly likely a consequence of the behavior observed in Figures \ref{fig:Simulation2_part1} - \ref{fig:Simulation3_part2}. Recall that these figures illustrate that an excessive number of communicating agents does not help in tracking and following targets, as the additional information an extra agent provides on the kinetic states of a target is negligible. The simulated setting which provides the fastest and closest tracking is when five groups of two agents independently and simultaneously track the targets. This is a scaled-up version of the simulation shown in Figures \ref{fig:Simulation4_part1} - \ref{fig:Simulation4_part2}, where two groups (as opposed to five) of two agents independently and simultaneously track two targets. The convergence in this case is shown by the magenta line in Figure \ref{fig:medianDist_T2} and is so prompt and close since (within each group of agents) there are no extraneous agents whose additional information is negligible. This type of convergence is observed on a larger scale in Figure \ref{fig:medianDist_T4}, where eight groups of four agents (a total of 32 agents) track four targets. This simulation is a scaled-up version of the simulation shown in Figures \ref{fig:Simulation5_part1} - \ref{fig:Simulation5_part2}, where only two (as opposed to eight) groups of four agents independently and simultaneously track four targets. \begin{figure}[th] \begin{center} \begin{tabular}{c} \includegraphics[trim = 1cm 7cm 1cm 7cm, scale = 0.45]{Convergence_T2.pdf} \end{tabular} \end{center} \caption{Median distance (across 100 simulations) from target to closest agent over time. Total number of targets is 2.} \label{fig:medianDist_T2} \end{figure} \begin{figure}[th] \begin{center} \begin{tabular}{c} \includegraphics[trim = 1cm 7cm 1cm 7cm, scale = 0.45]{Agents_Against_4Targets.pdf} \end{tabular} \end{center} \caption{Median distance (across 100 simulations) from target to closest agent over time. Total number of targets is 4, and the total number of agents is 32 (8 groups of 4 agents).} \label{fig:medianDist_T4} \end{figure} As can be seen in Figures \ref{fig:Simulation1_part1} - \ref{fig:medianDist_T4}, it appears that, on average, the targets are detected and found relatively quickly. This implies that the agents consistently choose (via the stochastic gradient method) to be close to a target. Recall that the closer an agent is to a target, the more likely it is to gain information about the target's states, and information gain on the states of all of the targets is the ultimate goal. We also explored how the computational cost of the algorithm scales with the number of agents, $A$, and the number of targets, $T$. Table \ref{tab:CPU_time} gives the average CPU time it takes to run one simulation for 4000 time steps (using {\tt MATLAB 2020b} on a MacBook Pro with a 2.3 GHz 8-Core Intel Processor). Table \ref{tab:CPU_time} also gives the average CPU time it takes for one agent to do the necessary filtering and processing in one time step. We refer to the former metric as the simulation time (ST) and the latter metric as Agent Processing Time (APT). The APT may be useful in a practical setting when scheduling the time delay between two different agents executing the PAC steps. \begin{table}[ht] \centering \caption{The average simulation time (ST) and the average agent processing time (APT) in seconds.} \begin{tabular}{ccccc} \hline A & T & Mean ST & Mean APT \\ \hline 2 & 2 & 47.86 & .00487 \\ 5 & 2 & 203.33 & .00934 \\ 5 & 3 & 273.62 & .0127 \\ 5 & 4 & 377.56 & .0176 \\ 5 & 5 & 498.42 & .0232 \\ 5 & 10 & 879.46 & .0412 \\ 5 & 15 & 1256.10 & .0584 \\ 10 & 2 & 679.91 & .0161 \\ 15 & 2 & 1431.37 & .0228 \\ 20 & 2 & 2537.79 & .0305 \\ 25 & 2 & 3817.83 & .0368 \\ \hline \end{tabular} \label{tab:CPU_time} \end{table} Plotting mean ST as $T$ increases with the value of $A$ fixed (at $A = 5$) and plotting mean ST as $A$ increases with the value of $T$ fixed (at $T = 2$), it is clear that the computational cost of the simulation grows quadratically with the number of agents and linearly with the number of targets. Plotting mean APT as $T$ increases with the value of $A$ fixed (at $A = 5$) and plotting mean APT as $A$ increases with the value of $T$ fixed (at $T = 2$), it is clear that the computational cost of the agent processing time grows linearly with the number of agents and the number of targets. \section{Conclusions} \label{sec:conclusions} We have observed in our simulation study that our proposed CSO is effective. On average, agents do successfully swarm to locate, track, and follow the moving enemy assets. Our proposed CSO algorithm is also simple. It requires that each agent iteratively (one-at-a-time) sense the targets, communicate its position and FIMs, estimate a loss function which decreases with decreasing uncertainty in the estimated states, and then selects a motion that minimizes its contribution to this loss function. Areas of future work include accounting for the dependence in the measurements collected by the agents, and possibly avoiding agent collisions.
{'timestamp': '2021-08-04T02:02:26', 'yymm': '2010', 'arxiv_id': '2010.05328', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05328'}
arxiv
\section{Introduction} Convolutional Neural Networks (CNNs) have set the state-of-the-art for many computer vision tasks~\cite{krizhevsky_imagenet_2012,he_deep_2016,simonyan_very_2015,szegedy_going_2015,lecun_gradient-based_1998,redmon_you_2016,chen_semantic_2015,goodfellow_deep_2016,he_delving_2015,lecun_deep_2015,noh_learning_2015,long_fully_2015}. The benchmark datasets which are used to measure performance often consist of clean and undistorted images~\cite{cordts_cityscapes_2016}. When networks are trained on clean image data and tested on real-world image corruptions, such as image noise or blur, the performance can decrease drastically~\cite{geirhos_generalisation_2018,hendrycks_benchmarking_2019,dodge_understanding_2016,azulay_why_2019,kamann_benchmarking_2020}. Common image corruptions cannot be avoided in safety-critical applications: Environmental influences, such as adverse weather conditions, may corrupt the image quality significantly. Foggy weather decreases the image contrast, and low-light scenarios may exhibit image noise. Fast-moving objects or camera motion cause image blur. Such influences cannot be fully suppressed by sensing technology, and it is hence essential that CNNs are robust against common image corruptions. Obviously a CNN should also be robust towards adversarial perturbations (e.g.,~\cite{szegedy_intriguing_2013,huang_safety_2017,cisse_parseval_2017,gu_towards_2014,carlini_towards_2017,metzen_detecting_2017,carlini_adversarial_2017}). \begin{figure}[h] \centering \subfloat[Corrupted validation image]{% \includegraphics[width=0.455\linewidth]{0a_crop.png}% }\hfil \subfloat[Ground truth]{% \includegraphics[width=0.455\linewidth]{0b_crop.png}% } \subfloat[Prediction with our training schema]{% \includegraphics[width=0.455\linewidth]{0e_crop.png}% }\hfil \subfloat[Prediction with standard training schema]{% \includegraphics[width=0.455\linewidth]{0d_crop.png}% } \caption{Results of a semantic segmentation model that is trained with our data augmentation schema. (a) An image crop of the Cityscapes validation set is corrupted by severe image noise. (b) Corresponding ground-truth. (c) Prediction of a model that is trained with our schema. (d) Prediction of the same model with reference training schema, where training images are not augmented with noise. The prediction with our training schema (c) is clearly superior to the prediction of the reference training schema (d), though our model is not trained with image noise. In particular the classes \textit{road}, \textit{traffic signs}, \textit{cars}, \textit{persons} and \textit{poles}, are more accurately predicted } \label{fig:fig1} \end{figure} Training CNNs directly on image corruptions is generally a possibility to increase the performance on the respective type of image corruption, however, this approach comes at the cost of increased training time. It is also possible that a CNN overfits to a specific type of image corruption trained on~\cite{geirhos_generalisation_2018,vasiljevic_examining_2016}. Recent work deals with the robustness against common image corruptions for the task of full-image classification, and less effort has been dedicated to semantic segmentation. Whereas other work utilizes, e.g., a set of data augmentation operations~\cite{hendrycks_augmix:_2019} we propose a new, robustness increasing, data augmentation schema (see Fig.~\ref{fig:fig1}) that does: a) not require any additional image data, and b) is easy to implement and c) can be used within any supervised semantic segmentation network, and d) is robust against many common image corruptions. For this, we build upon the work of Geirhos et al.~\cite{geirhos_imagenet-trained_2019}, where it has been shown that increasing the network bias towards the shape of objects does make the task of full-image classification more robust with respect to common image corruptions. We applied the style-transfer technique of Geirhos et al. to Cityscapes, but found the resulting images to be quite noisy (see Fig.~\ref{fig:stylized}). Training on such data might, therefore, increase robustness not solely due to an increased shape bias, but rather due to increased image corruption. Our aim is to find a training schema that does not have any type of image corruption added. \begin{figure}[h] \centering \subfloat[Original data]{% \includegraphics[width=0.24\linewidth]{9a.png}% }\hfil \subfloat[Stylized data]{% \includegraphics[width=0.24\linewidth]{9b.png}% }\hfil \subfloat[Zoom of (a)]{% \includegraphics[width=0.24\linewidth]{9c.png}% }\hfil \subfloat[Zoom of (b)]{% \includegraphics[width=0.24\linewidth]{9d.png}% } \caption{ Illustration of the style transfer technique of~\cite{geirhos_imagenet-trained_2019}. An original training image (a) of the Cityscapes dataset is stylized by a painting (b). (c) and (d) show the image content of the red rectangle of (a), where (d) is clearly noisier compared to the original data (c) } \label{fig:stylized} \end{figure} Whereas the method of~\cite{geirhos_imagenet-trained_2019} delivers high-quality results, their approach requires a computationally intensive style transfer technique and additional image data. We propose a simple, yet effective, data augmentation scheme, that decreases the amount of texture in the training data, and does not need additional data. The basic idea is to alpha-blend some training images with a texture-free representation, as illustrated in Fig.~\ref{fig:paintingbynumbers} (b). By doing so, the texture-based appearance of a training image is less reliable, forcing the network to develop additional shape-based cues for the segmentation. In this way, our schema does not require additional training data, as we directly use the available semantic segmentation ground-truth. It can be easily utilized for training any supervised semantic segmentation model. We demonstrate our data augmentation scheme's effectiveness on a broad range of common image corruptions, evaluated on the Cityscapes dataset. In summary, we give the following contributions: \begin{itemize}[noitemsep,nolistsep] \item[--] We propose a simple, yet effective, data augmentation scheme that increases the robustness of well-established semantic segmentation models for a broad range of image corruptions, through increasing the model's shape-bias. Our new training schema requires no additional data, can be utilized in any supervised semantic segmentation model, and is computationally efficient. \item[--] We validate our training schema through a series of validation experiments. With respect to our 16 different types of image corruptions and five different network backbones, we are in \SI{74}{\%} better than training with clean data. We are able to increase the mean IoU by up to \SI{25}{\%}. \end{itemize} \section{Related Work} Recent work has dealt with the robustness of CNNs for common image corruptions. We discuss the most recent work in the following. \textbf{Benchmarking robustness with respect to common corruptions.} The work in~\cite{azulay_why_2019,engstrom_exploring_2019} demonstrates that shifting input pixels can change the outcome significantly. Dodge and Karam~\cite{dodge_understanding_2016} show that CNNs are prone to common corruptions, such as blur, noise, and contrast variations, for the task of full-image classification. The authors further show in~\cite{dodge_study_2017} that the CNN performance of classifying corrupted images is significantly lower than human performance. Zhou~\cite{zhou_classification_2017} et al. find similar results. Geirhos et al.~\cite{geirhos_generalisation_2018} show that established models~\cite{szegedy_going_2015,he_deep_2016,simonyan_very_2015} for image classification trained on one type of image noise can struggle to generalize well to other noise types. Vasiljevic et al.~\cite{vasiljevic_examining_2016} find a similar result w.r.t image blur, and further, a reduced performance for clean data. Hendrycks and Dietterich~\cite{hendrycks_benchmarking_2019} corrupt the ImageNet dataset~\cite{deng_imagenet:_2009} by many common image corruptions and image perturbations. In this work, we apply the proposed image corruptions to the Cityscapes dataset. Michaelis et al.~\cite{michaelis_benchmarking_2019} benchmark the robustness in object detection and find a significant performance drop for corrupted input data. For the task of semantic segmentation, Vasiljevic et al.~\cite{vasiljevic_examining_2016} find that model performance of a VGG-16~\cite{simonyan_very_2015} is decreasing for an increasing amount of blur in the test data. Kamann and Rother~\cite{kamann_benchmarking_2020,kamann2020benchmarking} ablate the state-of-the-art semantic segmentation DeepLabv3$+$ architecture and show that established architectural design choices affect model robustness with respect to common image corruptions. Other work deals with robustness towards adverse weather conditions~\cite{sakaridis_guided_2019,sakaridis_semantic_2018,volk_towards_2019}, night scenes~\cite{dai_dark_2018}, or geometric transformations~\cite{fawzi_manitest:_2015,ruderman_pooling_2018}. \textbf{Increasing robustness with respect to common corruptions.} The research interest in increasing the robustness of CNN models with respect to common image corruptions grows. Most methods have been proposed for the task of full-image classification. Mahajan et al.~\cite{mahajan_exploring_2018} and Xie et al.~\cite{xie_self-training_2019} show that using more training data increases the robustness. The same result is found when more complex network backbones are used, also for object detection~\cite{michaelis_benchmarking_2019} and semantic segmentation~\cite{kamann_benchmarking_2020}. Hendrycks et al.~\cite{hendrycks_benchmarking_2019} show that adversarial logit pairing~\cite{kannan_adversarial_2018} increases the robustness for adversarial and common perturbations. The authors of~\cite{zheng_improving_2016,laermann_achieving_2019} increase model robustness through stability training methods. Several other works apply data augmentation techniques to increase generalization performance. Whereas some work occludes parts of images~\cite{zhong_random_2017,devries_improved_2017}, crops, replaces and mixes several images~\cite{yun_cutmix:_2019,zhang_mixup:_2017,takahashi_data_2019}, or applies various (learned) sets of distortions~\cite{hendrycks_augmix:_2019,cubuk_autoaugment:_2019}, other methods augment with artificial noise to increase robustness~\cite{gilmer_adversarial_2019,lopes_improving_2019,rusak_increasing_2020}. Geirhos et al.~\cite{geirhos_imagenet-trained_2019} demonstrate that classifiers trained on ImageNet tend to classify images based on an image's texture. They further show that increasing the shape-bias of a classifier (through style transfer~\cite{gatys_neural_2015}), also increases the robustness for common image corruptions. This work builds upon this finding to increase the shape-bias of semantic segmentation models and, thus, the robustness for common image corruptions. \section{Training Schema: Painting-by-Numbers} \label{sec:method} \begin{figure}[htbp] \centering \includegraphics[width=0.8\textwidth]{imgs/paintingbynumbers.pdf} \caption{ Overview of our proposed training schema, which we refer to as Painting-by-Numbers. (a) An RGB image of the Cityscapes training set and the respective ground-truth in (d). We paint the \textit{numbers}, i.e., ground-truth IDs of (d) randomly, leading to the texture-free representation shown in (c). Painting the numbers randomly is essential since these colors are not likely to appear in real imagery. The final training image (b) is then generated by alpha-blending (a) and (c). A fraction of training data is augmented as in b), which is used as training data that increases the robustness against common corruptions } \label{fig:paintingbynumbers} \end{figure} Our goal is to generically increase the robustness of semantic segmentation models for common image corruptions. Here, \textit{robustness} refers to training a model on clean data and subsequently validating it on corrupted data. Simply adding corrupted data to the training set does certainly increase the robustness against common corruptions. However, this approach comes along with drawbacks: Firstly, a significantly increased training time. Secondly, the possibility to overfit to specific image corruptions~\cite{geirhos_generalisation_2018,vasiljevic_examining_2016} and reduced performance on clean data~\cite{vasiljevic_examining_2016}. Thirdly, it further may be hard to actually identify all sources of corruption for new test scenarios. For our training schema, we build on the finding of~\cite{geirhos_imagenet-trained_2019}. We propose an augmentation schema (Painting-by-Numbers) that modifies the training process so that the model develops shape-based cues for the decision of how to segment a pixel, resulting in a generic increase of model robustness. The basis of our schema is that we treat the segmentation ground-truth as a texture-free representation of the original training data (see Fig.~\ref{fig:paintingbynumbers}). We then colorize (or \textit{paint}) the ground-truth labels (or \textit{numbers}) randomly (Painting-by-Numbers) to generate a representation as shown in Fig.~\ref{fig:paintingbynumbers} (c). We uniformly sample the color from the sRGB color gamut with range $[0, 255]$, similar to the images of the Cityscapes dataset. Painting the numbers randomly is essential since these colors are not likely to appear in real imagery. Finally, we alpha-blend this this representation with the original training image, according to eq.~\ref{eq:alphablend}, \begin{equation} I_{\mathit{blended}} = \alpha \times I_{\mathit{painting-by-numbers}} + (1 - \alpha) \times I_{\mathit{original}} \label{eq:alphablend} \end{equation} where $I_{\mathit{blended}}$ is the resulting alpha-blended training image (Fig.~\ref{fig:paintingbynumbers} b), $\alpha$ is the blend parameter (where $\alpha=1$ corresponds to a representation where original training input is entirely blended), $I_{\mathit{painting-by-numbers}}$ is the texture-free representation (Fig.~\ref{fig:paintingbynumbers} c) and $I_{\mathit{original}}$ is the original training image (Fig.~\ref{fig:paintingbynumbers} a). Training a network on such data forces the network to develop (or increase) its shape-bias since we actively corrupt the textural content of the image. The texture features of the image are, therefore, less reliable, and a model needs to develop additional cues to segment pixels correctly. Painting-by-Numbers is computationally efficient. For our setup, the training time increases by only~\SI{2.5}{\%} (please see the supplementary material for more details). \textbf{Motivation blending with $ \bm{0 < \alpha < 1}$.} We conducted the following analysis. We trained a model solely on texture-free images, as shown in Fig.~\ref{fig:paintingbynumbers} c, meaning that the blend parameter $\alpha$ is fixed to $1$. This network achieved a decent performance when tested on a texture-free variant of the Cityscapes validation set. This is a positive signal because it means that the model is able to learn from entirely texture-free training data. When we augmented only half of a training batch, instead of every image, ($\alpha$ is still fixed to $1$), the performance on both, the original validation set and texture-free validation set was, again, considerably high; However, the robustness of the new model with respect to common image corruptions was not increased. We hypothesize that such a model learns to predict well for two different domains, which are the original data and the texture-free data. This motivates us to choose $\alpha < 1$ for some training images. As we will see, with a varying degree of alpha-blending, the robustness of the model towards common image corruptions increases significantly and, at the same time, keeps a consistently good performance on clean data. \textbf{Training protocol.} We use the state-of-the-art DeepLabv3$+$~\cite{chen_deeplab:_2017,chen_encoder-decoder_2018,chen_rethinking_2017,chen_semantic_2015} semantic segmentation architecture as baseline model. We show the effectiveness of Painting-by-Numbers for many network backbones: MobileNet-V2~\cite{sandler_mobilenetv2:_2018}, ResNet-50~\cite{he_deep_2016}, ResNet-101, Xception-41, Xception-71~\cite{chollet_xception:_2017}. We augment exactly half of a batch by our Painting-by-Numbers approach and leave the remaining images unchanged. Doing so ensures that the performance on clean data is comparable to a network that is trained regularly on clean data only. We kindly refer to the next section for reasonable choices of the hyperparameters. We apply a similar training protocol as in~\cite{chen_encoder-decoder_2018}: crop size $513 \times 513$\footnote{Due to hardware limitations we are not able to train on the suggested crop size of 769.}, initial learning rate $0.01$, ``poly''~\cite{liu_parsenet:_2015} learning rate schedule, using the Atrous Spatial Pyramid Pooling (ASPP) module~\cite{chen_semantic_2015,grauman_pyramid_2005,he_spatial_2014,lazebnik_beyond_2006,zhao_pyramid_2017}, fine-tuning batch normalization~\cite{ioffe_sergey_batch_2015} parameters, output stride $16$, random scale data augmentation and random flipping during training. As suggested by~\cite{chen_encoder-decoder_2018}, we apply no global average pooling~\cite{lin_network_2014}. We train every model using TensorFlow~\cite{abadi_tensorflow:_2016}. \textbf{Evaluation protocol.} We use the image transformations provided by the ImageNet-C~\cite{hendrycks_benchmarking_2019} dataset to generate Cityscapes-C, similar to~\cite{kamann_benchmarking_2020}. The ImageNet-C corruptions give a huge selection of transformations. They consist of several types of blur (Gaussian, motion, defocus, frosted glass), image noise (Gaussian, impulse, shot, speckle), weather (snow, spatter, fog, frost), and digital transformations (JPEG, brightness, contrast). Please see the supplementary material for examples. Each corruption type (e.g., Gaussian noise) is parameterized in five severity levels. We evaluate the mean-IoU~\cite{everingham_pascal_2010} of many variants of the Cityscapes validation set, which is corrupted by the ImageNet-C transformations. \section{Experimental Evaluation and Validation} \label{sec:experiments} In this section, we demonstrate the effectiveness of Painting-by-Numbers. In section~\ref{sec:ablationstudies} we discuss implementation details. We then show the results w.r.t the Cityscapes dataset in section~\ref{sec:results_cityscapes}. We conduct a series of experiments to validate the increased shape-bias of a model trained with Painting-by-Numbers in section~\ref{sec:validation}. \subsection{Implementation Details} \label{sec:ablationstudies} We experiment with varying implementations and augmentation schemes, which we discuss next. \textbf{Parameters for alpha-blending.} Our experiments show that a fixed value for $\alpha$ does not yield the best results. Instead, we use two parameters for alpha-blending, $\alpha_{min}$ and $\alpha_{max}$. These values define an interval from which $\alpha$ is drawn. They are the essential hyperparameters needed to achieve the best results towards common image corruptions. If $\alpha_{min}$ is too low, i.e., the amount of texture in the image is high, the robustness increase for common corruptions is minor. If $\alpha_{min}$ is too high, i.e., the amount of texture in the image is further diminished, the robustness decreases with respect to common corruptions (as discussed previously). We observe that the models only connect learned features from the two domains (original data domain and alpha-blended data domain) if the latter's texture is present, i.e., $0 < \alpha < 1$. \textbf{Batch augmentation schemes.} We always augment exactly the half of a batch by Painting-By-Numbers for each iteration of the forward path. To summarize, the only parameters to be optimized are $\alpha_{min}$ and $\alpha_{max}$. We do not observe better results when for every image in the mini-batch is individually decided if it shall be augmented by Painting-by-Numbers. \textbf{Incorporating instance labels.} Beside semantic segmentation ground-truth, the Cityscapes dataset also contains instance labels for several classes. We additionally utilize them in our augmentation scheme to paint each instance with a randomly chosen color (instead of painting each instance of a class with the same color), as illustrated in Fig.~\ref{fig:instancelabels} (a). This produces promising results with respect to further increasing network robustness. Since Painting-by-Numbers is targeted for semantic segmentation task, we base our schema on the more general semantic labels, which are available for all reference datasets. \begin{figure} \centering \subfloat[Instances are painted randomly]{% \includegraphics[width=0.3\linewidth]{blended_instances_randomly_2.png}% }\hfil \subfloat[Instances are painted by RGB-mean]{% \includegraphics[width=0.3\linewidth]{blended_instances_mean_2.png}% }\hfil \subfloat[Instances are painted by RGB-median]{% \includegraphics[width=0.3\linewidth]{blended_instances_median_2.png}% }\hfil \caption{ Examples of several coloring schemes used for Painting-by-Numbers} \label{fig:instancelabels} \end{figure} \textbf{Paint with mean and median RGB.} We further paint the images with a more consistent color, such as the mean and median RGB value of the class or instance (instead of painting the semantic classes randomly), as illustrated in Fig.~\ref{fig:instancelabels} (b) and (c). This approach does, as expected, not increase the model robustness. Instead of forcing a model to not rely on texture and color appearance, by corrupting these very properties, the network learns to assign a mean or median value to classes and instances, contrary to the effect of random painting. Hence, there is no need to increase the shape-bias for predicting the segmentation map when the colors are likely to appear in real imagery. \textbf{Best Setup.} We train MobileNet-V2, ResNet-50, ResNet-101, Xception-41, and Xception-71 with Painting-by-Numbers. We evaluate the models on Gaussian noise to select the final values for $\alpha$. For ResNet-50, and Xception-41, we observe the best results when we draw $\alpha$ uniformly from the interval $\alpha_{min}=0.70$ and $\alpha_{max}=0.99$. For the remaining networks, we observe the best results for $\alpha_{min}=0.50$ and $\alpha_{max}=0.99$. \subsection{Results on Cityscapes} \label{sec:results_cityscapes} In the following, we refer to a network that is trained with standard training schema as the reference model (i.e., trained on clean data only), and to a model that is trained with Painting-by-Numbers as our model. Fig.~\ref{fig:corruptions} shows qualitative and quantitative results on corrupted variants of the Cityscapes dataset, when a network (ResNet-50) is trained with both training schemes. Every image corruption is parameterized with five severity levels. Severity level $0$ corresponds to the clean data. The reference model (third row) struggles to predict well in the presence of image corruptions (Fig.~\ref{fig:corruptions} top). It segments large parts of \textit{road} wrongly as \textit{building} for \textit{spatter} and \textit{image noise}. When the same model is trained with Painting-by-Numbers, the predictions are clearly superior (fourth row). With respect to quantitative results (Fig.~\ref{fig:corruptions} bottom), our model performs significantly better for image corruptions of category \textit{speckle noise}, \textit{shot noise}, and \textit{contrast}. Corruption \textit{contrast} decreases the contrast of the full image, corrupting hence the textural image content strongly. A network that is able to rely also on shape-based cues for the image segmentation is hence a well-performing model for \textit{contrast reduction}. The mean IoU on \textit{spatter} is for both models comparable for the first severity level, but it is for our model higher by almost \SI{15}{\%} for the fourth severity level. \begin{figure}[ht!] \centering \resizebox{\textwidth}{!}{ \begin{tabular}{c c c c } \centering { (a) Speckle Noise } & { (b) Shot Noise} & {(c) Contrast }& {(d) Spatter}\\ [-2ex] \subfloat{ \rotatebox[origin=b]{90}{RGB} \includegraphics[valign=m,width=0.225\linewidth]{4a.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4bbb.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4ccc.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4ddd.png} } \\ [-2ex] \subfloat{ \rotatebox[origin=b]{90}{GT} \includegraphics[valign=m,width=0.225\linewidth]{4agt.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4bgt.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4cgt.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4dgt.png} } \\ [-2ex] \subfloat{ \rotatebox[origin=b]{90}{Reference} \includegraphics[valign=m,width=0.225\linewidth]{4ee.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4fff.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{imgs/4ggg.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4hhh.png} } \\ [-2ex] \subfloat{ \rotatebox[origin=b]{90}{Ours} \includegraphics[valign=m,width=0.225\linewidth]{4ii.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4jjj.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4kkk.png} } & \subfloat{ \includegraphics[valign=m,width=0.225\linewidth]{4lll.png} } \\ [+5ex] \multicolumn{4}{l}{ \subfloat{ \includegraphics[width=1\linewidth]{eccv_corruption_plot.pdf} } } \end{tabular}~ } \caption{ \textbf{(top)} Qualitative results by the ResNet-50 backbone on four corrupted images of the Cityscapes validation dataset for both the reference model and our model (i.e., trained with Painting-by-Numbers). \textbf{(bottom)} Quantitative results on the corrupted variants of the Cityscapes dataset. Each image corruption is parameterized with five severity levels, where severity level $0$ corresponds to clean (i.e., original) data. While for clean data, both models' performance is more or less the same, we see that our model is clearly superior for all types of noise added. For consistent performance on clean data, the performance on corrupted data increases when the model is trained with Painting-by-Numbers. For the first severity level of shot noise, the mIoU of our model is higher by \SI{25}{\%} } \label{fig:corruptions} \end{figure} The results for the remaining image corruptions for the Cityscapes dataset are listed in Table~\ref{tab:results_cs}. We show the effectiveness of Painting-by-Numbers besides ResNet-50 also for MobileNet-V2, ResNet-101, Xception-41, and Xception-71. In the first column, we report the performance on clean data, i.e., the original Cityscapes validation set. The mIoU evaluated on several types of image corruptions is listed accordingly. Each value is the average for up to five severity levels. We report for both clean and corrupted data, the result of the reference model and our model. In the following, we discuss the main results of Table~\ref{tab:results_cs}. \begin{table}[hbtp] \centering \caption{ Results on the Cityscapes dataset. Each entry is the mean IoU of several corrupted variants of the Cityscapes dataset. Every image corruption is parameterized with five severity levels, and the resulting mean IoU are averaged. For image noise-based corruption, we exclude every severity level whose signal-to-noise ratio less than 10. The higher mIoU of either the reference model or the respective model trained with Painting-by-Numbers is bold. Overall, we see many (\SI{74}{\%}) more bold numbers for our Painting-by-Numbers model } \label{tab:results_cs} \begin{adjustbox}{width=\textwidth} \begin{tabular}{@{}cccccccccccccccccc@{}} \toprule & & \multicolumn{4}{c}{\textbf{Blur}} & \multicolumn{4}{c}{\textbf{Noise}} & \multicolumn{4}{c}{\textbf{Digital}} & \multicolumn{4}{c}{\textbf{Weather}} \\ \midrule \multicolumn{1}{c|}{Network} & \multicolumn{1}{c|}{Clean} & Motion & Defocus & \begin{tabular}[c]{@{}c@{}}Frosted \\ Glass\end{tabular} & \multicolumn{1}{c|}{Gaussian} & Gaussian & Impulse & Shot & \multicolumn{1}{c|}{Speckle} & Brightness & Contrast & Saturate & \multicolumn{1}{c|}{JPEG} & Snow & Spatter & Fog & Frost \\ \midrule \multicolumn{1}{c|}{\textbf{Reference}} & \multicolumn{1}{c|}{} & & & & \multicolumn{1}{c|}{} & & & & \multicolumn{1}{c|}{} & & & & \multicolumn{1}{c|}{} & & & & \\ \multicolumn{1}{c|}{MobileNet-V2} & \multicolumn{1}{c|}{\textbf{73.0}} & \textbf{52.4} & \textbf{47.0} & \textbf{44.7} & \multicolumn{1}{c|}{\textbf{48.1}} & 9.6 & 14.2 & 9.8 & \multicolumn{1}{c|}{25.6} & 50.4 & 43.8 & 32.5 & \multicolumn{1}{c|}{\textbf{20.3}} & 10.8 & 43.3 & 47.7 & 16.1 \\ \multicolumn{1}{c|}{ResNet-50} & \multicolumn{1}{c|}{\textbf{76.6}} & 57.1 & \textbf{55.2} & 45.3 & \multicolumn{1}{c|}{\textbf{56.5}} & 10.7 & 13.4 & 12.1 & \multicolumn{1}{c|}{37.7} & 59.8 & 52.7 & 41.7 & \multicolumn{1}{c|}{\textbf{23.4}} & \textbf{12.9} & 39.8 & 56.2 & 19.0 \\ \multicolumn{1}{c|}{ResNet-101} & \multicolumn{1}{c|}{76.0} & \textbf{58.9} & \textbf{55.3} & 47.8 & \multicolumn{1}{c|}{\textbf{56.3}} & 22.9 & 22.9 & 23.1 & \multicolumn{1}{c|}{45.5} & 57.7 & 56.8 & 41.6 & \multicolumn{1}{c|}{\textbf{32.5}} & \textbf{11.9} & 45.5 & 55.8 & 23.2 \\ \multicolumn{1}{c|}{Xception-41} & \multicolumn{1}{c|}{77.8} & 61.6 & \textbf{54.9} & 51.0 & \multicolumn{1}{c|}{\textbf{54.7}} & 27.9 & 28.4 & 27.2 & \multicolumn{1}{c|}{53.5} & 63.6 & 56.9 & 51.7 & \multicolumn{1}{c|}{\textbf{38.5}} & 18.2 & 46.6 & 57.6 & 20.6 \\ \multicolumn{1}{c|}{Xception-71} & \multicolumn{1}{c|}{77.9} & 62.5 & \textbf{58.5} & \textbf{52.6} & \multicolumn{1}{c|}{\textbf{57.7}} & 22.0 & 11.5 & 21.6 & \multicolumn{1}{c|}{48.7} & 67.0 & 57.2 & 45.7 & \multicolumn{1}{c|}{\textbf{36.1}} & 16.0 & 48.0 & 63.9 & 20.5 \\ \midrule \multicolumn{1}{c|}{\textbf{Painting-by-Numbers}} & \multicolumn{1}{c|}{} & & & & \multicolumn{1}{c|}{} & & & & \multicolumn{1}{c|}{} & & & & \multicolumn{1}{c|}{} & & & & \\ \multicolumn{1}{c|}{MobileNet-V2} & \multicolumn{1}{c|}{72.2} & 49.5 & 41.4 & 40.7 & \multicolumn{1}{c|}{43.0} & \textbf{17.4} & \textbf{18.4} & \textbf{16.8} & \multicolumn{1}{c|}{\textbf{35.7}} & \textbf{62.5} & \textbf{50.8} & \textbf{51.0} & \multicolumn{1}{c|}{17.6} & \textbf{12.1} & \textbf{46.9} & \textbf{56.5} & \textbf{22.4} \\ \multicolumn{1}{c|}{ResNet-50} & \multicolumn{1}{c|}{76.1} & \textbf{58.1} & 53.5 & \textbf{50.3} & \multicolumn{1}{c|}{55.1} & \textbf{35.7} & \textbf{34.3} & \textbf{36.1} & \multicolumn{1}{c|}{\textbf{56.7}} & \textbf{68.8} & \textbf{64.2} & \textbf{60.5} & \multicolumn{1}{c|}{21.3} & 10.6 & \textbf{46.1} & \textbf{61.0} & \textbf{22.9} \\ \multicolumn{1}{c|}{ResNet-101} & \multicolumn{1}{c|}{\textbf{76.3}} & 58.1 & 54.2 & \textbf{48.7} & \multicolumn{1}{c|}{54.7} & \textbf{41.6} & \textbf{44.3} & \textbf{40.6} & \multicolumn{1}{c|}{\textbf{57.4}} & \textbf{70.5} & \textbf{64.4} & \textbf{65.0} & \multicolumn{1}{c|}{25.6} & 10.8 & \textbf{50.1} & \textbf{56.9} & \textbf{28.0} \\ \multicolumn{1}{c|}{Xception-41} & \multicolumn{1}{c|}{\textbf{78.5}} & \textbf{65.5} & 54.2 & \textbf{51.1} & \multicolumn{1}{c|}{51.8} & \textbf{46.9} & \textbf{44.9} & \textbf{46.9} & \multicolumn{1}{c|}{\textbf{64.3}} & \textbf{73.4} & \textbf{60.2} & \textbf{68.8} & \multicolumn{1}{c|}{15.7} & \textbf{19.3} & \textbf{55.8} & \textbf{65.7} & \textbf{28.2} \\ \multicolumn{1}{c|}{Xception-71} & \multicolumn{1}{c|}{\textbf{78.6}} & \textbf{63.0} & 53.6 & 48.6 & \multicolumn{1}{c|}{52.2} & \textbf{35.5} & \textbf{38.4} & \textbf{34.2} & \multicolumn{1}{c|}{\textbf{57.6}} & \textbf{74.9} & \textbf{63.9} & \textbf{69.1} & \multicolumn{1}{c|}{22.2} & \textbf{18.2} & \textbf{57.4} & \textbf{65.4} & \textbf{25.5} \\ \bottomrule \end{tabular} \end{adjustbox} \end{table} \textbf{Performance w.r.t clean data.} Even though we paint the exact half of the training data and train both models for the same amount of iterations, the performance on clean data is oftentimes barely affected. \textbf{Performance w.r.t image blur.} The robustness of our model with respect to image blur does not notably increase. We assume that Painting-by-Numbers does not increase the performance for this category of image corruptions because blur corrupts the object shapes by smearing the object boundaries. Hence, our learned shape-bias does not work well. \textbf{Performance w.r.t image noise.} Painting-by-Numbers increases the robustness with respect to image noise the most (see figures above). For example, the absolute mIoU of Xception-41 for Gaussian noise, impulse noise, shot noise, and speckle noise increases by \SI{19.0}{\%}, \SI{16.5}{\%}, \SI{19.7}{\%}, and \SI{11.0}{\%}, respectively. \textbf{Performance w.r.t digital corruptions.} A network trained with Painting-by-Numbers increases significantly the robustness against the corruptions \textit{brightness}, \textit{contrast}, and \textit{saturation}--but not JPEG artifacts. The reason is that \textit{JPEG compression} corrupts the boundary of objects and incorporates new boundaries through posterization artifacts. Our network cannot hence profit from its increased shape-bias. We refer to the supplement for an illustration. \textbf{Performance w.r.t weather corruptions.} Xception-71 and Xception-41 increases the performance with respect to \textit{spatter} by \SI{9.4}{\%} and \SI{9.2}{\%}, respectively. Xception-41 further increases the mIoU against \textit{frost} by \SI{7.6}{\%}. Every model increases the performance against \textit{fog}. We cannot observe a significant performance increase for \textit{snow}. Though the performance increase on image corruptions of category \textit{weather} is less than, e.g., for image noise, the predictions of a network trained with Painting-by-Numbers are improved for key-classes such as \textit{cars}, \textit{persons}, and \textit{traffic signs} than for a regularly trained network. Please see the supplementary material for more results. \subsection{Understanding Painting-by-Numbers} \label{sec:validation} We explain the increased robustness towards common image corruptions, i.e., when a network is trained with Painting-by-Numbers, by an increased shape-bias. To validate this assumption, we conduct a series of experiments that are based on the following consideration: Classes that either have a) no texture at all or b) texture that is strongly corrupted should be more reliably segmented by a network trained with Painting-by-Numbers. In more detail, we generate numerous, on class-level corrupted, variants of the Cityscapes validation set, as illustrated in Fig.~\ref{fig:validation}. In (a), we remove the texture of \textit{cars} and replace it by the dataset-wide RGB-mean of the training set of the respective class. The respective class does, in this way, not contain any texture but homogeneous color information. In (b) and (c) we corrupt \textit{building} and \textit{car} by a high degree of additive Gaussian noise and Gaussian blur, respectively. Please note that Fig.~\ref{fig:validation} shows only a small set of examples. We apply these corruptions for every class. We test the models on such images to evaluate if they are capable of segmenting the respective class when they cannot rely on the class texture. To achieve this, a network needs to utilize other cues, such as shape-based cues. \begin{figure}[hbtp] \centering \subfloat[Replaced \textit{car} by RGB-mean]{ \includegraphics[width=0.3\linewidth]{frankfurt_000000_000576_leftImg8bit_mask13_classmean_background_original.png} }\hfil \subfloat[Corrupted \textit{building} by severe noise]{ \includegraphics[width=0.3\linewidth]{frankfurt_000000_001751_leftImg8bit_mask2_noise100_background_original.png} }\hfil \subfloat[Corrupted \textit{car} by severe blur]{ \includegraphics[width=0.3\linewidth]{validation_blur.png} } \caption{ Examples of image data to validate an increasing shape-bias when models are trained with Painting-by-Numbers. We remove, or strongly corrupt, the texture of each class in the Cityscapes dataset and evaluate the segmentation performance when a network cannot rely on the class texture. (a) Texture is fully replaced by the dataset-wide RGB-mean value of the respective class. (b) Class is corrupted by severe noise. (c) Class is corrupted by severe blur } \label{fig:validation} \end{figure} Instead of IoU, we use the sensitivity $s$ ($s = TP/(TP+FN)$, where $TP$ are true-positives, and $FN$ are false-negatives) as evaluation metric. The sensitivity is for these experiments more appropriate than IoU ($IoU = TP/(TP+FN+FP)$) since we are solely interested in the segmentation performance on the class-level. Because all classes but one is clean (i.e., not corrupted), false-positively (FP) segmented pixels are of less interest. Utilizing IoU could, especially for classes covering fewer image regions, result in misleading scores. The results of these experiments are listed in Table~\ref{tab:validation_results}. \begin{table}[ht] \centering \caption{ Sensitivity score per class for several corrupted variants on the class-level of the Cityscapes datasets. \textbf{Clean:} The performance on clean (i.e. original, non-corrupted) data. \textbf{RGB-mean:} The texture of a class is replaced by the dataset-wide RGB mean of that class. \textbf{Noise:} The texture of a class is corrupted by severe additive Gaussian noise. \textbf{Blur:} The texture of a class is corrupted by severe Gaussian blur. The higher sensitivity score of a network backbone of either the reference (top) or our model (bottom) is bold. Overall, we see many more bold numbers for our Painting-by-Numbers model } \label{tab:validation_results} \begin{adjustbox}{width=\textwidth} \begin{tabular}{@{}cccccccccccccccccccc@{}} & \rotatebox[origin=l]{90}{road} & \rotatebox[origin=l]{90}{sidewalk} & \rotatebox[origin=l]{90}{building} & \rotatebox[origin=l]{90}{wall} & \rotatebox[origin=l]{90}{fence} & \rotatebox[origin=l]{90}{pole} & \rotatebox[origin=l]{90}{traffic light} & \rotatebox[origin=l]{90}{traffic sign} & \rotatebox[origin=l]{90}{vegetation} & \rotatebox[origin=l]{90}{terrain} & \rotatebox[origin=l]{90}{sky} & \rotatebox[origin=l]{90}{person} & \rotatebox[origin=l]{90}{rider} & \rotatebox[origin=l]{90}{car} & \rotatebox[origin=l]{90}{truck} & \rotatebox[origin=l]{90}{bus} & \rotatebox[origin=l]{90}{train} & \rotatebox[origin=l]{90}{motorcycle} & \rotatebox[origin=l]{90}{bicycle} \\ \midrule \textbf{Reference} & & & & & & & & & & & & & & & & & & & \\ Clean & 98.8 & \textbf{93.1} & \textbf{96.6} & 53.3 & \textbf{69.6} & \textbf{74.5} & \textbf{81.7} & \textbf{85.7} & \textbf{96.7} & \textbf{74.1} & \textbf{97.8} & \textbf{91.5} & \textbf{76.9} & \textbf{97.6} & 85.1 & \textbf{92.8} & \textbf{70.7} & \textbf{79.2} & \textbf{88.7} \\ RGB-mean & 92.7 & 21.1 & \textbf{88.9} & \textbf{40.7} & 5.4 & 68.9 & 12.8 & 31.5 & 1.4 & \textbf{3.3} & \textbf{97.7} & 73.4 & 62.5 & 24.5 & 13.6 & \textbf{16.3} & \textbf{9.0} & 2.9 & 0.9 \\ Noise ($\mathit{scale}=0.5$) & 5.8 & 0.8 & \textbf{95.0} & 0.2 & 1.7 & 4.7 & 6.4 & \textbf{39.2} & 0.1 & 1.4 & 2.8 & 8.1 & 2.9 & 4.5 & 0.0 & 0.0 & \textbf{7.1} & 0.2 & 3.4 \\ Noise ($\mathit{scale}=1.0$) & 2.9 & 0.0 & \textbf{94.0} & 0.1 & 1.2 & 2.0 & 6.4 & \textbf{40.2} & 0.0 & 0.5 & 0.2 & 4.4 & 1.2 & 3.6 & 0.0 & 0.0 & \textbf{3.0} & 0.2 & 2.0 \\ Blur ($\sigma=20$) & \textbf{94.6} & 42.8 & \textbf{89.3} & \textbf{38.0} & 1.8 & 63.6 & 18.4 & 19.1 & 0.6 & \textbf{7.3} & 94.0 & 55.4 & 55.5 & 56.7 & 32.5 & \textbf{24.0} & \textbf{7.7} & 9.0 & 0.9 \\ Blur ($\sigma=30$) & \textbf{94.1} & 42.1 & \textbf{89.4} & \textbf{33.2} & 1.2 & 62.3 & 14.0 & 16.2 & 0.6 & \textbf{2.3} & 93.8 & 54.6 & 51.8 & 44.2 & 29.8 & \textbf{18.6} & \textbf{8.1} & 4.2 & 1.1 \\ \midrule \textbf{Painting-by-Numbers} & & & & & & & & & & & & & & & & & & & \\ Clean & \textbf{99.0} & 90.3 & 96.3 & \textbf{56.0} & 67.1 & 68.9 & 76.5 & 81.1 & 96.2 & 66.3 & 97.1 & 89.5 & 74.0 & 96.8 & \textbf{89.7} & 86.0 & 59.6 & 72.2 & 87.8 \\ RGB-mean & \textbf{97.9} & \textbf{53.8} & 51.2 & 34.2 & \textbf{14.9} & \textbf{79.7} & \textbf{38.4} & \textbf{40.5} & \textbf{1.8} & 2.3 & 97.4 & \textbf{78.4} & \textbf{66.3} & \textbf{78.6} & \textbf{37.6} & 3.5 & 0.4 & \textbf{9.1} & \textbf{4.6} \\ Noise ($\mathit{scale}=0.5$) & \textbf{97.4} & \textbf{50.9} & 92.1 & \textbf{8.4} & \textbf{37.4} & \textbf{34.1} & \textbf{8.2} & 11.1 & \textbf{23.3} & \textbf{30.6} & \textbf{32.3} & \textbf{50.1} & \textbf{19.7} & \textbf{49.8} & \textbf{31.5} & \textbf{1.9} & 0.0 & \textbf{0.3} & \textbf{26.7} \\ Noise ($\mathit{scale}=1.0$) & \textbf{95.9} & \textbf{51.7} & 91.3 & \textbf{9.6} & \textbf{29.4} & \textbf{32.3} & \textbf{7.1} & 9.9 & \textbf{12.2} & \textbf{27.2} & \textbf{33.6} & \textbf{52.7} & \textbf{21.3} & \textbf{40.6} & \textbf{25.8} & \textbf{1.1} & 0.0 & \textbf{0.4} & \textbf{23.3} \\ Blur ($\sigma=20$) & 49.3 & \textbf{43.5} & 86.5 & 18.7 & \textbf{4.7} & \textbf{73.6} & \textbf{55.1} & \textbf{29.8} & \textbf{1.0} & 0.8 & \textbf{94.3} & \textbf{75.5} & \textbf{73.2} & \textbf{71.9} & \textbf{56.6} & 7.9 & 0.5 & \textbf{20.2} & \textbf{3.5} \\ Blur ($\sigma=30$) & 46.3 & \textbf{48.0} & 83.2 & 14.1 & \textbf{4.5} & \textbf{73.6} & \textbf{49.7} & \textbf{25.4} & \textbf{1.0} & 0.5 & \textbf{94.7} & \textbf{74.6} & \textbf{71.1} & \textbf{73.7} & \textbf{47.9} & 3.8 & 0.2 & \textbf{18.2} & \textbf{3.8} \\ \bottomrule \end{tabular} \end{adjustbox} \end{table} \textbf{Quantitative results.} The results in Table~\ref{tab:validation_results} are created by DeepLabv3$+$ with ResNet-50 as network backbone. As previously, we refer to a network that is trained with the standard training schema as the reference model (i.e., only clean data used), and to a model that is trained with Painting-by-Numbers as our model. The top (bottom) part of the Table contains the sensitivity score for each class of the reference model (our model). Each line shows the sensitivity for the corrupted data as described previously (the performance on clean data is also listed). The higher sensitivity of a network backbone of either the reference model (top) or our model (bottom) is bold. We separately discuss in the following the quantitative results for class categories ``stuff'' and ``things''. Both networks perform well for classes ``stuff'' since the amount of texture is often poor, such as for \textit{road}, \textit{wall}, \textit{sidewalk}, and \textit{sky}. The sensitivity of both models differs for \textit{road} by \SI{5.2}{\%}, for \textit{wall} by \SI{6.5}{\%}, and for sky by \SI{0.3}{\%}. Whereas the absolute sensitivity for both models is above \SI{90.0}{\%} for \textit{road} and \textit{sky}, it is less than \SI{41}{\%} for \textit{wall}. Our model performs for \textit{sidewalk} better by \SI{32.7}{\%}. Painting-by-Numbers performs worse than the reference for classes ``stuff'' with a large amount of textual information, such as \textit{building}, \textit{vegetation}, and \textit{terrain}. For example, the sensitivity score of our model for \textit{building} is \SI{37.7}{\%} less. Classes ``stuff'' have no distinct shape, hence, Painting-by-Numbers does not aid performance. When, additionally, the amount of texture of a class is large, the sensitivity of our model is less than of the reference model. The reference model performs well when the texture of the category ``things'' is replaced by RGB-mean. Its sensitivity for \textit{person} is \SI{73.4}{\%}, which is only \SI{5.0}{\%} less than for our model. The result for class \textit{rider} is similar. However, our model performs often significantly better than the reference model for most of the remaining ``things'' such as \textit{car}. The sensitivity score of our model for this class is $s_\mathit{ours}=\SI{78.6}{\%}$, which is \SI{54.1}{\%} higher than the sensitivity score of the reference model. We explain this high score with a large shape-bias due to both the distinct shape of \textit{cars} and the comparatively large number of \textit{cars} in the training set~\cite{cordts_cityscapes_2016}. Our model performs for other classes of ``things'' also better than the reference model. For example, the sensitivity score for classes \textit{traffic light}, \textit{traffic sign} and \textit{pole} is higher by \SI{25.6}{\%}, \SI{9.0}{\%}, and \SI{9.8}{\%}, respectively. Both models perform poorly on ``vehicles'' that are, compared to \textit{cars}, less frequent present in the training set (e.g., \textit{truck, motorcycle, train}). In the presence of severe Gaussian noise, the reference model is struggling to segment classes. The sensitivity is poor for every class, except for \textit{traffic signs} and \textit{building}. In the presence of image noise, the reference model tends to segment pixels oftentimes as these very classes, as illustrated in Fig.~\ref{fig:corruptions} and Fig~\ref{fig:validation_qualitive_results}. The sensitivity scores of our model are often significantly higher. Similar to the previously discussed results, the sensitivity with respect to ``stuff'' with less texture is often high (e.g., $s_\mathit{ours}=\SI{95.9}{\%}$ for \textit{road}). The sensitivity scores are also high for ``things'' such as \textit{persons} and \textit{cars} ($s_\mathit{ours}=\SI{52.7}{\%}$, and $s_\mathit{ours}=\SI{40.6}{\%}$, respectively). Our model segments many classes well that are corrupted by severe image noise, even though our model has not seen image noise during the training. The reference model generally performs well when classes are low-pass filtered by severe Gaussian blur. This result is in accordance with~\cite{kamann_benchmarking_2020}, where the authors found semantic segmentation models to be relatively robust towards image blur. Again, for class category ``things'', our model outperforms the reference model in most cases. For example, the sensitivity score of our model for \textit{person}, \textit{rider}, and \textit{car} is by approx. \SI{20.0}{\%} higher. \textbf{Qualitative results.} See Fig.~\ref{fig:validation_qualitive_results} for qualitative results of the previously discussed experiments. Please see the caption of Fig.~\ref{fig:validation_qualitive_results} for discussion. \begin{figure}[ht] \centering \resizebox{\textwidth}{!}{ \begin{tabular}{c c c c} \centering (a) Original & (b) Mean-RGB & (c) Blur & (d) Noise \\ \subfloat{ \rotatebox[origin=b]{90}{RGB} \includegraphics[valign=m,width=0.23\linewidth]{frankfurt_000000_011810_leftImg8bit.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{frankfurt_000000_011810_leftImg8bit_mask13_classmean_background_original.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{frankfurt_000000_011810_leftImg8bit_mask13_blur30_background_original.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{frankfurt_000000_011810_leftImg8bit_mask13_noise100_background_original.png} } \\ [-2ex] \subfloat{ \rotatebox[origin=b]{90}{GT} \includegraphics[valign=m,width=0.23\linewidth]{2gt.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2gt.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2gt.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2gt.png} } \\ [-2ex] \subfloat{ \rotatebox[origin=b]{90}{Reference} \includegraphics[valign=m,width=0.23\linewidth]{reference_clean.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{rgb_and_blended_reference_mask13_classmean.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{1g.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{rgb_and_blended_reference_mask13_noise50.png} } \\ [-2ex] \subfloat{ \rotatebox[origin=b]{90}{Ours} \includegraphics[valign=m,width=0.23\linewidth]{11_clean.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{rgb_and_blended_11_mask13_classmean.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{rgb_and_blended_11_mask13_blur20.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{rgb_and_blended_11_mask13_noise50.png} } \\ \subfloat{ \rotatebox[origin=b]{90}{RGB} \includegraphics[valign=m,width=0.23\linewidth]{2a.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2b.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2c.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2d.png} } \\ [-2ex] \subfloat{ \rotatebox[origin=b]{90}{GT} \includegraphics[valign=m,width=0.23\linewidth]{2gt_pedestrians.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2gt_pedestrians.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2gt_pedestrians.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2gt_pedestrians.png} } \\ [-2ex] \subfloat{ \rotatebox[origin=b]{90}{Reference} \includegraphics[valign=m,width=0.23\linewidth]{2e.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2f.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2g.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2h.png} } \\ [-2ex] \subfloat{ \rotatebox[origin=b]{90}{Ours} \includegraphics[valign=m,width=0.23\linewidth]{2i.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2j.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2k.png} } & \subfloat{ \includegraphics[valign=m,width=0.23\linewidth]{2l.png} } \end{tabular}~ } \caption{ Qualitative results of our experiments to understand the effect of Painting-by-Numbers. We train the ResNet-50 network backbone on Cityscapes with a standard training schema (i.e., with clean data only, reference model) and with Painting-by-Numbers (our model). \textbf{(top)} The first row shows the original validation image and the corrupted variants for class \textit{car} and the respective ground truth in the second row. We replace either the class texture by the dataset-wide RGB-mean, strongly low-pass filtered the class, or added severe Gaussian image noise. The third row shows the predictions of the reference model. The fourth row shows the predictions of our model. The predictions in the fourth row (our model) are superior to the third row (reference model). Our model is able to withstand the image noise based corruption (last column) for which the reference model confuses \textit{cars} with \textit{traffic signs} mostly. \textbf{(bottom)} For \textit{persons}, the reference model predicts well, when the RGB-mean replaces the texture of the class. Both models are relatively robust when the classes are low-pass filtered by severe Gaussian blur. Similar to the results with respect to class \textit{car}, the reference model struggles to predict well for severe image noise and confuses \textit{persons} also with \textit{traffic signs} mostly } \label{fig:validation_qualitive_results} \end{figure} \section{Conclusions} \label{sec:conclusion} We proposed a simple, yet effective, data augmentation schema (Painting-by-Numbers) for semantic image segmentation in this work. This training schema increases the robustness for a wealth of common image corruptions in a generic way. Painting-by-Numbers corrupts training data so that the texture of image classes becomes less reliable, forcing the neural network to develop and increase its shape-bias to segment the image correctly. Painting-by-Numbers' benefits are that it does not require any additional data, is easy to implement in any supervised segmentation model, and is computationally efficient. It would be interesting to enforce other network biases, such as context bias or layout bias, and even to combine these with a shape bias, to further increase the robustness of semantic segmentation models with respect to common image corruptions. \clearpage \bibliographystyle{splncs04}
{'timestamp': '2020-10-13T02:30:02', 'yymm': '2010', 'arxiv_id': '2010.05495', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05495'}
arxiv
\section{Introduction} A common property of many populational networks is that the degree of connectivity between individuals follows a power law distribution \cite{barabasi1999emergence, giacobini2005takeover, payne2007takeover, payne2008influence, payne2009evolutionary, broido2019scale, reed2002gene}. Experimental results on the dynamics of populational structures have been presented \cite{alba2005exploration, whitacre2008self, clauset2009power}, and a technique that encodes a genealogical history tracing the genetic flow and impact of individuals has revealed the power law with different shapes (or scaling factors) \cite{whitacre2009making}. Several different forms of probability distributions observed in empirical data have been successfully described by Nonextensive Statistical Mechanics \cite{abe2001nonextensive, gell2004nonextensive, tsallis2009introduction}, whose formalism is derived from a proposed generalization of the Boltzmann-Gibbs entropy \cite{tsallis1988possible}. Among these, the $q$-exponential distribution family \cite{picoli2009q} is given by \begin{equation} p_{qe}(x)=p_0\left[1-(1-q)\frac{x}{x_0}\right]^{\frac{1}{1-q}}, \label{eq1} \end{equation} where $x_0$ and $q$ are variable parameters and the inequality $1-(1-q)x/x_0 \geq 0$ and the normalization condition, $p_0=(2-q)/x_0$, must be satisfied. For $q<1$, $p_{qe}$ has finite value for any finite real $x$ since, by definition, $p_{qe} (x)=0$ for $1-(1-q)x/x_0 <0$. For $q>1$, $p_{qe}$ exhibits an asymptotic behavior based on the power law, \begin{equation} p_{qe}(x) \sim x^{-\frac{1}{q-1}}, \end{equation} where the $q$-exponential distribution corresponds to a Burr-type distribution \cite{burr1942cumulative} and to the Zipf-Mandelbrot’s law \cite{mandelbrot1982fractal}. The $q$-exponential distribution is, therefore, a generalization of these distributions, able to represent both the ``heavy tailed'' and the ``light tailed'' distributions. Confirmation of this generalization has been corroborated by several empirical works that addressed diverse subjects, such as the distribution of the population in cities \cite{malacarne2001q}, surnames \cite{yamada2008q}, human behavior \cite{takahashi2011depressive, takahashi2008psychophysics, cajueiro2006note}, circulation of magazines \cite{picoli2005statistical}, delay of trains \cite{briggs2007modelling}, financial markets \cite{politi2008fitting, jiang2008scaling, kaizoji2006interacting, kaizoji2004inflation}, citations in scientific articles \cite{anastasiadis2009characterization, tsallis2000citations}, and even DNA sequences \cite{oikonomou2008nonextensive}. The dynamics of complex populational networks need a theoretical basis to interpret experimental results \cite{alba2005exploration, whitacre2009making, whitacre2008self} and to understand and solve many open problems \cite{payne2013complex}. Studying the models and conjectures around these problems, as in \cite{cipriani2019dynamical}, can help us understand the evolution of social networks \cite{topirceanu2018weighted}, bitcoin networks \cite{holtz2013evolutionary}, and wealth distribution \cite{kondor2014rich}. In this paper, we study the different power law behaving distributions observed in several numerically generated genealogical networks and describe its dynamics over time using Tsallis’s $q$-exponential distribution. Ultimately, we show that the different power law shapes and deviations observed are a product of a time-dependent dynamic evolution that can be described by the $q$-exponential distribution family. \section{Methodology} \label{Methodology} Here, we describe the methodologies necessary to carry out the processes and numerical experiments presented. These include: (1) The creation of genealogical trees in the form of graphs from the genetic and historical information of each individual in several populations; (2) The quantification of the impact of each individual within the family trees; (3) The creation of the correspondent individual impact value probability density distributions; (4) And the determination of the best fitting $q$-exponential curves for each probability density distribution. \subsection{Event Takeover Value (ETV) algorithm} \label{ETV} In population-based optimization algorithms, a good measure of the impact of an individual on the dynamics of the entire population can be obtained by analyzing how said individual, and its offspring, performed in survival and reproduction over the generations. The Event Takeover Value (ETV) algorithm, proposed in \cite{whitacre2009making}, is an algorithm that measures the impact of an individual on the population dynamics through genealogical graphs. Said algorithm is also useful for observing how the genetic material of an individual is able to spread through the future populations. \subsubsection{ETV calculation procedure} Let us consider that, in each generation, $N$ individuals are created. We denote the $i$-th birth by $i$ for $1\leq i \leq N$, and each new generation by $j$ for $1 \leq j \leq t$, where $t$ is the number of generations at the end of each simulation. Like this, any individual in the family tree can be represented by $(i,j)$, and it is possible to count the number of individuals in the population who are historically connected to any ancestor in any generation. The number of individuals historically connected to the $(i,j)$ ancestor, after $k$ generations subsequent to $j$ (where $j \leq k \leq t$), represents the impact of this individual on the $j+k$ generation, denoted by $\iota=ETVgen(i,j,k)$. In the genealogical graph, $\iota$ also represents the number of links from the $(i,j)$ individual to individuals descended from this one in the $j+k$ generation. So, the maximum dissemination power of the genetic material, for any $(i,j)$ individual, is the maximum $ETVgen$ for all $t-j$ subsequent generations after its creation, \begin{equation} ETV_{i,j}(t)=max\{ETVgen(i,j,k)\}_{k=j+1}^{t}. \end{equation} By definition, note that: (1) The $ETV_{i,j}(t)$ value is always greater than or equal to 1, and is limited by the number of individuals in the population in each generation. Also, since we consider that every generation has $N$ individuals\footnote{In cases where the generations do not have a fixed number of individuals, the $ ETV_{i,j}(t)$ value will be limited to the number of individuals in the generation with the larger population.}, $1\leq ETV_{i,j}(t)\leq N$; (2) At each new generation, the $ ETV_{i,j}(t)$ value is updated, therefore it is dependent on the number of generations at the end of each simulation, $t$. This characteristic is essential to observe the power law dynamics thereof. \subsubsection{ETV frequency measurement} If we denote by $n(x)$ the number of individuals with $ETV_{i,j}(t)=x$ and $\cal N$ the number of individuals in the genealogical network, then the frequency of the $x$ value, $n(x)/{\cal N }$, approximates the probability of $ETV_{i,j}(t)=x$, \begin{equation} \text{Pr}[ETV_{i,j}(t)=x]\sim\frac{n(x)}{\cal N }. \end{equation} If the number of individuals in each generation\footnote{If the number of individuals generated in each generation is not fixed, then ${\cal N}=\sum_{j=1}^{N} N_j$, where $N_j$ is the number of individuals created in the $j$-th generation.} is $N$, then ${\cal N}=Nt$. To increase the reliability on the $n(x)/{\cal N }$ frequency, we must use the law of large numbers. Like this, we can run the algorithm $R$ times and calculate a more reliable frequency to approximate the probability, \begin{equation} \text{Pr}[ETV_{i,j}(t)=x] \approx \frac{\sum_{r=1}^{R} n_r(x)}{\sum_{r=1}^{R} {\cal N}_r }, \label{freq} \end{equation} where $n_r(x)$ is the number of individuals with $ETV_{i,j}(t)=x$ and ${\cal N}_r$ is the number of individuals in the $r$-th family tree. In our simulations we use $R=20$. \subsubsection{Genetic hitchhiking} The genetic hitchhiking, effect in which the impact of an individual on a population is shared with its ancestors, was here disregarded since it may not reflect the reality of many phenomena found in populational networks. For example, under the ETV metric, Genghis Khan was a very high-impact individual in the Asian population \cite{zerjal2003genetic, derenko2007distribution}. If we consider the effect of genetic hitchhiking, his parents, grandparents, and other ancestors would also have the same impact. This approach can be useful in other contexts, where only the individual impact is not enough and the weight of genetic contribution must be shared by the individuals' ancestors. However, in many populational networks, the ascendants' contribution is limited only to generating the individual with the greatest impact, not causing significant direct contributions in the generations in which they were alive. Thus, in our numerical experiments, genetic hitchhiking is disregarded through an ancestrality detachment mechanism\footnote{For more details on the genetic hitchhiking effect, and how to eliminate it, the reader should consult \cite{whitacre2009making}.}. \subsection{Genetic algorithm} \label{GA} In \cite{whitacre2009making}, the authors conducted experiments using evolutionary algorithms to analyze the resulting ETV distributions for several well-known test problems. In their results, it was found that genealogical networks are little sensitive to the number of individuals in a population or the fitness landscape on which evolution occurs. On the other hand, the population updating strategy and several conversion delaying mechanisms were found to contribute to the observation of power law deviations in the population dynamics. Especially so when combined. In order to cover the conditions necessary for the formation of the power law and its more severe deviations \cite{whitacre2009making,albert2002statistical}, we employ similar experiments to those shown in \cite{whitacre2009making} while using different test problems, different population updating strategies, and different conversion delaying mechanisms. More specifically, we implemented a genetic algorithm (GA) with the following settings: \begin{itemize} \item Traveling salesman problems as main test problems. \item Fixed population of 100 individuals. \item Roulette selection. \item Crossover by direct analysis of the ``genetic code'' of the involved individuals. \item Severe mutation mechanics. \item Analysis with the use or disuse of elitism. \item Insertion of historically uncoupled individuals. \item Implementation of aging and maximum edge limitation. \end{itemize} \subsubsection{Traveling salesman problems as main test problems} The Traveling Salesman Problem (TSP) is a combinatorial optimization problem based on determining the shortest distance circuit to go through a number of points, passing only once at each point and finishing the circuit at the starting point. It is one of the most famous problems in computational mathematics that has numerous direct applications but still lacks an effective solution method for the general case. Of particular interest to us is the fact that, in a TSP, individuals are represented by its route (a numerical combination of points), which, given a big enough number of points, can act as a ``genetic code'' in our analyzes. This allows us to track when and which ``traits'' of an individual are being spread through the future populations in the genealogical graphs. Further, the TSP presents several characteristics of power law behaving complex systems such as unclear or multiple optimal solutions, unknown complexity, and non-linear dynamics. \subsubsection{Fixed population of 100 individuals} In \cite{whitacre2009making}, the authors show that genealogical network dynamics are little sensitive to the number of individuals in a population. Knowing this, we work with a fixed population of 100 individuals per generation. In each new generation, 100 new individuals are ``born'' and may take the place of the individuals of the previous generation depending on the use of elitism and its fitness value. \subsubsection{Roulette selection} The selection of individuals for reproduction (crossover) is realized through roulette selection, a method in which individuals with higher fitness are more likely to be selected. This selection method reproduces reasonably well the concept of preferential attachment in its most general form\footnote{Concept in which new network nodes (individuals) are more likely to interact with the nodes with the higher annexation probabilities (usually of higher fitness). This effect is present in several real complex systems, and it plays an important role in the development of free-scale networks with power law structures \cite{barabasi1999emergence, broido2019scale}.} \cite{newman2003structure, albert2002statistical}. \subsubsection{Crossover by direct analysis of the ``genetic code'' of the involved individuals} The crossover method employed was the Enhanced Edge Recombination (EER) method\footnote{The EER, while more time-consuming and of more difficult implementation, is generally superior when compared to the Order 1, Order Multiple, and PMX crossover methods. Detailed descriptions on the operation and implementation of the EER method are available in \cite{merz2002comparison, larranaga1999genetic}.}, a TSP crossover method that uses information from the genetic links of the parents in the creation of the offspring. We chose this method due both to the easiness in determining the dominant parent (necessary for the calculation of $ETVgen$), through direct analysis of the genetic links of the parents and their offspring, as well as the intrinsic characteristic of the method in reducing the amount of ``implicit mutations'' during the crossover process. The smaller the number of ``implicit mutations'', the greater is our control over the number of historically uncoupled individuals, and the more accurate will be our analyzes of the population dynamics when considering these cases. The EER method was employed with a probability of 0.9. \subsubsection{Severe mutation mechanics} The mutation method chosen was the sub-string inversion mutation, where a string of 2 or more genes is randomly chosen and inverted in the individual's code, here employed with a probability of 0.05. This method was chosen due to its great variability capacity and additional algorithm conversion delay. \subsubsection{Analysis with the use or disuse of elitism} Several evolutionary algorithms used in research papers focused on power law behaviors use elitism as default. Elitism, or elitist selection, is a population updating mechanic that guarantees that the population fitness in the GA will not decrease from one generation to the next\footnote{This is achieved by comparing the fitness values of the parents and their offspring after reproduction. If the fitness value of the offspring is lower than that of the parent, then the offspring is discarded, and the parent takes its place in the next generation.}. Elitism is a mechanic that, while greatly increasing the conversion speed, also inevitably causes power law deviations since, at minimum, a significant number of low-impact individuals are prevented from existing. We will analyze the influence of elitism's use (or disuse) in the populations and power law dynamics. \subsubsection{Insertion of historically uncoupled individuals} In order to cause even more ``disturbance'' and cover the cases in which the power law deviates the most \cite{whitacre2009making}, we implemented two mechanisms for the insertion of historically uncoupled individuals. (1) The first occurs in the genetic hitchhiking elimination process, in which some individuals are detached from their ancestors and then considered as ``new'', history-less individuals. (2) The second mechanism occurs using a custom method. This method consists of analyzing, at each generation, the number of times in which each new individual and its reverse\footnote{Keep in mind that here an individual is a route. As an example, for a 4-point TSP, 1-3-2-4-1 is a valid individual, and its reverse is 1-4-2-3-1.} are repeated. If an individual is present in the population more than once, but its reverse is not present, one of these repeated individuals is replaced by its reverse (which has different coding but the same fitness value). So, whenever an individual of a different genetic code is acquired and repeated, its reverse is created and inserted into the population. In this way, we guarantee that there will always be two or more different ``genes'' dominating the population. This process increases diversity and decentralizes the dominance of the fittest individuals. The increased diversity occurs simply because different individuals are being inserted into the population (genetically/historically uncoupled individuals). As for the dominance decentralization, the fact that these individuals are different, but have the same fitness as their original reverse, causes a trend of dominance by these individuals to arise in distinct portions of the population. So, new individuals with the same fitness acquire a portion of the population to dominate in the next generations. \subsubsection{Implementation of aging and maximum edge limitation} According to \cite{albert2002statistical}, aging and maximum edge limitation are mechanics that cause deviations from the power law behavior. For the aging mechanism, we set a maximum age limit, $m$, up to which each individual may stay alive. An individual dies by being replaced by its offspring. For the maximum edge limitation mechanism, we limit the number of links between individuals in the genealogical networks, i.e., we limit the maximum $ETVgen$ an individual might attain. \bigskip With these settings, we can implement a genetic algorithm (GA) that solves several symmetrical TSPs while storing the necessary information to construct genealogical trees. These genealogical trees will be evaluated using the ETV algorithm (section \ref{ETV}), and the resulting impact value probability distributions can be analyzed. \subsection{$q$-exponential fitting method} \label{Dfm} Investigating the power law evolutionary dynamics in the resulting $\text{Pr}[ETV_{i,j}(t)=x]$ distributions (or $ETV_{i,j}(t)$ probability distributions) will require us to determine the best-fitting $p_{qe}(x)$ curves across all $t$ generations. In this section, we demonstrate the method employed to calculate the values of the $q$, $x_0$, and $p_0$ parameters for each $p_{qe}(x)$ curve. For simplicity of notation, we will represent $\text{Pr}[ETV_{i,j}(t)=x]$ by PETV, $ETV_{i,j}(t)$ by ETV, and $p_{qe}(x)$ by $p_{qe}$. Let us use the genetic algorithm described in section \ref{GA} to exemplify the $q$-exponential fitting method employed. Disregarding elitism and taking a generation limit of $t=100$ generations, we can perform $R=20$ simulations\footnote{Generating 20 genealogical networks of 10000 individuals (100 individuals per generation in 100 generations).} and calculate the ETV values for each individual. Now, we calculate the frequency of each ETV value using Equation \ref{freq} and create the corresponding probability density distributions. For visualization purposes, we apply the $q$-logarithm function, defined as $ln_q(x) \equiv [x^{(1-q)} - 1]/(1- q)$, with $ln_1x \equiv ln(x)$, in the calculated probabilities. If the distribution fits a $q$-exponential function, then there is a pair of values $(q,x_0)$ in which the data will be adjusted on a straight line \cite{picoli2009q}. Applying the $ln_q(x)$ function on both sides of Equation \ref{eq1}, we obtain \begin{equation} ln_q \;p_{qe}(x)=ln_q\; p_0 -[1+(1-q)ln_q\; p_0]\frac{x}{x_0}. \end{equation} Since $p_0=(2-q)/x_0$ (normalization condition, see Equation \ref{eq1}), determining the values of $q$ and $x_0$ will now consist of verifying at which point the most number of higher frequency ETVs best tend to concentrate on a straight line. Figure \ref{fig1} a) presents the resulting PETV distribution (average of 20 simulations) and the best-fitting $ln_{q}\; p_{qe}$ curve for $q=1.19$, $p_0=1.0421$, and $x_0=0.7773$. The traditional method for illustrating the power law is, however, through log-log scale plots in which straight asymptotes are drawn on to illustrate the power law. We will therefore adopt the log-log scale representation in all of our next plots, making it so that our results can be compared to those divulged in other similar articles in the literature. Like this, in Figure \ref{fig1} b), where we now use log-log scale instead of $q$-logarithm scale, note that there is a concavity in the distribution and that the $q$-exponential distribution adjusts the data reasonably well in all ETV values. \begin{figure}[!ht] \centering \includegraphics[scale=0.55]{Figure1} \caption{\textbf{$\times$ markers:} mean values of a) $ln_{q}$PETV vs. ETV, and b) PETV vs. ETV, in 20 simulations. \textbf{Red curves:} a) resulting $ln_{q}\; p_{qe}$ curve (exhibited in $q$-logarithm scale), and b) resulting $p_{qe}$ curve (exhibited in log-log scale), for $q=1.19$, $p_0=1.0421$, and $x_0=0.7773$.} \label{fig1} \end{figure} This process can be reproduced for several other configurations, using or disusing several other mechanisms, allowing us to study the resulting power law dynamics and how each employed mechanism influences it. \section{Results} In this section, we exhibit the power law dynamics observed in the genealogical networks generated with the genetic algorithm described in section \ref{GA}. The conditions for constructing the genealogical networks, PETV distributions, and corresponding best-fitting $p_{qe}$ curves are the same as the example in section \ref{Dfm}. Using as reference the data available in TSPLIB \cite{reinelt1991tsplib}, we ran the GA on several TSP problems (varying from 14 to 42 points), generated the correspondent PETV distributions, and analyzed the resulting power law dynamics over time. We obtained very similar results for all problems tested\footnote{As expected, since genealogical networks have been found be little sensitive to the fitness landscape on which evolution occurs \cite{whitacre2009making}.}. Here, we will present the results for the most complex problem tested, swiss42 (42 cities Switzerland), divided into two parts. The first part shows the results obtained while not using elitism. The second part shows the results obtained while using elitism and other mechanisms. Finally, we compare the power law dynamics observed in both cases and discuss the influence of elitism and other mechanisms. \subsection{First experiment} \label{SemEl} In our first experiment, we disregarded elitism and ran the GA up to $t = 500$ generations. After 20 runs (thus generating 20 genealogical graphs of 50000 individuals each), we analyzed the impact of all individuals in all populations across all generations. We calculated the ETV occurrence probability values (PETV) and plotted the resulting probability density distributions in fifteen generation intervals. Finally, we determined the best-fitting $q$-exponential curves for each interval and plotted these over the probability density distributions. The results can be seen in Figure \ref{fig2}, where we exhibit the obtained PETV vs. ETV distributions and its respective best-fitting $p_{qe}$ curves. \begin{figure}[!ht] \centering \centerline{\includegraphics[scale=0.55]{Figure2}} \caption{PETV vs. ETV distributions (blue markers) and best-fitting $p_{qe}$ curves (red curves) for a) $t = 25$, b) $t = 30$, c) $t = 35$, d) $t = 40$, e) $t = 50$, f) $t = 67$, g) $t = 85$, h) $t = 100$, i) $t = 125$, j) $t = 150$, k) $t = 200$, l) $t = 250$, m) $t = 335$, n) $t = 400$, and o) $t = 500$ generations. p) Best-fitting $p_{qe}$ curves for $t = 25$, $t = 40$, and $t = 500$ generations. Note that, over time, there is a progressive increase in the frequency of occurrence of higher ETV values. Also note that the distribution becomes less concave over the generations. From generation 500 on, variations in the shape of the distribution are almost imperceptible.} \label{fig2} \end{figure} In analyzing Figure \ref{fig2}, first observe that the behavior pattern of these distributions can be satisfactorily represented by a family of $q$-exponential curves (where a good fit can be made with the appropriate $q$, $p_0$, and $x_0$ values) at any generation. Also note that, without elitism, a slow evolution process occurs. This is evidenced by the fact that, after 500 generations, the maximum ETV value achieved was only 38 (on a scale of 1 to 100). As for the distribution dynamics, note that there is a progressive increase in the frequency of occurrence of higher and higher ETV values as generations pass. This leads to an increase in the number of points of the distribution and to the lifting of its tail (see Figure \ref{fig2} p)) due to the increasingly larger PETV values in higher ETV positions. This process makes the distribution less and less concave (or more and more straight) over time. This ``straightening'' speed is more pronounced in the first generations and decreases in intensity (and tends to saturate) as the population evolves. \begin{figure}[!ht] \centering \includegraphics[scale=0.5]{Figure3} \caption{Evolution of the maximum average ETV values, calculated $p_{qe}$ parameters, $q$ and $x_0$, and corresponding power law scaling factors, $\gamma$, over the generations. \textbf{$\times$ markers:} values obtained for 25, 30, 35, 40, 50, 67, 85, 100, 125, 150, 200, 250, 335, 400 and 500 generations. \textbf{Red curves:} best-fitting interpolating curves.} \label{fig3} \end{figure} The power law dynamics require that the values of the $q$, $x_0$, and $p_0$ parameters be adjusted at each generation. In Figure \ref{fig3}, we exhibit the evolution of the maximum average ETV values, the variation of the $q$ and $x_0$ parameters on the $p_{qe}$ curves, and the corresponding power law scaling factors, $\gamma$, over the generations\footnote{$p_0=(2-q)/x_0$ due to normalization. The asymptotic form of the $q$-exponential is $x^{-\gamma}$, where $\gamma=1/(q-1)$.}. Note that there is a regularity in the observed values ($\times$ markers), which allows us to fit these into $f(t)=at^b+c$ functions, where $t$ is the generation value, and $a$, $b$, and $c$ are the interpolation parameters. Also note that the $q$ curve is positively correlated to the maximum average ETV curve, whereas the $x_0$ and $\gamma$ curves are negatively correlated to the maximum average ETV and $q$ curves. The best-fitting parameters and regression values for the interpolating curves in Figure \ref{fig3} are shown in table \ref{tab1}. \begin{table}[!ht] \centering \caption{$a$, $b$, $c$ parameters and regression, R, for the best-fitting $ETV$, $x_0$, $q$, and $\gamma$ interpolating curves obtained. Fitting function: $f(t)=at^b+c$.} \begin{tabular}{|c|c|c|c|c|}\hline Parameters & $a$ & $b$ & $c$ & R \\ \hline ETV & -74.2 & -0.2435 & 50.35 & 0.983 \\ \hline $x_0$ & 8.038 & -1.525 & 0.7696 & 0.984 \\ \hline $q$ & -6.306 & -1.527 & 1.196 & 0.988 \\ \hline $\gamma$ & 795.3 & -1.941 & 5.169 & 0.992 \\ \hline \end{tabular} \label{tab1} \end{table} After analyzing the variation ratios shown in Figure \ref{fig3}, we realize that the large variations in the $q$ and $x_0$ parameters (between generations $t=25$ and $t=150$) are due to a decreasingly rapid emergence of individuals with higher ETV values in this interval. As the emergence of higher impact individuals decreases (generation 150 onwards), a regime is reached, and changes in the distribution shape occur very slowly (with a maximum average ETV variation of only 4 points between generations $t=250$ and $t=500$). Comparing these results to the $p_{qe}$ curves in Figure \ref{fig2} shows us that intervals of higher variation ratios (earlier generations) correspond to the most concave $p_{qe}$ curves, whereas the intervals of lower variation ratios (later generations) correspond to the least concave (or straighter) $p_{qe}$ curves. For every simulation, the power law dynamics observed using the $q$-exponential curves is that of initially concave lines that become more and more straight over time. This ``straightening’’ speed is higher in the first generations but tends to decrease in intensity and gradually stagnate. \subsection{Second experiment} Aging and maximum edge limitation provide similar results in causing power law deviating behaviors \cite{albert2002statistical}. Since, in our case, maximum edge limitation mostly only impacts the number of points of the distribution, we will only show the results obtained with the aging mechanism. For our second experiment, we employ the same configurations used in the first experiment, with the sole exception of the use of elitism and/or the aging mechanism. The results can be seen in Figure \ref{fig4}, where we exhibit the obtained PETV vs. ETV distributions for $t=25$ and $t=500$ generations, and its respective best-fitting $p_{qe}$ curves. The remaining curves, including the $t=40$ shown in the first experiment (Figure \ref{fig2} p)), were omitted here to not overly ``pollute'' the figure, but they also presented very similar fits. The evolution of the maximum average ETV values, the variation of the $q$ and $x_0$ parameters on the $p_{qe}$ curves, and the corresponding power law scaling factors, $\gamma$, over the generations were similar to those shown in Figure \ref{fig3}. \begin{figure}[!ht] \centering \includegraphics[scale=0.55]{Figure4} \caption{ \textbf{$\times$ markers:} mean values of PETV vs. ETV at $t = 25$ and $t = 500$ generations. \textbf{Red curves:} best-fitting $p_{qe}$ curves at $t = 25$ and $t = 500$ generations. Average of 20 simulations. a) Use of elitism and fast-aging ($m = 2$). At $t = 25$ generations, the calculated $p_{qe}$ parameters are $q = 1.25$ and $x_0 = 0.665$, and the corresponding power law scaling factor is $\gamma = 4$. At $t = 500$ generations, the calculated $p_{qe}$ parameters are $q = 1.35$ and $x_0 = 0.635$, and the corresponding power law scaling factor is $\gamma = 2.8571$. b) Use of elitism only. At $t = 25$ generations, the calculated $p_{qe}$ parameters are $q = 1.26$ and $x_0 = 0.795$, and the corresponding power law scaling factor is $\gamma = 3.8462$. At $t = 500$ generations, the calculated $p_{qe}$ parameters are $q = 1.345$ and $x_0 = 0.625$, and the corresponding power law scaling factor is $\gamma = 2.8986$. } \label{fig4} \end{figure} In analyzing Figure \ref{fig4}, first note that the behavior pattern of these distributions can, once again, be satisfactorily represented by $q$-exponential curves. Second, note that, in both cases, maximum ETV value is achieved at $t=500$ generations. A closer analysis will show that maximum ETV value was achieved as soon as generation $t=250$ with or without aging. This result shows us that the use of elitism, by itself, caused an accelerated emergence of the power law (that is, a rapid ``straightening" in the $q$-exponential curve). In fact, elitism sped up this ``straightening" so much that, compared to the curves in the first experiment, generation $t = 15$ with elitism is already as ``straight" as generation $t = 250$ without elitism. This difference increases with the number of generations until it reaches a saturation limit for both. A visual representation of how much elitism affected the power law dynamics here is shown in Figure \ref{fig5}, where we plot the PETV vs. ETV distributions and corresponding best-fitting $p_{qe}$ curves at generation $t = 500$ for both experiments. \begin{figure}[!ht] \centering \includegraphics[scale=0.5]{Figure5} \caption{Comparison between the PETV vs. ETV distributions ($\times$ markers) and corresponding best-fitting $p_{qe}$ curves at $t = 500$ generations for both experiments. Fitting parameters and corresponding power law scaling factors: $q = 1.194$, $x_0 = 0.773$, $p_0 = 1.042$, $\gamma = 5.1546$ (dark red curve) and $q = 1.350$, $x_0 = 0.635$, $p_0 = 1.040$, $\gamma = 2.8571$ (blue curve).} \label{fig5} \end{figure} A comparative analysis on the graphs in Figure \ref{fig4} shows that the use of aging caused an initial difference in ``straightness'' in the earliest generations, meaning that power law emerged faster without aging. This difference diminishes along the generations, and the two distributions become similar after saturation. In fact, at $t = 500$ generations, both best-fitting $p_{qe}$ curves are almost identical. The main difference between both graphs is the appearance of several ``strange points" at the tail of the distribution (highlighted by the red circle), representing a paradoxical high probability of appearance of individuals of the highest impact. This anomaly also appears in most of the results presented in \cite{whitacre2009making}. A closer analysis of the populations across all generations shows that this anomaly appears as soon as fitness balance\footnote{Fitness balance is the state in which all individuals in the population have the same fitness value.} is achieved. At this point, elitism ``kills'' any new offspring, genetic variability is lost in the population, and the evolution process is finished with only clones being added to the population. This result is an indication that the use of elitism can lead to misleading insights unless other restrictive mechanisms (such as fast-aging) are employed, or the simulation is stopped as soon as genetic variability is lost (which can be tricky, since fitness plateaus, followed by fast evolution, are sometimes common on more complex problems). Finally, from Figures \ref{fig4} and \ref{fig5}, note the difference in the values of the corresponding power law scaling factors in both experiments. Without elitism, $\gamma = 5.1546$ at $t = 500$ generations. With elitism, $\gamma = 2.8571$ (with aging) or $\gamma = 2.8986$ (without aging), at $t = 500$ generations. The scaling factors obtained using elitism are now in the typical range of $2 \leq \gamma \leq 3$ \footnote{Save the occasional exception, the power law scaling factor typically lies in the range of $2 \leq \gamma \leq 3$ \cite{clauset2009power}.}. This result is further indication that the use of elitism can significantly influence the power law dynamics in population-based optimization algorithms. \section{Discussion} \subsection{Similarity to research based on empirical data} Several papers in the literature present evidence that real complex systems follow a $q$-exponential power law \cite{malacarne2001q, yamada2008q, takahashi2011depressive, takahashi2008psychophysics, cajueiro2006note, picoli2005statistical, briggs2007modelling, politi2008fitting, jiang2008scaling, kaizoji2006interacting, kaizoji2004inflation, anastasiadis2009characterization, tsallis2000citations, oikonomou2008nonextensive}. In our experiments, we implemented several of the conditions found in real complex networks, such as unclear or multiple optimal solutions, preferential attachment, mutation, reproduction by gene recombination, and aging \cite{barabasi1999emergence, amaral2000classes, albert2002statistical}. We also incorporated several of the mechanisms reported to cause significant power law deviations, such as the severe mutation, insertion of historically uncoupled individuals, maximum edge limitation, and fast aging \cite{albert2002statistical}. Ultimately, we verified that the observed individual impact value probability distributions could be satisfactorily modeled, at any point, by $q$-exponential curves. These $q$-exponential curves presented concavities very similar to those highlighted in \cite{whitacre2009making, albert2002statistical} (see Figure \ref{fig4} a)) and in several other papers based on empirical data \cite{malacarne2001q, yamada2008q, takahashi2011depressive, takahashi2008psychophysics, cajueiro2006note, picoli2005statistical, briggs2007modelling, politi2008fitting, jiang2008scaling, kaizoji2006interacting, kaizoji2004inflation, anastasiadis2009characterization, tsallis2000citations, oikonomou2008nonextensive, redner1998popular, seglen1992skewness, solow2003testing, clauset2009power} (see Figure \ref{fig2} and Figure \ref{fig4} b)). Elitism, as applied in evolutionary algorithms, rarely occurs in the real world. In our numerical experiments, we found that, without elitism, populations evolve more slowly and randomly, but genetic variability is generally higher (more diverse populations). We also found this to be the situation in which we achieved our best $q$-exponential data fittings at any stage of evolution. The maintenance of this distribution shape from early generations to a nearly stationary regime (population stabilization) resembles many results observed in empirical data from real population structures \cite{malacarne2001q, yamada2008q, takahashi2011depressive, takahashi2008psychophysics, cajueiro2006note, picoli2005statistical, briggs2007modelling, politi2008fitting, jiang2008scaling, kaizoji2006interacting, kaizoji2004inflation, anastasiadis2009characterization, tsallis2000citations, oikonomou2008nonextensive, redner1998popular, seglen1992skewness, solow2003testing, clauset2009power}. \subsection{Power law dynamics} The emergence of a power law distribution implies that most individuals have a negligible impact on population dynamics and do not provide useful information (i.e., act as noise). In several research papers, particularly in \cite{whitacre2009making, albert2002statistical}, the authors analyze the behavior of empirical and/or artificial data distributions under various configurations and observe the emergence and ``breakdown" of power law behaviors under one condition or another. In general, at the end of these analyzes, the authors conclude that most systems analyzed initially do not have population dynamics defined by a power law, but over the generations, or under specific conditions, the system evolves to reach that state. In our work, we obtain very similar results, but we analyze them from a different perspective. Instead of using a conventional power law curve, we used Tsallis's $q$-exponential distribution (a generalization of the power law) and noticed that cases previously understood as ``power law deviations'' fit perfectly into a family of $q$-exponential curves. We found that $q$-exponential functions could satisfactorily model the power law dynamics throughout the entire process (from the first to the last generations) by simply adjusting its $q$ and $x_0$ parameters. Both these parameters and its corresponding power law scaling factors, $\gamma$, are time-dependent and follow a $f(t)=at^b+c$ pattern, where $t$ is the number of generations. These results provide further evidence that nonextensive statistics and scale-free networks are intimately related (connection conjectured in \cite{tsallis2004should} and discussed in \cite{soares2005preferential}). They also imply that power law behavior stands true regardless of many previously reported ``power law deviating'' mechanisms employed, but its shape is time-dependent. \section{Conclusion} \label{Conc} Power law is a statistical phenomenon found in many population samples. Power law behavior with several different shapes can also be observed in genealogical networks. In this paper, we investigated the dynamics and relation to population evolution over time of power law behaving probability distributions observed in numerically generated genealogical networks. First, we used a genetic algorithm to generate several genealogical graphs and measured the impact of all individuals in all populations across all generations. Then, we analyzed the resulting individual impact value probability distributions and studied the dynamics of evolution of said populations through nonextensive statistics. Like this, we verified that the emergence of power law in these distributions has a dynamic behavior over time. This dynamic development can be well described by a family of $q$-exponential distributions in which the $q$ and $x_0$ parameters follow a $f(t)=at^b+c$ pattern. Finally, we discussed the use of elitism and other restrictive mechanisms and their effects on the power law dynamics. We found that elitism, while a valuable tool that boosts conversion speed, also dramatically influences the observed power law dynamics, sometimes even creating strange anomalies that could lead to misleading insights. The results presented in this paper are important and have many implications. First, they indicate that the causes responsible for the formation of the power law are also dynamically changing within the genealogical network. Second, they provide evidence that power law behavior stands true regardless of many previously reported ``power law deviating'' mechanisms employed. Third, they show that the different power law shapes (with several scaling factors) and deviations observed in our genealogical networks are, in fact, static images of a time-dependent dynamic development that can be described using $q$-exponential distributions. Fourth, they imply that the different power law shapes and deviations reported in similar papers may also be static images of a time-dependent dynamic development. Fifth, they show that elitism (commonly used as default in population-based optimization algorithms) significantly influences the power law scaling factors and deviations observed. Finally, they provide further evidence for the conjecture that relates nonextensive statistical mechanics with complex networks. \section*{Declaration of competing interest} The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper. \section*{Data availability} Data underlying the results presented in this paper are not publicly available at this time but may be obtained from the authors upon reasonable request. \bibliographystyle{IEEEtran}
{'timestamp': '2022-03-08T02:05:10', 'yymm': '2010', 'arxiv_id': '2010.05463', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05463'}
arxiv
\section{Introduction} Human language\footnote{In this work we focus on English.} is a complex system, involving an intricate interplay between meaning (“semantics”) and structural rules between words and phrases (“syntax”). Self-supervised neural sequence models for text trained with a language modeling objective, such as ELMo \citep{elmo}, BERT \citep{bert}, and RoBERTA \citep{roberta}, were shown to produce representations that excel in recovering both structure-related information \citep{gulordava2018LMagreement, vanschijndel2018gardenpath, wilcox2018fillergap, goldberg2019} as well as in semantic information \citep{bert-questions, joshi2019bert}. \begin{figure}[t] \centering \includegraphics[width=1\linewidth]{plots/model.png} \caption{An illustration of triplet-loss calculation. Pairs of words are represented by the difference between their transformation $f$, which is identical for all words. The pairs of words in the anchor and positive sentences are lexically different, but structurally similar. The negative example presented here is especially challenging, as it is lexically similar, but structurally different.} \label{fig:triplet-loss} \end{figure} In this work, we study the problem of disentangling structure from semantics in neural language representations: we aim to extract representations that capture the structural function of words and sentences, but which are not sensitive to their content. For example, consider the sentences: \begin{enumerate} \item Neural networks are interesting. \item I study neural networks. \item Maple syrup is delicious. \item John loves maple syrup. \end{enumerate} \noindent While (1) and (3) are different in content, they share a similar structure, the corresponding words in them, while unrelated in meaning,\footnote{We focus on lexical semantics.} serve the same function. Similarly for sentences (2) and (4). In contrast, sentence (1) shares the phrase \emph{neural networks} with sentence (2), and \emph{maple syrup} is shared between (3) and (4).\footnote{There is a syntactic distinction between the two, with ``maple" being part of a noun compound and ``neural" being an adjective. However, we focus in their similarity as noun modifiers in both phrases.} While the two occurrences of each phrase share the meaning, they are used in different structural (syntactic) configurations, serving different roles within the sentence (appearing in subject vs object position).\footnote{These differences in syntactic position are also of relevance to language modeling, as different positions may pose different restrictions on the words that can appear in them.} We seek a representation that will expose the similarity between ``networks'' in (1) and ``syrup'' in (2), while ignoring the similarity between ``syrup'' in (2) and ``syrup'' in (4). We seek a function from contextualized word representations to a space that exposes these similarities. Crucially, we aim to do this in an unsupervised manner: we do not want to inform the process of the kind of structural information we want to obtain. We do this by learning a transformation that attempts to remove the lexical-semantic information in a sentence, while trying to preserve structural properties. Disentangling syntax from lexical semantics in word representations is a desired property for several reasons. From a purely scientific perspective, once disentanglement is achieved, one can better control for confounding factors and analyze the knowledge the model acquires, e.g. attributing the predictions of the model to one factor of variation while controlling for the other. In addition to explaining model predictions, such disentanglement can be useful for the comparison of the representations the model acquires to linguistic knowledge. From a more practical perspective, disentanglement can be a first step toward controlled generation/paraphrasing that considers only aspects of the \textit{structure}, akin to the style-transfer works in computer vision, i.e., rewriting a sentence while preserving its structural properties while ignoring its \textit{meaning}, or vice-versa. It can also inform search-based application in which one can search for ``similar'' texts while controlling various aspects of the desired similarity. To achieve this goal, we begin with the intuition that the structural component in the representation (capturing the \emph{form}) should remain the same regardless of the lexical semantics of the sentence (the \emph{meaning}). Rather than beginning with a parsed corpus, we automatically generate a large number of structurally-similar sentences, without presupposing their formal structure (\S\ref{sec:sentences-generation}). This allows us to pose the disentanglement problem as a metric-learning problem: we aim to learn a transformation of the contextualized representation, which is \textit{invariant} to changes in the lexical semantics within each group of structurally-similar sentences (\S\ref{sec:triplet-loss}). We demonstrate the structural properties captured by the resulting representations in multiple experiments (\S\ref{sec:experiments}), among them automatic identification of structurally-similar words and few-shot parsing. We release our code at \url{https://github.com/shauli-ravfogel/NeuralDecomposition}. \section{Related Work} The problem of disentangling different sources of variation has long been studied in computer vision, and was recently applied to neural models \citep{bengio-representation-learning, lecum-disentangling, hadad-disentanglement}. Such disentanglement can assist in learning representations that are invariant to specific factors, such as pose-invariant face-recognition \citep{pose-invariant} or style-invariant digit recognition \citep{digits-style}. From a generative point of view, disentanglement can be used to modify one aspect of the input (e.g., ``style''), while keeping the other factors (e.g., ``content'') intact, as done in neural image style-transfer \citep{image-style-transfer}. In NLP, disentanglement is much less researched. In controlled natural language generation and style transfer, several works attempted to disentangle factors of variation such as sentiment or age of the writer, with the intention to control for those factors and generate new sentences with specific properties \citep{sohn2015learning, ficler2017controlling, lample2018multiple}, or transfer existing sentences to similar sentences that differ only in the those properties. The latter goal of style transfer is often realized by learning representations which are invariant to the controlled attributes \citep{fu2018style, HuControlledGeneration}. Another main line of work which is relevant to our approach is that of probing. The concept, originally introduced by \citet{diagnostic1} and \citet{diagnostic2}, relies on training classifiers (probes) to expose symbolic linguistic information that is encoded in the model. A large body of works have shown sensitivity to both semantic \cite{nlp-bert-pipeline-tenney,richardson2019probing} and syntactic \cite{tenney2018what,lin2019open,reif2019visualizing,structural-probe,liu2019linguistic} information. \citet{structural-probe} demonstrated that it is possible to train a linear transformation, under which squared euclidean distance between transformed contextualized word vectors correspond to the distances between the respective words in the syntactic tree. \citet{Eisner-IB} have used a variational estimation method \citep{variational-IB} of the information-bottleneck principle \citep{tishby2000information} to extract word embeddings that are useful to the end task of parsing. While impressive, those works presuppose a specific syntactic structure (e.g. annotated parse tree) and use this linguistic signal to learn the probe in a supervised manner. This approach can introduce confounding between \emph{extracting} information and \emph{learning} it by the probe \citep{Hewitt-control, probing-probing, probe-parser,amnesic-probing:2020}. In contrast, we aim to \emph{expose} the structural information encoded in the network in an unsupervised manner, without pre-supposing an existing syntactic annotation scheme. \subsection{Goal} \section{Method} Our goal is to learn a function $f : \mathbb{R}^n \mapsto \mathbb{R}^m$, which operates on contextualized word representations $x$ and extracts vectors $f(x)$ which make the structural information encoded in $x$ more salient, while discarding as much lexical information as possible. In the sentences ``Maple syrup is delicious'' and ``Neural networks are interesting'', we want to learn a function $f$ such that $f(v^3_{\text{syrup}})$ $\approx$ $f(v^1_{\text{networks}})$, where $v^i_{\text{word}}$ is the contextualized vector representation of the word in sentence $i$. We also want $f(v^4_{\text{syrup}})$ $\approx$ $f(v^2_{\text{networks}})$, while keeping $f(v^1_{\text{networks}})$ $\not\approx$ $f(v^2_{\text{networks}})$. Moreover, we would like the \textit{relation} between the words ``maple'' and ``delicious'' in the third sentence, to be similar to the relation between ``neural'' and ``interesting'' in the first sentence: $\text{pair}(v^3_\text{maple},v^3_\text{delicious}) \approx \text{pair}(v^1_\text{neural},v^1_\text{interesting})$. Operatively, we represent pairs of words $(x,y)$ by the difference between their transformation $f(x) - f(y)$, and aim to learn a function $f$ that preserves: $f(v^3_\text{maple})-f(v^3_\text{delicious}) \approx f(v^1_\text{neural})-f(v^1_\text{interesting})$. The choice to represent pairs this way was inspired by several works that demonstrated that nontrivial semantic and syntactic relations between uncontextualized word representations can be approximated by simple vector arithmetic \citep{mikolov2013distributed, mikolov2013linguistic, levy2014linguistic}. To learn $f$, we start with groups of sentences such that the sentences within each group are known to share structure but differ in lexical semantics. We call the sentences in each group \emph{structurally equivalent}. Figure \ref{fig:equivalent-sentences} shows an example of two structurally equivalent sets. Acquiring such sets is challenging, especially if we do not assume a known syntactic formalism and cannot mine for sentences based on their observed tree structures. To this end, we automatically generate the sets starting with known sentences and sampling variants from a language model (\S\ref{sec:sentences-generation}). Our sentence-set generation procedure ensures that words from the same set that share an index also share their structural function. We call such words \emph{corresponding}. We now proceed to learn a function $f$ to map contextualized vectors of corresponding words (and the relations between them, as described above) to neighbouring points in the space. We train $f$ such that the representation assigned to positive pairs --- pairs that share indices and come from the same equivalent set --- is distinguished from the representations of negative pairs --- challenging pairs that come from different sentences, and thus do not share the structure of the original pair, but can, potentially, share their lexical meaning. We do so using Triplet loss, which pushes the representations of pairs coming from the same group closer together (\S\ref{sec:triplet-loss}). Figure \ref{fig:triplet-loss} sketches the network. \subsection{Generating Structurally-similar Sentences} \label{sec:sentences-generation} \begin{figure*}[t!] \centering \begin{multicols}{2} \includegraphics[width=1\textwidth]{plots/sentences.png} \end{multicols} \caption{Two groups of structurally-equivalent sentences. In each group, the first sentence is original sentence from Wikipedia, and the sentences below it were generated by the process of repeated BERT substitution. Some sets of corresponding words--that is, words that share the same structural function--are highlighted in the same color.} \label{fig:equivalent-sentences} \end{figure*} In order to generate sentences that approximately share their structure, we sequentially replace content words in the sentence with other content words, while aiming to maintain the grammatically of the sentence, and keep its structure intact. Since we do not want to rely on syntactic annotation when performing this replacement, we opted to use a pre-trained language model -- BERT -- under the assumption that strong neural language models do implicitly encode many of the syntactic restrictions that apply to words in different grammatical functions (e.g., we assume that BERT would not predict a transitive verb in the place of an intransitive verb, or a verb that accepts a complement in the place of a verb that does not accept a complement). While this assumption seems to hold with regard to basic distinctions such as transitive vs. intransitive verbs, its validity is less clear in the more nuanced cases, in which small differences in the surface level can translate to substantial differences in abstract syntactic structure -- such as replacing a control verb with a raising verb. This is a limitation of the current approach, although we find that the average sentence we generate is grammatical and similar in structure to the original sentence. Moreover, as our goal is to \emph{expose} the structural similarity encoded in neural language models, we find it reasonable to only capture the distinctions that are captured by modern language models. \paragraph{Implementation} We start each group with a Wikipedia sentence, for which we generate $k=6$ equivalent sentences by iterating over the sentence from left to right sequentially, masking the ith word, and replacing it with one of BERT's top-30 predictions. To increase semantic variability, we perform the replacement in place (online): after randomly choosing a guess $w$, we insert $w$ to the sentence at index $i$, and continue guessing the $i + 1$ word based on the modified sentence.\footnote{We note that this process bears some similarity to Gibbs sampling from BERT conditioned LM.} We exclude a closed set of a few dozens of words (mostly function words) and keep them unchanged in all $k$ variations of a sentence. We further maintain structural correctness by maintaining the POS\footnote{We maintain the same POS so that the dataset will be valid for other tasks that require structure-preserving variants. However, In practice, we did not observe major differences when repeating the experiments reported here without the POS-preserving constraint when generating the data.}, and encourage semantic diversity by the auto-regressive replacement process. In Table \ref{tbl:parallel_examples} in the Appendix we show some additional generated groups. The sets in Figure~\ref{fig:equivalent-sentences} were generated using this method. \subsection{Word Representation} We sample $N=150,000$ random sentences and use the our method to generate $900,000$ equivalent sets $E$ of structurally equivalent sentences. Then, we encode the sentences and randomly collect $1,500,000$ contextualized vector representations of words from these sets, resulting in 1,500,000 training pairs and 200,000 evaluation pairs for the training process of $f$. We experiment with both ELMo and BERT language models. In average, we sample 11 word-pairs from each group of equivalent sentences. For ELMo, we represent each word in context as a concatenation of the last two ELMo layers (excluding the word embedding layer, which is not contextualized and therefore irrelevant for structure), resulting in representations of dimension 2048. For BERT, we concatenate the mean of the words' representation\footnote{Since BERT uses word-piece tokenization, we take the first token to represent each word.} across all contextualized layers of BERT-Large, with the representation of layer 16, which was found by \citet{structural-probe} most indicative of syntax. \subsection{Triplet Loss} \label{sec:triplet-loss} We learn the mapping function $f$ using triplet loss (Figure \ref{fig:triplet-loss}). Given a group of equivalent sentences $E_i$, we randomly choose two sentences to be the anchor sentence $S^A$ and the positive sentence $S^P$, and sample two different word indices $\{i_1, i_2\}$. Let $S^A[i_1]$ be the contextualized representation of the $i_1$th word in sentence $S^A$. The words $S^A[i_1]$ and $S^A[i_2]$ from the anchor sentence would form a representation of a pair of words, which should be close to the pair $S^P[i_1]$, $S^P[i_2]$ from the positive sentence. We represent pairs as their differences after transformation, resulting in the anchor pair $V^A$ and positive pair $V^P$: \begin{align} V^A = f(S^A[i_1]) - f(S^A[i_2]) \;\;\;\;\;\; S^A \in E_i \\ V^P = f(S^P[i_1]) - f(S^P[i_2]) \;\;\;\;\;\; S^P \in E_i \end{align} where $f$ is the parameterized syntactic transformation we aim to learn. We also consider a negative pair: \begin{equation} V^N = f(S^N[j_1]) - f(S^N[j_2]) \;\;\;\;\;\; S^N \not\in E_i \end{equation} coming from sentence $S^N$ which is not in the equivalent set. As $f$ has shared parameters for both words in the pair, it can be considered a part of a Siamese network, making our learning procedure an instance of a triplet Siamese network \cite{triplet-siamese}. We choose $f$ to be a simple model: a single linear layer that maps from dimensionality 2048 to 75. The dimensions of the transformation were chosen according to development set performance. We use triplet loss \citep{triplet-siamese} to move the representation of the anchor vector $V^A$ closer to the representation of the positive vector $V^P$ and farther apart from the representation of the negative vector $V^N$. Following \citet{triplet-softmax}, we calculate the softmax version of the triplet loss: \begin{equation} L^{triplet}(V^A, V^P, V^N) = \frac{e^{d(V^A, V^P)}}{e^{d(V^A, V^P)} + e^{d(V^A, V^N)}} \end{equation} where $d(x,y) = 1 - \frac{x^{{\scriptscriptstyle \top}} y}{\|x\| \|y\|}$ is the cosine-distance between the vectors $x$ and $y$. The triplet objective is optimized end-to-end using the Adam optimizer \citep{adam}. We train for 5 epochs with a mini-batch of size 500 \footnote{A large enough mini-batch is necessary to find challenging negative examples.}, and take the last model as the final syntactic extractor. During training, the gradient backpropagates through the pair vectors to the parameters $f$ of the Siamese model, to get representations of individual words that are similar for corresponding words in equivalent sentences. We note that we do not back-propagate the gradient to the contextualized vectors: we keep them intact, and only adjust the learned transformation. \paragraph{Hard negative sampling} We obtain the negative vectors $V^N$ using hard negative sampling. For each mini-batch $B$, we collect 500 \{V$_i^A$, V$_i^P$\} pairs, each pair taken from an equivalent set $E_i$. The negative instances V$_i^N$ are obtained by searching the batch for a vector that is closest to the anchor and comes from a different set: \begin{equation} V_i^N = \argmin_{\substack{V_{j\neq i}^A\in B}} d(V_i^A,V_j^A). \end{equation} In addition, we enforce a symmetry between the anchor and positive vectors, by adding a pair (positive, anchor) for each pair (anchor, positive) in $B$. That is, $V_i^N$ is the ``most misleading'' word-pair vector: it comes from a sentence that has a different structure than the structure of V$_i^A$ sentence, but is the closest to V$_i^A$ in the mini-batch. \section{Experiments and Analysis} \label{sec:experiments} We have trained the syntactic transformation $f$ in a way that should encourage it to retain the structural information encoded in contextualized vectors, but discard other information. We assess the representations the model acquired in an unsupervised manner, by evaluating the extent to which the local neighbors of each transformed contextualized vector $f(x)$ share known structural properties, such as grammatical function within the sentence. For the baseline, we expect the neighbors of each vector to share a mix of semantic and syntactic properties. For the transformed vectors, we expect the neighbors to share mainly syntactic properties. Finally, we demonstrate that in a few-shot setting, our representations outperform the original ELMO representation, indicating they are indeed distilled from syntax, and discard other information that is encoded in ELMO vectors but is irrelevant for the extraction of the structure of a sentence. \\[0.5em] \textbf{Corpus } For training the transformation $f$, we rely on 150,000 sentences from Wikipedia, tokenized and POS-tagged by spaCy \cite{honnibal2015improved,honnibal2017spacy}. The POS tags are used in the equivalent set generation to filter replacement words. Apart from POS tagging, we do not rely on any syntactic annotation during training. The evaluation sentences for the experiments mentioned below are sampled from a collection of 1,000,000 original and unmodified Wikipedia sentences (different from those used in the model training). \subsection{Qualitative Analysis} \input{tables/text_examples} \paragraph{t-SNE Visualization} \begin{figure}[t!] \centering \subfloat{ \includegraphics[width=0.9\columnwidth]{plots/tsne-before-updated} }\\ \vspace{-8mm} \subfloat{ \includegraphics[width=0.9\columnwidth]{plots/tsne-after-updated} } \caption{t-SNE projection of ELMO states, colored by syntactic function, before (upper) and after (lower) the syntactic transformation.} \label{fig:tsne} \end{figure} Figure \ref{fig:tsne} shows a 2-dimensional t-SNE projection \citep{t-sne} of 15,000 random content words. The left panel projects the original ELMo states, while the right panel is the syntactically transformed ones. The points are colored according to the dependency label (relation to parent) of the corresponding word, predicted by the parser. In the original ELMo representation most states -- apart from those characterized by a specific part-of-speech, such as amod (adjectives, in orange) or nummod (numbers, in light green) -- do not fit well into a single cluster. In contrast, the syntactically transformed vectors are more neatly clustered, with some clusters, such as direct objects (brown) and prepositional-objects (blue), that are relatively separated after, but not before, the transformation. Interestingly, some functions that used to be a single group in ELMo (like the adjectives in orange, or the noun-compounds in green) are now split into several clusters, corresponding to their use in different sentence positions, separating for examples adjectives that are used in subject positions from those in object position or within prepositional phrases. Additionally, as noun compounds (``maple'' in ``maple syrup'') and adjectival modifiers (``tasty'' in ``tasty syrup'') are relatively structurally similar (they appear between determiners and nouns within noun phrases, and can move with the noun phrase to different positions), they are split and grouped together in the representation (the green and orange clouds). To quantify the difference, we run $K$-means clustering on the projected vectors, and calculate the average cluster purity score as the relative proportion of the most common dependency label in each cluster. The higher this value is, the more the division to clusters reflect division to grammatical functions (dependency labels). We run the clustering with different $K$ values: 10, 20, 40, 80. We find an increase in class purity following our transformation: from scores of 22.6\%, 26.8\%, 32.6\% and 36.4\% (respectively) for the original vectors, to scores of 24.3\%, 33.4\%, 42.1\% and 48.0\% (respectively) for the transformed vectors. \paragraph{Examples} In Table \ref{tbl:txt_example} we present a few query words (Q) and their closest neighbours before (N) and after (NT) the transformation. Note the high structural similarity of the entire sentence, as well as the function of the word within it (Q1: last word of subject NP in a middle clause, Q2: possessed noun in sentence initial subject NP, Q3: head of relative clause of a direct object). Additional examples (including cases in which the retrieved vector does not share the dependency edge with the query vector) are supplied in Appendix \S\ref{more-examples}. \subsection{Quantitative Evaluation} \label{sec:neighbors-test} \input{tables/closet_word_results.tex} We expect the transformed vectors to capture more structural and less lexical similarities than the source vectors. We expect each vectors' neighbors in space to share the structural function of the word over which the vector was collected, but not necessarily share its lexical meaning. We focus on the following structural properties: (1) Dependency-tree edge of a given word (dep-edge), that represents its function (subject, object etc.). (2) The dependency edge of the word parent's (head's dep-edge) in the tree -- to represent higher level structure, such as a subject that resides within a relative clause, as in the word ``man" in the phrase ``the child that the man saw". (3) Depth in the dependency tree (distance from the root of the sentence tree). (4) Constituency-parse paths: consider, for example, the sentence ``They saw the moon with the telescope''. The word ``telescope" is a part of a noun-phrase ``the telescope", which resides inside a prepositional phrase ``with the telescope", which is part of the Verbal phrase ``saw with the telescope". The complete constituency path for this word is therefore ``NP-PP-VP". We calculate the complete tree path to the root (Tree-path-complete), as well as paths limited to lengths 2 and 3. For this evaluation, we parse 400,000 random sentences taken from the 1-million-sentences Wikipedia sample, run ELMo and BERT to collect the contextualized representations of the sentences, and randomly choose 400,000 query word vectors (excluding function words). We then retrieve, for each query vector $x$, the value vector $y$ that is closest to $x$ in cosine-distance, and record the percentage of closest-vector pairs ($x, y$) that share each of the structural properties listed above. For the tree depth property, we calculate the Pearson correlation between the depths of the queries and the retrieved values. We use the Berkeley Neural Parser \citep{benepar-parser} for constituency parsing. We exclude function words from the evaluation. \noindent \paragraph{Easier and Harder cases} The baseline models tend to retrieve words that are lexically similar. Since certain words tend to appear at above-chance probability in certain structural functions, this can make the baseline be ``right for the wrong reason'', as the success in the closest-word test reflects lexical similarity, rather than grammatical generalization. To control for this confounding, we sort the different POS tags according to the entropy of their dependency-labels distribution, and repeat the evaluation only for words belonging to those POS tags having the highest entropy (those are the most structurally variant, and tend to appear in different structural functions). The performance of the baselines (ELMo, BERT models) on those words drops significantly, while the performance of our model is only mildly influenced, indicating the superiority of the model in capturing structural rather than lexical information. \paragraph{Results} The results for ELMo are presented in Table \ref{tbl:closest_word_results}. For BERT, we witnessed similar, but somewhat lower, accuracy: for example, 68.1\% dependency-edge accuracy, 56.5\% head's dependency-edge accuracy, and 22.1\% complete constituency-path accuracy. The results for BERT are available in Appendix \S \ref{bert-results}, and for the reminder of the paper, we focus in ELMo. We observe significant improvement over the baseline for all tests. The correlation between the depth in tree of the query and the value words, for examples, rises from 44.8\% to 56.1\%, indicating that our model encourages the structural property of the depth of the word to be more saliently encoded in its representation compared with the baseline. The most notable relative improvement is recorded with regard to full constituency-path to the root: from 16.6\% before the structural transformation, to 25.3\% after it -- an improvement of 52\%. In addition to the increase in syntax-related properties, we observe a sharp drop --- from 73.6\% to 28.4\% --- in the proportion of query-value pairs that are lexically identical (lexical match, Table \ref{tbl:closest_word_results}). This indicates our transformation $f$ removes much of the lexical information, which is irrelevant for structure. To assess to what extent the improvements stems from the information encoded in ELMo, rather than being an artifact of the triplet-loss training, we also evaluate on a transformation $f$ that was trained on a randomly-initialized ELMo, a surprisingly strong baseline \citep{sent-vectors}. We find this model performs substantially worse than the baseline (Table \ref{tbl:closest_word_results}, ``Transformed-untrained (all)"). \subsection{Minimal Supervision for Structure Distillation: Few-Shot Parsing} \label{sec:parsing-test} \begin{figure}[ht!] \centering \subfloat{ \centering \includegraphics[width=0.8\columnwidth]{plots/las.png}% \label{fig:correlations-bert-biased} } \\ \subfloat{ \centering \includegraphics[width=0.8\columnwidth]{plots/uas.png}% \label{fig:correlations-bert} } \caption{Results of the few-shots parsing setup.} \label{fig:few-shot} \end{figure} The absolute nearest-neighbour accuracy values may appear to be relatively low: for example, only 67.6\% of the (query, value) pairs share the same dependency edge. As the model acquires its representation without being exposed to human-mandated syntactic convention, some of the apparent discrepancies in nearest neighbours may be due to the fact the model acquires different kind of generalization, or learned a representation that emphasizes different kinds of similarities. Still, we expect the resulting (75 dimensional) representations to contain distilled structure information that is mappable to human notions of syntax. To test this, we compare dependency-parsers trained on our representation and on the source representation. If our representation indeed captures structural information, we expect it to excel on a low data setting. To this end, we test our hypothesis with few-shot dependency parsing setup, where we train a model to predict syntactic trees representation with only a few hundred labeled examples. We use an off-the-shelf dependency parser model \citep{dozat2016deep} and swap the pre-trained Glove embeddings \citep{pennington2014glove} with ELMo contextualized embeddings \citep{elmo}. In order to have a fair comparison with our method, we use the concatenation of the two last layers of Elmo; we refer to this experiment as \textit{elmo}. As our representation is much smaller than ELMo's (75 as opposed to 2048), a potential issue for a low data setting is the higher number of parameters to optimize in the later case, therefore a lower dimension may achieve better results. We design two additional baselines to remedy this potential issue: (1) Using PCA in order to reduce the representation dimensionality. We randomly chose 1M words from Wikipedia, calculated their representation with ELMo embeddings and performed PCA. This transformation is applied during training on top of ELMo representation while keeping the 75 first components. This experiment is referred to as \textit{elmo-pca}. This representation should perform well if the most salient information in the ELMo representations are structural. We exepct it to not be the case. (2) Automatically learning a matrix that reduces the embedding dimension. This matrix is learned during training and can potentially extract the relevant structural information from the representations. We refer to this experiment as \textit{elmo-reduced}. Additionally, we also compare to a baseline where we use the gold-POS labels as the sole input to the model, by initializing an embedding matrix of the same size for each POS. We refer to this experiment as \textit{pos}. Lastly, we examine the performance of our representation, where we apply our structural extraction method on top of ELMo representation. We refer to this experiment as \textit{syntax}. \\ We run the few-shot setup with multiple training size values: 50, 100, 200, 500. The results---for both labeled (LAS) and unlabeled (UAS) attachment scores---are presented in Figure \ref{fig:few-shot}, and the numerical results are available in the Appendix \S \ref{appendix-parsing}. In the lower training size setting, we obtain the best performances compared to all baselines. The more training data is used, the gap between our representation and the baselines reduced, but the \emph{syntax} representation still outperforms \textit{elmo}. Using gold POS labels as inputs works relatively well with 50 training examples, but it quickly reaches a plato in performance and remains behind the other baselines. Reducing the dimensions with PCA (\textit{elmo-pca}) works considerably worse than ELMo, indicating PCA loses important information. Reducing the dimensions with a learned matrix (\textit{elmo-reduced}) works substantially better than ELMo, and achieve the same UAS as our representation from 200 training sentences onward. However, our transformation was learned in an unsupervised fashion, without access to the syntactic trees. Finally, when considering the labeled attachment score, where the model is tasked at predicting not only the child-parent relation but also its label, our \textit{syntax} representation outperforms \textit{elmo-reduced}. \section{Conclusion} We propose an unsupervised method for the distillation of structural information from neural contextualized word representations. We used a process of sequential BERT-based substitution to create a large number of sentences which are structurally similar, but semantically different. By controlling for structure while changing lexical choice, we learn a metric under which pairs of words that come from structurally-similar sentences are close in space. We demonstrated that the representations acquired by this method share structural properties with their neighbors in space, and show that with a minimal supervision, those representations outperform ELMo in the task of few-shots parsing. The method is a first step towards a better disentanglement between various kinds of information that is represented in neural sequence models. The method used to create the structurally equivalent sentences can be useful by its own as a data-augmentation technique. In future work, we aim to extend this method to allow for a more soft alignment between structurally-equivalent sentences. \section{Appendix} \ \section{Additional Query-Value Examples} \label{more-examples} \begin{itemize} \item Q: \emph{as they did , the \textbf{probability} of an impact event temporarily climbed , peaking at 2 .}\\ N: \emph{however , the \textbf{probability} of flipping a head after having already flipped 20 heads in a row is simply } \\ NT: \emph{during the first year , the \textbf{scope} of red terror expanded significantly and the number of executions grew into the thousands .} \item Q: \emph{the \textbf{celtics} honored his memory during the following season by retiring his number 35 . }\\ N: \emph{the \textbf{beatles} performed the song at the 1969 let it be sessions .} \\ NT: \emph{the \textbf{warriors} dedicated their round five home match to fai 's memory . } \item Q: \emph{in the old zurich war , the swiss confederation plundered the monastery , whose \textbf{monks} had fled to zurich . }\\ N: \emph{the hridaya sūtra and the `` five meditations '' are recited , after which \textbf{monks} will be served with the gruel and vegetables .} \\ NT: \emph{other commanders were killed and later rooplo kolhi was arrested near pag wool well , where his \textbf{troops} were fetching water. } \item Q: \emph{the \textbf{main} cause of the punic wars was the conflict of interests between the existing carthaginian empire and the expanding roman republic . }\\ N: \emph{the \textbf{main} issue was whether or not something had to be directly perceptible ( meaning intelligible to an ordinary human being ) for it to be a `` copy .} \\ NT: \emph{the \textbf{main} enemy of the game is a sadistic but intelligent arms-dealer known as the jackal , whose guns are fueling the violence in the country .} \item Q: \emph{jones maintained lifelong links with his \textbf{native} county , where he had a home , bron menai , dwyran . }\\ N: \emph{his association with the bbc ended in 1981 with a move back to his \textbf{native} county and itv company yorkshire television , replacing martin tyler as the regional station 's football commentator .} \\ NT: \emph{he leaves again for his \textbf{native} england , moving to a place near bath , where he works with a powerful local coven . } \item Q: \emph{silver iodate can be \textbf{obtained} by reacting silver nitrate ( agno3 ) with sodium iodate . }\\ N: \emph{best mechanical strength is \textbf{obtained} if both sides of the disc are fused to the same type of glass tube and both tubes are under vacuum .} \\ NT: \emph{each of these options can be \textbf{obtained} with a master degree from the university along with the master of engineering degree . } \item Q: \emph{it \textbf{confirmed} that thomas medwin was a thoroughly learned man , if occasionally imprecise and careless }\\ N: \emph{it was \textbf{confirmed} that the truth about heather 's murder would be revealed which ultimately led to ben 's departure .} \\ NT: \emph{it \textbf{proclaimed} that the entire movement of plastic art of our time had been thrown into confusion by the discoveries above-mentioned . } \item Q: \emph{after the death of nadab and abihu , moses \textbf{dictated} what was to be done with their bodies . }\\ N: \emph{most sources indicate that while no marriage took place between haile melekot and woizero ijigayehu , sahle selassie \textbf{ordered} his grandson legitimized .} \\ NT: \emph{vvkj pilots who flew the hurricane conversion \textbf{considered} it to be superior to the standard model . } \item Q: \emph{letters were delivered to sorters who \textbf{examined} the address and placed it in one of a number of `` pigeon holes '' .}\\ N: \emph{i \textbf{examined} and reported on the thread called transcendental meditation which appears on the page you linked to .} \\ NT: \emph{ronson visits purported psychopaths , as well as psychologists and psychiatrists who have \textbf{studied} them , and meets with robert d . } \item Q: \emph{slowboat to hades is a compilation \textbf{dvd} by gorillaz , released in october 2006 .}\\ N: \emph{the album was released in may 2003 as a single album with a bonus \textbf{dvd} .} \\ NT: \emph{master series is a compilation \textbf{album} by the british synthpop band visage released in 1997 . } \item Q: \emph{however , there are also many \textbf{theories} and conspiracies that describe the basis of the plot .}\\ N: \emph{the name tabasco is not definitively known with a number of \textbf{theories} debated among linguists} . \\ NT: \emph{it is likely that to this day there are some \textbf{harrisons} and harrises that are related . } \item Q: \emph{nne , married first , to richard , eldest son of sir richard nagle , \textbf{secretary} of state for ireland , temp .}\\ N: \emph{in the early 1960s , profumo was the \textbf{secretary} of state for war in harold macmillan 's conservative government and was married to actress valerie hobson .} \\ NT: \emph{he was born in edinburgh , the son of william simpson , \textbf{minister} of the tron church , edinburgh , by his wife jean douglas balderston . } \item Q: \emph{battle of stoke field , the final \textbf{engagement} of the wars of the roses .}\\ N: \emph{among others , hogan announced the `` \textbf{engagement} '' of utah-born pitcher roy castleton .} \\ NT: \emph{song of susannah , the sixth \textbf{installment} in the dark tower series . } \item Q: \emph{it vies for \textbf{control} with its host , causing physiological changes that will eventually cause the host 's internal organs to explode .}\\ N: \emph{hurtig and loewen developed rival factions within the party , and battled for \textbf{control} .} \\ NT: \emph{players take \textbf{control} of each of the four main characters at different times throughout the game , which enables multilateral perspective on the storyline . } \item Q: \emph{as such , radio tirana kept close to the official \textbf{policy} of the people 's republic of china , which was also both anti-west and anti-soviet whilst still being socialist in tone .}\\ N: \emph{this was in line with the \textbf{policy} outlined by constantine vii porphyrogenitus in de administrando imperio of fomenting strife between the rus ' and the pechenegs . } \\ NT: \emph{april 2006 , the upr periodically examines the human rights \textbf{performance} of all 193 un member states . } \item Q: \emph{the engine was designed to \textbf{accept} either regular grade , 87 octane gasoline or premium grade , 91 octane gasoline .}\\ N: \emph{for example , an advanced html editing field could \textbf{accept} a pasted or inserted image and convert it to a data uri to hide the complexity of external resources from the user . } \\ NT: \emph{it uses plug-ins ( html parsing technology ) to \textbf{collect} bibliographic information , videos and patents from webpages .} \item Q: \emph{one such decree was the notorious 1876 ems ukaz , which \textbf{banned} the kulishivka and imposed a russian orthography until 1905 ( called the yaryzhka , after the russian letter yery . ) . }\\ N: \emph{fin 1612 , the shogun declared a decree that specifically \textbf{banned} the killing of cattle . } \\ NT: \emph{tannis has \textbf{eliminated} the other time lords and set the doctor and the minister against each other . } \item Q: \emph{a 25 degree list was \textbf{reduced} to 15 degrees ; men had abandoned ship prematurely - hence the pow .}\\ N: \emph{i suggest the article be \textbf{reduced} to something over half the size .} \\ NT: \emph{the old high school was \textbf{converted} into a middle school , until in 1971 the 5 .} \item Q: \emph{the library catalog is maintained on a database that is \textbf{made} accessible to users through the internet.}\\ N: \emph{this screenshot is \textbf{made} for educational use and used for identification purposes in the article on nba on abc .} \\ NT: \emph{hpc is the main ingredient in cellugel which is \textbf{used} in book conservation .} \item Q: \emph{although he lost , \textbf{he} was evaluated highly by kazuyoshi ishii , and he was invited to seidokaikan . }\\ N: \emph{\textbf{he} attended suny fredonia for one year and in 1976 received a b .} \\ NT: \emph{played primarily as a small forward , \textbf{he} showed some opportunist play and in his 18 games managed a creditable 12 goals . } \item Q: \emph{for each \textbf{round} won , you gain one point towards winning the match .}\\ N: \emph{in the fourth \textbf{round} , federer beat tommy robredo and equalled jimmy connors ' record of 27 consecutive grand slam quarterfinals .} \\ NT: \emph{at the beginning of each \textbf{mission} , as well as the end of the last mission , a cutscene is played that helps develop the story . } \section{BERT Closest-Word Results} \label{bert-results} In Table \ref{tbl:closest_word_results_bert}, we present the full quantitative results when using BERT as the encoder. "Baseline" refers to unmodified vectors derived from BERT, and "Transformed" refers to the vectors after the learned syntactic transformation $f$. "hard" refers to evaluation on the subset of POS tags which are most structurally diverse. \input{tables/closest_word_results_bert.tex} \section{Complete Parsing Results} \label{appendix-parsing} Below are the LAS and UAS scores for the experiments described in \S\ref{fig:few-shot}. \label{parsing-numerical-results} \begin{table}[ht] \input{tables/parsing-LAS.tex} \end{table} \begin{table}[ht] \input{tables/parsing-UAS.tex} \end{table} \section{Examples of Equivalent Sentences} In Table \ref{tbl:parallel_examples} we present randomly selected examples of groups of structurally-similar sentences (\S \ref{sec:sentences-generation}). \label{equivalent-sentences-examples} \input{tables/parallel_sentences_examples} \end{itemize} \section*{Acknowledgments} We would like to thank Gal Chechik for providing valuable feedback on early version of this work. This project has received funding from the Europoean Research Council (ERC) under the Europoean Union's Horizon 2020 research and innovation programme, grant agreement No. 802774 (iEXTRACT). Yanai Elazar is grateful to be partially supported by the PBC fellowship for outstanding PhD candidates in Data Science.
{'timestamp': '2021-03-15T01:02:59', 'yymm': '2010', 'arxiv_id': '2010.05265', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05265'}
arxiv
\section*{Appendix} \section{}\label{app:holo_trans} The readers may have noticed that even though $Z = \frac{1}{\sqrt{2}}\left[\begin{smallmatrix} 1 & 1 \\ i & -i \end{smallmatrix}\right]$ is a complex-valued matrix, under the $Z$-transformation not only the binary {\sc Equality} function $(=_2)$ is transformed to the binary {\sc Disequality} function $(\neq_2)$, the arity 4 constraint function $f$ is also transformed to a \emph{real-valued} constraint function $Z^{\otimes 4} f$. This is not a coincidence, but a consequence of the fact that $f$ satisfies arrow reversal symmetry. We say a real-valued constraint function $f$ satisfies arrow reversal symmetry if for all $(a_1, \ldots, a_n) \in \{0, 1\}^n$, \[f(a_1, \ldots, a_n) = f(\overline{a_1}, \overline{a_2}, \ldots, \overline{a_n}),\] where $\overline{a_i} = 1 - a_i$ for all $i$. \begin{lemma} A real-valued $f$ of arity $n$ satisfies arrow reversal symmetry, if and only if $Z^{\otimes n} f$ is real-valued. \end{lemma} \begin{proof} Suppose $f$ satisfies arrow reversal symmetry. Denote by $\widehat{f} = Z^{\otimes n} f$. We have $2^{n/2}\widehat{f}= \left[\begin{smallmatrix} 1 & 1 \\ i & -i \end{smallmatrix}\right]^{\otimes n} f$, and thus for all $(a_1, \ldots, a_n) \in \{0, 1\}^n$, \[2^{n/2}\widehat{f}_{a_1 \ldots a_n} =\sum_{(b_1, \ldots, b_n) \in \{0, 1\}^n } f_{b_1, \ldots, b_n} \prod_{1 \le j \le n} \left\{(-1)^{ a_j b_j}i^{a_j} \right\}.\] Hence, taking complex conjugation, \begin{eqnarray*} 2^{n/2}\overline{\widehat{f}_{a_1 \ldots a_n}} &=& \sum_{(b_1, \ldots, b_n) \in \{0, 1\}^n } {f_{b_1 \ldots b_n}} \prod_{1 \le j \le n}\left\{ (-1)^{ a_j b_j} (-i)^{ a_j } \right\}\\ &=& \sum_{(c_1, \ldots, c_n) \in \{0, 1\}^n } f_{c_1 \ldots c_n} \prod_{1 \le j \le n}\left\{ (-1)^{a_j (1-c_j)} (-i)^{a_j}\right\} \\ &=& 2^{n/2}\widehat{f}_{a_1 \ldots a_n}. \end{eqnarray*} Now in the opposite direction, suppose $\widehat{f}$ is real. We have $Z^{-1} = \frac{1}{\sqrt{2}} \left[\begin{smallmatrix} 1 & -i \\ 1 & i \end{smallmatrix}\right]$, hence by the inverse transformation $2^{n/2}f= \left[\begin{smallmatrix} 1 & -i \\ 1 & i \end{smallmatrix}\right]^{\otimes n} \widehat{f}$, and thus for all $(a_1, \ldots, a_n) \in \{0, 1\}^n$, \[2^{n/2}f_{a_1 \ldots a_n} =\sum_{(b_1, \ldots, b_n) \in \{0, 1\}^n } \widehat{f}_{b_1, \ldots, b_n} \prod_{1 \le j \le n} \left\{(-1)^{ a_j b_j}(-i)^{b_j} \right\}.\] So \begin{eqnarray*} 2^{n/2}f_{\overline{a_1} \ldots \overline{a_n}} &=& \sum_{(b_1, \ldots, b_n) \in \{0, 1\}^n } \widehat{f}_{b_1, \ldots, b_n} \prod_{1 \le j \le n} \left\{(-1)^{ (1-a_j) b_j}(-i)^{b_j} \right\}\\ &=& \sum_{(b_1, \ldots, b_n) \in \{0, 1\}^n } \widehat{f}_{b_1 \ldots b_n} \prod_{1 \le j \le n}\left\{ (-1)^{a_j b_j} i^{b_j}\right\} \\ &=& \overline{2^{n/2}f_{a_1 \ldots a_n}}\\ &=& 2^{n/2}f_{a_1 \ldots a_n}. \end{eqnarray*} \end{proof} \subsection{The eight-vertex model as a Holant problem} Given a 4-regular graph $G = (V, E)$, the \emph{edge-vertex incidence graph} $G' = (U_E, U_V, E')$ is a bipartite graph where $(u_e, u_v) \in U_E \times U_V$ is an edge in $E'$ iff $e \in E$ in $G$ is incident to $v \in V$. We model an orientation ($w \rightarrow v$) on an edge $e = \left\{w, v\right\} \in E$ from $w$ into $v$ in $G$ by assigning $1$ to $(u_e, u_w) \in E'$ and $0$ to $(u_e, u_v) \in E'$ in $G'$. A configuration of the eight-vertex model on $G$ is a \emph{0-1 labeling} on $G'$, namely $\sigma: E' \rightarrow \{0, 1\}$, where for each $u_e \in U_E$ its two incident edges are assigned 01 or 10, and for each $u_v \in U_V$ the sum of values $\sum_{i=1}^4 \sigma(e_i) \equiv 0 \pmod 2$, over the four incident edges of $u_v$. Thus we model the even orientation rule of $G$ on all $v \in V$ by requiring ``two-0-two-1/four-0/four-1'' locally at each vertex $u_v \in U_V$. The ``one-0-one-1'' requirement on the two edges incident to a vertex in $U_E$ is a binary {\sc Disequality} constraint, denoted by $(\neq_2)$. The values of a 4-ary \emph{constraint function} $f$ can be listed in a matrix $M(f) = \left[\begin{smallmatrix} f_{0000} & f_{0010} & f_{0001} & f_{0011} \\ f_{0100} & f_{0110} & f_{0101} & f_{0111} \\ f_{1000} & f_{1010} & f_{1001} & f_{1011} \\ f_{1100} & f_{1110} & f_{1101} & f_{1111}\end{smallmatrix}\right]$, called the \emph{constraint matrix} of $f$. For the eight-vertex model satisfying the even orientation rule and arrow reversal symmetry, the constraint function $f$ at every vertex $v \in U_V$ in $G'$ has the form $M(f) = \left[\begin{smallmatrix} d & 0 & 0 & a \\ 0 & b & c & 0 \\ 0 & c & b & 0 \\ a & 0 & 0 & d \end{smallmatrix}\right]$, if we locally index the left, down, right, and up edges incident to $v$ by 1, 2, 3, and 4, respectively according to \figref{fig:orientations}. Thus computing the partition function $Z_{\textup{8V}}(G; a, b, c, d)$ is equivalent to evaluating \[\sum_{\sigma:E'\rightarrow\left\{0,1\right\}}\prod_{u\in U_E}(\neq_2)\left(\sigma |_{E'(u)}\right) \prod_{u\in U_V}f\left(\sigma |_{E'(u)}\right),\] where $E'(u)$ denotes the incident edges of $u \in U_E \cup U_V$. In fact, in this way we express the partition function of the eight-vertex model as the Holant sum in the framework for Holant problems: \[Z_{\textup{8V}}(G; a, b, c, d) = \textup{Holant}\left(G'; \neq_2 |\ f\right)\] where we use $\textup{Holant}(H; g\ |\ f)$ to denote the Holant sum $\sum_{\sigma:E\rightarrow\left\{0,1\right\}}\prod_{u\in U}g\left(\sigma |_{E(u)}\right) \prod_{u\in V}f\left(\sigma |_{E(u)}\right)$ on a bipartite graph $H = (U, V, E)$ for the Holant problem $\textup{Holant}(g\ |\ f)$. Each vertex in $U$ (or $V$) is assigned the constraint function $g$ (or $f$, respectively). The constraint function $g$ is written as a row vector, whereas the constraint function $f$ is written as a column vector, both as truth tables. (See \cite{cai_chen_2017} for more on Holant problems.) The following proposition says that an invertible holographic transformation does not change the complexity of the Holant problem in the bipartite setting. \begin{proposition}[\cite{Valiant:2008:HA:1350684.1350697}]\label{prop:holo_trans} Suppose $T \in \mathbb{C}^2$ is an invertible matrix. Let $d_1 = \operatorname{arity}(g)$ and $d_2 = \operatorname{arity}(f)$. Define $g' = g \left(T^{-1}\right)^{\otimes d_1}$ and $f' = T^{\otimes d_2} f$. Then for any bipartite graph $H$, $\textup{Holant}(H; g\ |\ f) = \textup{Holant}(H; g'\ |\ f')$. \end{proposition} We denote $\textup{Holant}(G; f) = \textup{Holant}(G'; =_2 |\ f)$. For the even-coloring model, if we view a green-red edge coloring by a 0-1 assignment to the edges such that an edge $e$ is assigned $0$ if it is colored green and assigned $1$ if it is colored red, then the partition function of the even-coloring model $Z_{\textup{EC}}(G; w, x, y, z)$ is exactly the value of the Holant problem $\operatorname{Holant}\left(G; \left[\begin{smallmatrix} z & 0 & 0 & w \\ 0 & x & y & 0 \\ 0 & y & x & 0 \\ w & 0 & 0 & z \end{smallmatrix}\right]\right)$. The following two lemmas show that the eight-vertex model and the even-coloring model are connected via suitable holographic transformations in unexpected ways as Holant problems. \begin{lemma}\label{lem:pm-hard_holant} Let $G$ be a 4-regular graph and let $M_{Z} = \frac{1}{2} \left[\begin{smallmatrix} -1 & 1 & 1 & -1 \\ 1 & -1 & 1 & -1 \\ 1 & 1 & -1 & -1 \\ 1 & 1 & 1 & 1 \end{smallmatrix}\right]$. Then $Z_{\textup{8V}}(G; a, b, c, d) = Z_{\textup{EC}}(G; w, x, y, z)$ where $\left[\begin{smallmatrix} w\\ x\\ y\\ z \end{smallmatrix}\right] = M_{Z \left[\begin{smallmatrix} a\\ b\\ c\\ d \end{smallmatrix}\right]$. \end{lemma} \begin{proof} Using the binary disequality function $(\not=_2)$ for the orientation of any edge, we can express the partition function of the eight-vertex model $G$ as a Holant problem on its edge-vertex incidence graph $G'$, \[Z_{\textup{8V}}(G; a, b, c, d) = \textup{Holant}\left(G'; \neq_2 |\ f\right),\] where $f$ is the 4-ary signature with $M(f) = \left[\begin{smallmatrix} d & 0 & 0 & a \\ 0 & b & c & 0 \\ 0 & c & b & 0 \\ a & 0 & 0 & d \end{smallmatrix}\right]$. Note that, writing the truth table of $(\neq_2) = (0, 1, 1, 0)$ as a vector and multiplied by a tensor power of the matrix $Z^{-1}$, where $Z = \frac{1}{\sqrt{2}}\left[\begin{smallmatrix} 1 & 1 \\ i & -i \end{smallmatrix}\right]$ we get $(\neq_2) (Z^{-1})^{\otimes 2} = (1, 0, 0, 1)$, which is exactly the truth table of the binary equality function $(=_2)$. Then according to \propref{prop:holo_trans}, by the $Z$-transformation, we get \begin{align*} \textup{Holant}\left(G'; \neq_2 |\ f\right) & = \textup{Holant}\left(G'; \neq_2 \cdot \left( Z^{-1} \right)^{\otimes 2} |\ Z^{\otimes 4} \cdot f\right) \\ & = \textup{Holant}\left(G'; =_2 |\ Z^{\otimes 4} f\right)\\ & = \textup{Holant}\left(G; \ Z^{\otimes 4} f\right), \end{align*} and a direct calculation shows that $M(Z^{\otimes 4} f) = \frac{1}{2} \left[\begin{smallmatrix} a + b + c + d & 0 & 0 & - a + b + c - d \\ 0 & a - b + c - d & a +b - c - d & 0 \\ 0 & a +b - c - d & a - b + c - d & 0 \\ - a + b + c - d & 0 & 0 & a + b + c + d \end{smallmatrix}\right]$. \end{proof} Readers are referred to \appref{app:holo_trans} for a more insightful explanation on why the arity-4 constraint function $f$ is transformed to a \emph{real-valued} constraint function, under the \emph{complex-valued} $Z$-transformation. \begin{lemma}\label{lem:holo_trans} Let $G$ be a 4-regular graph and let $M_{HZ} = \frac{1}{2} \left[\begin{smallmatrix} -1 & 1 & 1 & 1 \\ 1 & -1 & 1 & 1 \\ 1 & 1 & -1 & 1 \\ 1 & 1 & 1 & -1 \end{smallmatrix}\right]$. Then $Z_{\textup{8V}}(G; a, b, c, d) = Z_{\textup{EC}}(G; w, x, y, z)$ where $\left[\begin{smallmatrix} w\\ x\\ y\\ z \end{smallmatrix}\right] = M_{HZ \left[\begin{smallmatrix} a\\ b\\ c\\ d \end{smallmatrix}\right]$. \end{lemma} \begin{proof} For the eight-vertex model as a Holant problem $\textup{Holant}\left(G'; \neq_2 |\ f\right)$, we perform a holographic transformation by the matrix $\frac{1}{2} \left[\begin{smallmatrix} 1+i & 1-i \\ 1-i & 1+i \end{smallmatrix}\right]$. We note that this is the composition of a $Z$-transformation and an $H$-transformation where $Z = \frac{1}{\sqrt{2}}\left[\begin{smallmatrix} 1 & 1 \\ i & -i \end{smallmatrix}\right]$ and $H = \frac{1}{\sqrt{2}}\left[\begin{smallmatrix} 1 & 1 \\ 1 & -1 \end{smallmatrix}\right]$, namely $\frac{1}{2} \left[\begin{smallmatrix} 1+i & 1-i \\ 1-i & 1+i \end{smallmatrix}\right] = HZ$. Then \begin{align*} Z_{\textup{8V}}(G; a, b, c, d) & = \textup{Holant}\left(G'; \neq_2 |\ f\right)\\ & = \textup{Holant}\left(G'; (\neq_2) \cdot \left( (HZ)^{-1} \right)^{\otimes 2} |\ (HZ)^{\otimes 4} \cdot f\right) \\ & = \textup{Holant}\left(G'; =_2 |\ (HZ)^{\otimes 4} f\right)\\ & = \textup{Holant}\left(G; \ (HZ)^{\otimes 4} f\right). \end{align*} Here $(\neq_2) \cdot \left( (HZ)^{-1} \right)^{\otimes 2} = (\neq_2) \cdot \left( Z^{-1} \right)^{\otimes 2} \cdot \left( H^{-1} \right)^{\otimes 2} = (=_2) \cdot \left( H^{-1} \right)^{\otimes 2} = (=_2)$, because $H$ is orthogonal. Now a direct calculation shows that $M((HZ)^{\otimes 4} f) = \frac{1}{2} \left[\begin{smallmatrix} a + b + c - d & 0 & 0 & - a + b + c + d \\ 0 & a - b + c + d & a + b - c + d & 0 \\ 0 & a + b - c + d & a - b + c + d & 0 \\ - a + b + c + d & 0 & 0 & a + b + c - d \end{smallmatrix}\right]$. \end{proof} \section{Introduction}\label{sec:intro} \input{intro} \bigskip \section{The even-coloring model}\label{sec:even-coloring} \input{even-coloring} \bigskip \section{Holographic Transformation}\label{sec:holo_trans} \input{holo_trans} \bigskip \section{Planar graphs}\label{sec:planar} \input{planar} \bigskip \section{Bipartite graphs}\label{sec:bipartite} \input{bipartite} \bigskip \section{Concluding remarks}{ All the FPRAS results obtained in this paper come from the algorithm for $\mathcal{AD} \bigcap \mathcal{BD} \bigcap \mathcal{CD} \bigcap \mathcal{Z}$. It is open if there exists an FPRAS/FPTAS for all $(a, b, c, d) \in \mathcal{AD} \bigcap \mathcal{BD} \bigcap \mathcal{CD}$. Assuming such an algorithm exists, our maps in \secref{sec:planar} would imply that all $\mathcal{AD} \bigcap \mathcal{BD}$ is approximable on planar graphs, and our maps in \secref{sec:bipartite} would imply that all $\overline{\mathcal{AD}} \bigcap \overline{\mathcal{BD}} \bigcap \overline{\mathcal{CD}}$ and $\overline{\mathcal{D}}$ are approximable on bipartite graphs. We note that the approximation in $\overline{\mathcal{A}}$, $\overline{\mathcal{B}}$, and $\overline{\mathcal{C}}$ is proved to be NP-hard even on bipartite graphs~\cite{DBLP:journals/corr/abs-1811-03126}. In \secref{sec:planar}, the canonical orientation has the same weight $c$ on every vertex and we are able to obtain algorithms for the eight-vertex model under parameter settings where $c$ is relatively large, e.g. the region $\overline{\mathcal{C}}$; in \secref{sec:bipartite}, the canonical orientation has the same weight $d$ on every vertex and we are able to obtain algorithms for parameter settings where $d$ is relatively large, e.g. region $\overline{\mathcal{D}}$. In general, the paradigm proposed in this paper can be applied to the study of the eight-vertex model on other classes of graphs in additional to planar/bipartite/torus graphs. In particular, the methodology can be readily extended to any class of graphs with a ``canonical'' even orientation where every vertex has the same weight (one of $a$, $b$, $c$, or $d$). } \clearpage
{'timestamp': '2020-10-13T02:27:40', 'yymm': '2010', 'arxiv_id': '2010.05425', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05425'}
arxiv
\section{Introduction} \vspace{-0.15cm} To meet people's increasing demand for network capacity, dense small cell networks are recognized as one of the most promising methods \cite{Kamel2017}. Given the dense deployment of small cell access points (SAPs), traffic requirements among cells can be heavily asynchronous. Dynamic time-division duplex (D-TDD) has emerged as a competitive solution to this problem as it can well adapt to such unaligned and variable traffic \cite{ding2016}. Different from static time-division duplex (S-TDD), which requires all cells to switch between uplink (UL) and downlink (DL) simultaneously, D-TDD allows each cell to adjust the configuration of UL and DL sub-frames dynamically according to its own load \cite{shen2012}. As a result, it is more adaptable to actual asymmetric capacity requirements thus taking full advantage of wireless resources. But, at the same time there will be serious inter-cell interference introduced by asynchronous UL/DL transmissions, especially for edge users. A variety of interference coordination techniques have been proposed to reduce interference. In the frequency domain, the orthogonal channels can be allocated to different cells \cite{Kamel2017}. Interference management in the time domain is done by blanking of sub-frames, such as almost blank sub-frame \cite{Chung2017}. The authors of \cite{Zhang2017} study the power control and sensing time optimization problem in cognitive small cell networks. Among all the interference coordination schemes, fractional frequency reuse (FFR) is proposed as an attractive approach \cite{novlan2011}. The basic idea of FFR is to divide the total frequency band into some interior sub-bands for cell-interior users and edge sub-bands for cell-edge users. All interior sub-bands can be allocated to each cell, while edge sub-bands are reused across different cells. Previously FFR has mainly been used in macro cell networks with high power access points and large cell radius \cite{xie2017}. This technique has been shown to be attractive in macro cell networks due to significant throughput improvement for edge users \cite{chang2016}. The authors of \cite{priyabrata2019} analyze the performance of massive {multiple-input multiple-output (MIMO)} networks with the fractional pilot reuse scheme, in which the interior and edge of a Voronoi cell are distinguished via distance. An FFR scheme where bandwidth allocation is based on real-time/non-real-time traffic classification under small and macro cells is proposed in \cite{Chowdhury2018}. As for small cell networks, the largest concern with applying FFR is how to manage spectrum resource given a large number of small cells each with small coverage. To further study its feasibility, we aim at comparing the performance under FFR-based D-TDD with that under traditional and clustered D-TDD \cite{li2018}. In this letter, we develop a general analytical framework to evaluate the effect of applying FFR to D-TDD small cell networks. We consider a multi-channel model, where each cell has multiple sub-bands available to users, and the number of sub-bands allocated to edge or interior users is adjustable. By modeling the locations of SAPs and users as independent Poisson point processes (PPPs) and the traffic arrivals at each node as independent Bernoulli processes, we derive analytical expressions for the DL and UL successful transmission probability (STP) under a simple FFR-based frequency allocation strategy. We then study mean packet throughput (MPT) per user with any fixed user-SAP distance, and derive the average MPT for users in the FFR-based D-TDD small cell networks for comparing with those under the traditional and clustered D-TDD. With constraints on each user's MPT, we further optimize the DL and UL MPT under FFR-based D-TDD. Numerical results show that FFR can be well adapted to small cell networks in terms of significantly boosting users' MPT, especially for those with a large distance to their associated SAPs. Moreover, the DL and UL MPT can be maximized through fine tuning network parameters. \vspace{-0.2cm} \section{System Model} \label{sect:system model} \vspace{-0.15cm} \subsection{Network Structure} \vspace{-0.15cm} \label{sect:FFR} Let us consider a D-TDD small cell network with orthogonal frequency division multiple access technique. The locations of SAPs and users are modeled as independent PPPs ${\Phi _{\rm{s}}}$ and ${\Phi _{\rm{u}}}$ with spatial densities ${\lambda _{\rm{s}}}$ and ${\lambda _{\rm{u}}}$, respectively. All users are served by their nearest SAPs. Due to the service capacity of an SAP, in any time slot the maximum number of users associated to an SAP is supposed to be $K$. Let $f(k)$ denote the probability that an SAP is associated by $k$ users \cite{li2018}. We assume all SAPs and users adopt fixed transmit power ${P_{\rm{s}}}$ and ${P_{\rm{u}}}$, respectively. We consider that the channel gain is subjected to large-scale path loss {with path loss exponent $\alpha$} and small-scale Rayleigh fading with unit mean. \subsection{Fractional Frequency Reuse Scheme and Scheduling} \label{sect:FFR} Let $\it{\Gamma} $ denote the total number of sub-bands in the network, in which $L$ sub-bands are allocated to each cell with a reuse factor $\Delta $ to serve edge users. That is, the total number of sub-bands allocated to edge users in the network is $\Delta L$. Accordingly, the number of sub-bands allocated to interior users in each cell $M$ is ${\it\Gamma}-\Delta L$.\footnote{{To ensure tractability of the analysis and unearth design insight, we adopt a static sub-band allocation scheme. The analysis here serves as a precursor and can be extended to consider more complicated scenarios such as a dynamic sub-band allocation approach.}} In each time slot, we assume that every SAP randomly selects $L$ edge users and $M$ interior users from its associated users with non-empty buffers to serve. If the number of schedulable edge (resp. interior) users is less than $L$ (resp. $M$), all of them will be selected and the non-occupied sub-bands will become idle at this time slot. Since the locations of SAPs follow PPPs, {each cell is a highly non-regular Voronoi region. As such, users with the same distance to their associated SAPs may have different performances, generating difficulty} to classify users according to the distance to their SAPs {\cite{elsawy2013}}. Therefore, we take the signal-to-interference ratio (SIR) as a classification indicator{\cite{novlan2011}}. Let each SAP randomly allocate an available interior sub-band to the served user. If the receiving SIR on this sub-band is larger than a predetermined threshold $\theta$, the user is recognized as an interior user and occupies this sub-band for transmission. Otherwise, it is deemed as an edge user and is randomly reassigned to an idle edge sub-band. \vspace{-0.2cm} \subsection{Traffic Model} We model the arrival and departure of packets by a discrete time queueing system. The DL and UL packet arrivals of a generic user are modeled as independent Bernoulli processes with probability ${\xi _{{\rm{TX}}}} \in [0,1]$, where $\rm{{TX} \in \{D,U\}}$ with D and U representing DL and UL, respectively \cite{Yang2017Packet}.\footnote{{{In this work we focus on average network throughput, thus adopting the decoupled DL and UL traffic. One can extend the framework to consider correlated traffic by introducing other metric such as timely throughput.}}} Each packet is of the same size and takes up one time slot for transmission on one sub-band. We assume that the DL and UL buffer for each user to accumulate incoming packets are infinite. Denote ${p_{\rm{D}}}$ (resp. ${p_{\rm{U}}} = 1 - {p_{\rm{D}}}$) as the probability that one cell is configured in DL (resp. UL) transmission in each time slot. To minimize the difference between the average DL and UL traffic demand densities \cite{ding2014}, we have ${p_{\rm{D}}} = \arg \mathop {\min }\limits_{\tau \in \left[ {0,1} \right]} \left| {\frac{{k{\xi _{\rm{D}}}}}{\tau } - \frac{{k{\xi _{\rm{U}}}}}{{1 - \tau }}} \right|$, {where $k{\xi _{\rm{D}}}$ and $k{\xi _{\rm{U}}}$ are the expected DL and UL traffic influxes, respectively.} Solving this equation yields ${p_{\rm{D}}} = {\xi _{\rm{D}}}/({\xi _{\rm{D}}} + {\xi _{\rm{U}}})$. {Note that although ${p_{\rm{D}}}$ is fixed across cells, the dynamics of real-time traffic in each cell still vary due to the randomness of packet arrivals and departures. Additionally, the proposed model can be extended to take into account the unbalanced UL/DL traffic attributes in the context of non-identical DL/UL packet arrival rates of different cells \cite{Yang2017Packet}.} \vspace{-0.1cm} \section{Performance Analysis} \label{sect: proposed scheme} In this section, we derive the DL/UL STP of both interior users and edge users as well as the DL/UL MPT. We also study how to fine tune the SIR threshold $\theta$ and the number of edge sub-bands $L$ to maximize the MPT performance under FFR-based D-TDD. \vspace{-0.3cm} \subsection{Interference and Signal-to-Interference Ratio} {Given limited frequency resources, the number of associated users in cells may affect users' scheduling probability, further affecting the accumulation of packets in the users' queue. To model the queues in different cells, we split the PPP of SAPs into $K$ tiers according to the number of associated users in cells, i.e., ${\Phi _{\rm{s}}} = \bigcup\nolimits_{k = 0}^K {{\Phi _{{\rm{s}}k}}}$, where ${{\Phi _{{\rm{s}}k}}}$ denotes the distribution of SAPs associated with $k$ users.} Similarly, users' distribution in the $k$-th tier is represented as ${{\Phi _{{\rm{u}}k}}}$. We focus on the analysis of typical user or SAP located at the origin. Let $x_{\rm{s}}$ denote the location of the SAP associated by the typical interior or edge user ${{z}}_{\rm{N}}$, where ${\rm{N}} \in \{ {\rm{e}},{\rm{in}}\} $ represents edge and interior users, respectively. For convenience of notation, we use the same variable to represent the node itself and its location. The received DL SIR can be written as \vspace{-0.15cm} \begin{equation} \gamma _{{\rm{D,N}}} = {{P_{\rm{s}}}{g_{x_{\rm s},z_{\rm {N}}}}{{\left\| {{x_{\rm{s}}}} \right\|}^{ - \alpha }}}/ (I_{{\rm{D,N}}}^{\Phi_{\rm{s}}}+I_{{\rm{D,N}}}^{\Phi_{\rm{u}}}) \vspace{-0.15cm} \end{equation} where $I_{{\rm{D}},{\rm{N}}}^{{\Phi _{\rm{s}}}} = \sum\nolimits_{k = 1}^K {\sum\nolimits_{x \in {\Phi _{{\rm{s}}k}}\backslash \{ {x_{\rm{s}}}\} } {{\sigma _{x,{z_{\rm{N}}},k}}{P_{\rm{s}}}{g_{x,{z_{\rm{N}}}}}{{\left\| x \right\|}^{ - \alpha }}} }$ is the DL SAP interference to the typical user ${{z}}_{\rm{N}}$, and $I_{{\rm{D,N}}}^{\Phi_{\rm{u}}}=\sum\nolimits_{k = 1}^K {\sum\nolimits_{z \in {\Phi _{{\rm{u}}k}}} {{\sigma _{z,{z_{\rm{N}}},k}}{P_{\rm{u}}}{g_{z,{z_{\rm{N}}}}}{{\left\| z \right\|}^{ - \alpha }}} }$ is the UL user interference to the typical user ${{z}}_{\rm{N}}$, with ${\sigma _{y,{z_{\rm{N}}},k}}$ ($y \in {\{ x,z\}}$) being the indicator variable showing whether node $y$ in the $k$-th tier cell is transmitting packets on the sub-band allocated to ${{z}}_{\rm{N}}$, and ${g_{x_{\rm s},z_{\rm {N}}}}$ (resp. ${g_{y,z_{\rm {N}}}}$) being the small-scale fading on the sub-band allocated to $z_{\rm {N}}$ from node $x_{\rm s}$ (resp. $y$) to the origin. Similarly, the UL SIR received by the typical SAP associated by user ${{z}}_{\rm{N}}$ can be expressed as \vspace{-0.15cm} \begin{equation} \gamma _{\rm{U,N}} = {{P_{\rm{u}}}{g_{z_{\rm{ N}},z_{\rm {N}}}}{{\left\| {{z_{\rm{N}}}} \right\|}^{ - \alpha }}}/(I_{{\rm{U,N}}}^{\Phi_{\rm{s}}}+I_{{\rm{U,N}}}^{\Phi_{\rm{u}}}) \vspace{-0.15cm} \end{equation} where $I_{{\rm{U,N}}}^{\Phi_{\rm{s}}}=\sum\nolimits_{k = 1}^K {{\sum _{x \in {\Phi _{{\rm{s}}k}}}}{\sigma _{x,{z_{\rm{N}}},k}}{P_{\rm{s}}}{g_{x,{z_{\rm{N}}}}}{{\left\| x \right\|}^{ - \alpha }}}$ and $I_{{\rm{U,N}}}^{\Phi_{\rm{u}}}=\sum\nolimits_{k = 1}^K{\sum_{z \in {\Phi _{{{\rm{u}}k}}}\backslash\{ {z_{\rm{N }}}\}} {{\sigma _{z,{z_{\rm{N}}},k}}{P_{\rm{u}}}{g_{z,{z_{\rm{N}}}}}{{\left\| z \right\|}^{ - \alpha }}} }$ are the DL SAP interference and UL user interference, respectively. \vspace{-0.35cm} \subsection{Buffer State Modeling and Non-Empty Buffer Probability} \label{app:a} \vspace{-0.6cm} \begin{figure}[htbp] \begin{center} \includegraphics [clip=true,width=0.4\textwidth]{MarkovChain2.eps} \end{center} \vspace{-0.7cm} \caption{Markov chain of buffer's state.} \vspace{-0.3cm} \label{fig:markov} \end{figure} To assess the interference that a typical user or SAP suffers from, we need a buffer state model to analyze whether other nodes have packets to transmit thus interfering with the typical user or SAP. Also, to evaluate the throughput of the typical user or SAP, we need a buffer state model to characterize its own service process. The main difference between the two models lies in that, the former is for an interfering node without knowing its location information \emph{a priori}, while the latter is otherwise. However, they can be analyzed similarly, which in the following we take the DL case of the second buffer state model as an example to illustrate. For the typical user in the $k$-th cell with a user-SAP distance $r$, we model its DL buffer state by the Markov chain shown in Fig. \ref{fig:markov}. We use $j\in \left\{ {0,1,2,...} \right\}$, the number of packets in a buffer at the beginning of a time slot, to represent the buffer's state. There are three types of state transitions: \footnote{ {Note that we omit the self-transitions, i.e., a new packet arrives and simultaneously a packet departs as well as no packet arrives and departs, since they have no impact on the buffer state.}} {{\textit{Transition 1:}} A new packet arrives at an empty buffer with transition probability $P_{k,r}\left( {\left. 1 \right|0} \right)={\xi _{{\rm{D}}}}$.} {{\textit{Transition 2:}} A new packet arrives at a non-empty buffer and no packet departs, with transition probability \vspace{-0.15cm} \begin{equation} P_{k,r}\left( {\left. j+1 \right|j } \right)={\xi _{{\rm{D}}}}\left(1 -{{\bar \mu }_{k,r}^{\rm{D}}} \right),~j = 1,2,3,... \vspace{-0.15cm} \end{equation} where ${{\bar \mu }_{k,r}^{\rm{D}}}={p_{{\rm{D}}}} [{q_{{\rm{D,in}}}(r)}{Q_{{\rm{D,in}}}}(k){\mu _{{\rm{D,in}}}(r)} \!\!+ \!{q_{{\rm{D,e}}}(r)}{Q_{\rm{D,e}}}(k) {\mu _{{\rm{D,e}}}(r)}] $ is departure probability that one packet is removed from the DL buffer.} Here, $q_{{\rm{D}},\rm{in}}(r)= \mathbb{P}\left( {{\gamma _{{\rm{D}},{\rm{in}}}} \ge \theta } \right)$ (resp. $q_{{\rm{D}},\rm{e}}(r) = 1- q_{{\rm{D}},\rm{in}}(r)$) represents the probability of the typical user with given $r$ being an interior user (resp. edge user) in a time slot. Note that the probability density function of $r$ is given by ${f_r}(r) = 2\pi {\lambda _{\rm{s}}}r\exp ( - \pi {\lambda_{\rm{s}}}{r^2})$\cite{li2018}. De-conditioning on $r$, we have $q_{{\rm{D}},\rm{N}} = \int_0^\infty {{q_{{\rm{D,N}}}}(r)} {f_r}(r)dr$, $\rm{N} \in \{\rm{e,in}\}$, to characterize the probability of a generic user being an interior or edge user. {${Q_{{\rm{D, N}}}}(k)$ is the probability that the typical user is scheduled as an interior or edge user when coexisting with other $k-1$ users in the cell. Let ${{\Xi } _{k}^{\rm{D}}}$ denote the probability that a generic user from the $k$-th tier cell has a non-empty buffer in the DL. Then, the average number of DL schedulable interior or edge users in the cell can be approximated as ${{1 + (k - 1)q_{{\rm{D}},\rm{in}}}}{{\Xi } _{k}^{\rm{D}}}$, where the first item $1$ is referred to as the typical user which has at least one packet in this transition case, and the second item calculates the mean number from the other users. The approximation is because the interdependency between the user-SAP distance distribution and the per-cell user number is ignored similar to \cite{Singh15} for analysis tractability.} So, given $M$ interior sub-bands in each cell, we can derive ${Q_{{\rm{D}},\rm{in}}}(k){\rm{ = }}\min \left( {\frac{M}{{1 + \left( {k - 1} \right)q_{{\rm{D}},\rm{in}}{{\Xi } _{k}^{\rm{D}}}}},1} \right)$. Similarly, we have ${Q_{\rm{D,e}}}(k){\rm{ = }}\min \left( {\frac{L}{{1 + (k - 1) {q_{{\rm{D,e}}}}{{\Xi } _{k}^{\rm{D}}}}},1} \right)$. ${\mu _{\rm{D,N}}}(r)$ is the DL STP of the typical user as an interior or edge user, which is to be derived in the next subsection. {{\textit{Transition 3:}} No new packet arrives and a packet in the queue is successfully transmitted, with transition probability \vspace{-0.15cm} \begin{equation} P_{k,r}\left( {\left. j \right|j + 1} \right)={{\bar \mu }_{k,r}^{\rm{D}}}\left(1-{\xi _{{\rm{D}}}} \right),~j = 0,1,2,... \vspace{-0.15cm} \end{equation}} Denote $\delta _{k,r}^{\rm{D}}(j)$ as the probability that the DL buffer has $j$ packets in the steady state for the typical user with given $k$ and $r$, the balance equation can be written as: \vspace{-0.2cm} \begin{equation} \delta _{k,r}^{\rm{D}} (j)P_{k,r}\left( {\left. j+1 \right|j }\right) = \delta _{k,r}^{\rm{D}} (j+1)P_{k,r}\left( {\left. j \right|j+1 }\right)~~j = 0,1,2,...\nonumber \vspace{-0.15cm} \end{equation} \vspace{-0.15cm} By utilizing $\sum\nolimits_{j = 0}^\infty {\delta _{k,r}^{\rm{D}} (j)} = 1$, we can find \begin{subequations} \begin{align} \delta_{k,r}^{\rm{D}} (0) =& { {1 - {{{\xi _{{\rm{D}}}}}}/{{\bar \mu }_{k,r}^{\rm{D}}}}}\\ \delta_{k,r}^{{\rm{D}}}(j) =& \frac{{\xi _{{\rm{D}}}^j{{\left( {1 - {{\bar \mu }_{k,r}^{\rm{D}}} } \right)}^{j - 1}}}}{{{{\left( {1 - \xi _{{\rm{D}}}^{}} \right)}^j}{ \left({{\bar \mu }_{k,r}^{\rm{D}}} \right)^j }}}\delta_{k,r}^{{\rm{D}}}(0). \vspace{-0.5cm} \end{align} \end{subequations} To make the queue stable, we need ${\xi _{{\rm{D}}}}<{{\bar \mu }_{k,r}^{\rm{D}}}$. Otherwise, the delay of packets accumulated in the queue will tend to be infinite. Then, the DL non-empty buffer probability for the typical user can be derived as ${{ \Xi }_{k,r}^{\rm{D}}} = 1-\delta _{k,r}^{\rm{D}}(0)$. The UL case for the typical SAP can be analyzed similarly. For the first buffer state model, theoretically, by de-conditioning on $r$ of ${{ \Xi }_{k,r}^{\rm{TX}}}$, ${\rm{TX \in \{D, U\}}}$, one can obtain the average non-empty buffer probability ${{ \Xi }_{k}^{\rm{TX}}}$ for a generic user in the $k$-th tier cell. But, a more computation-efficient way is to calculate it based on the Markov chain in Fig. \ref{fig:markov} without any constraints on $r$ and assuming that whether a packet transmission is successful is independent of whether the user is an interior or edge user. Then we can obtain ${{ \Xi }_{k}^{\rm{TX}}} = {\xi _{{\rm{TX}}}}/{{\bar \mu }_{k}^{\rm{TX}}}$, where ${{\bar \mu }_{k}^{\rm{TX}}}\approx {p_{{\rm{TX}}}}\left[{q_{{\rm{TX,in}}}}{Q_{{\rm{TX,in}}}}(k){\mu _{{\rm{TX,in}}}} + {q_{{\rm{TX,e}}}}{Q_{\rm{TX,e}}}(k){\mu _{{\rm{TX,e}}}}\right] $, with $\mu_{\rm{TX,N}}$ being the DL or UL average STP of a generic interior or edge user. \vspace{-0.2cm} \subsection{Successful Transmission Probability} \vspace{-0.15cm} If the received SIR exceeds a predefined threshold $T$, the packet is successfully transmitted and can be removed from the buffer. Otherwise, the transmission fails and the packet will be retransmitted in the next time slot. To this end, the DL and UL STP of an edge and interior user with distance $r$ can be defined as $\mu _{{\rm{TX,e}}}(r) {\buildrel \Delta \over=} \mathbb{P}({{ \gamma }_{{\rm{TX,e}}}} > T\left| {{\gamma _{{\rm{TX,in}}}} < \theta } \right.)$ and $\mu _{{\rm{TX,in}}}(r) {\buildrel \Delta \over=} \mathbb{P}({{\gamma }_{{\rm{TX,in}}}} > T\left| {{\gamma _{{\rm{TX,in}}}} \ge \theta } \right.)$, respectively. \begin{theorem} \label{the:a} For an edge or interior user with distance $r$ to its associated SAP, its DL or UL STP can be approximated as \vspace{-0.3cm} \vspace{-0.15cm} \begin{align} &\mu _{{\rm{D,e}}}(r) \approx \frac{{ { {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,e}}},{{{{\lambda}}}_{\rm {U,e}}},T,r} \right) - {\eta _2}\left( {T,\theta,r } \right)} } }}{{1 - {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}}_{\rm {U,in}}},\theta,r} \right)} }}\nonumber \\ &\mu _{{\rm{D,in}}}(r) \approx \frac{{ {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}},\max (T,\theta ),r} \right)} }}{{ {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}},\theta,r } \right)} }}\label{userSTP}\\ &\mu _{{\rm{U,e}}}(r)\approx \frac{{ { {{\eta _1}\left( {{{{{{\lambda}}} _{\rm {D,e}}},{{{{\lambda}}}_{\rm {U,e}}}},\frac{T{{P_{\rm{s}}}}}{{{P_{\rm{u}}}}},r } \right) -{\eta _2}\left( {\frac{T{{P_{\rm{s}}}}}{{{P_{\rm{u}}}}}, \frac{\theta {{P_{\rm{s}}}}}{{{P_{\rm{u}}}}},r}\! \right)}}}}{{1 - {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}}, \frac{{\theta {P_{\rm{s}}}}}{{{P_{\rm{u}}}}}} ,r\right)}}}\notag\\ &\mu _{{\rm{U,in}}}(r) \approx \frac{{ {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}},\frac{{\max (T,\theta ){P_{\rm{s}}}}}{{{P_{\rm{u}}}}},r} \right)} }}{{ {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}}, \frac{{\theta{P_{\rm{s}}}}}{{{P_{\rm{u}}}}},r} \right)} }}\notag \end{align} where functions ${\eta _1}(\cdot)$, ${\eta _2}(\cdot)$, and function $\zeta(\cdot)$ used in ${\eta _2}(\cdot)$ are given at the top of the next page, with ${{{{\lambda}}} _{\rm {TX,N}}}={\lambda _{\rm{s}}}{p_{\rm{TX}}}\sum\nolimits_{k=1}^K f(k){\chi _{{\rm{TX,N}},k}}$, ${\chi_{{\rm{TX,e}},k}} = \frac{1}{\Delta}\min \left( {\frac{{k{q_{{\rm{TX,e}}}}}{{\Xi} _{k}^{\rm{TX}}}}{L},1} \right)$, ${\chi_{{\rm{TX,in}},k}} = \min \left( {\frac{{k{q_{{\rm{TX,in}}}}{{\Xi} _{k}^{\rm{TX}}}}}{M},1} \right) $, $q_{{\rm{U}},{\rm{in}}} = \int\nolimits_0^\infty {\eta _1} \left( {{{{\lambda}}} _{\rm {D,in}}}, {{{{\lambda}}} _{\rm {U,in}}}, \right.\left.\theta\frac{{ {P_{\rm{s}}}}}{{{P_{\rm{u}}}}},r \right){f_r}(r)dr $, and $q_{{\rm{D,in}}} = \int\nolimits_0^\infty {{\eta _1}\left( { {{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}},\theta ,r} \right)} {f_r}(r)dr$. \newcounter{mytempeqncnt} \begin{figure*}[!t] \vspace{-0.1cm} \normalsize \setcounter{mytempeqncnt}{\value{equation}} \setcounter{equation}{5} \vspace{-0.1cm} \begin{equation} {{\eta _1}\left( { {{{{\lambda}}}_{\rm {D,e}}},{{{{\lambda}}}_{\rm {U,e}}},T,r } \right) = {\exp } \left[ { -\pi{r^2}{ {\int\nolimits_{{T^{ - \frac{2}{\alpha} }}}^\infty {\frac{ { {{{\lambda}}}_{\rm {D,e}}}{T^{\frac{2}{\alpha }}} }{ {1 + {v^{\alpha /2}}} }dv}} } } {{ -\pi {r^2} {\int\nolimits_{{\left(\frac{T{P_{\rm{u}}}}{{P_{\rm{s}}}}\right)^{ - \frac{2}{\alpha} }}}^\infty {\frac{{{{{\lambda}}}_{\rm {U,e}}}{\left(\frac{T{P_{\rm{u}}}}{{P_{\rm{s}}}}\right)^{\frac{2}{\alpha }}}}{ {1 + {v^{\alpha /2}}} }dv}}} } \right]\nonumber} \end{equation} \vspace{-0.1cm} \begin{equation} {{\eta _2}\left( {T,\theta,r } \right) = \prod\limits_{k = 1}^K {\exp } \left[ { - 2\pi {\lambda _{\rm{s}}}f(k){r^2}\left( {{p_{\rm{D}}}\zeta (T,\theta ,{\chi _{{\rm{D,in}},k}},{{\chi _{{\rm{D,e}},k}}}) + {p_{\rm{U}}}\zeta (\frac{{T{P_{\rm{u}}}}}{{{P_{\rm{s}}}}},\frac{{\theta {P_{\rm{u}}}}}{{{P_{\rm{s}}}}},{\chi _{{\rm{U,in}},k}},{{\chi _{{\rm{U,e}},k}}}) } \right)} \right]\nonumber} \end{equation} \vspace{-0.1cm} \begin{equation} {\zeta (T,\theta ,{\chi _{{\rm{D,in}},k}},{{\chi _{{\rm{D,e}},k}}}) \!=\! \int\nolimits_1^\infty {\left[ {1 - \!\left( {\frac{{\chi _{{\rm{D,in}},k}}}{{1 + \theta {v^{ - \alpha }}}} + 1 - {\chi _{{\rm{D,in}},k}}} \right)\!\left( {\frac{{{\chi _{{\rm{D,e}},k}} }}{{1 + T{v^{ - \alpha }}}} + 1 - {{\chi _{{\rm{D,e}},k}}}} \right)} \right]}vdv\nonumber} \vspace{-0.15cm} \end{equation} \vspace{-0.4cm} \setcounter{equation}{\value{mytempeqncnt}} \hrulefill \vspace*{4pt} \end{figure*} \begin{IEEEproof} See Appendix \ref{app:b} for a sketch of the proof. \end{IEEEproof} \end{theorem} \vspace{0.2cm} De-conditioning on $r$, we have the DL or UL STP of an edge or interior user given as follows \begin{align} &\mu _{{\rm{D,e}}} \approx \frac{{\int_0^\infty {\left[ {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,e}}},{{{{\lambda}}}_{\rm {U,e}}},T,r} \right) - {\eta _2}\left( {T,\theta,r } \right)} \right]} {f_r}(r)dr}}{{1 - \int_0^\infty {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}}_{\rm {U,in}}},\theta,r} \right)} {f_r}(r)dr}}\nonumber \\ &\mu _{{\rm{D,in}}} \approx \frac{{\int_0^\infty {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}},\max (T,\theta ),r} \right)} {f_r}(r)dr}}{{\int_0^\infty {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}},\theta,r } \right)} {f_r}(r)dr}}\label{averageSTP}\\ &\mu _{{\rm{U,e}}}\approx\frac{{\int_0^\infty \!{\left[ {{\eta _1}\left( {{{{{{\lambda}}} _{\rm {D,e}}},{{{{\lambda}}}_{\rm {U,e}}}},\frac{T{{P_{\rm{s}}}}}{{{P_{\rm{u}}}}},r } \right) -{\eta _2}\!\left( {\frac{T{{P_{\rm{s}}}}}{{{P_{\rm{u}}}}}, \frac{\theta {{P_{\rm{s}}}}}{{{P_{\rm{u}}}}},r}\! \right)}\right]} {f_r}(r)dr}}{{1 - \int_0^\infty {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}}, \frac{{\theta {P_{\rm{s}}}}}{{{P_{\rm{u}}}}}} ,r\right)} {f_r}(r)dr}}\notag\\ &\mu _{{\rm{U,in}}} \approx \frac{{\int_0^\infty {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}},\frac{{\max (T,\theta ){P_{\rm{s}}}}}{{{P_{\rm{u}}}}},r} \right)} {f_r}(r)dr}}{{\int_0^\infty {{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}}, \frac{{\theta{P_{\rm{s}}}}}{{{P_{\rm{u}}}}},r} \right)} {f_r}(r)dr}}\notag. \end{align} \vspace{-0.15cm} {\emph{Remark 1:} (\ref{userSTP}) and (\ref{averageSTP}) are given as the solutions of a system of equations due to the interdependency of the STP and statuses of queues at all nodes. To obtain the solution, we apply an iterative search-based method with an initial value of the typical user's STP\cite{alfa}.} \emph{Remark 2:} The coverage probability derived in \cite{novlan2011} for an interference-limited FFR system is a special case of (\ref{averageSTP}), if we consider saturated traffic and DL transmission only in the network, and assume each cell has a single sub-band for each type of users and always has edge and interior users to schedule, i.e., set ${p_{\rm{D}}}=1$, ${\chi_{{\rm{TX,e}},k}}=1/{\Delta}$, and ${\chi_{{\rm{TX,in}},k}}=1$. \vspace{-0.4cm} \subsection{Mean Packet Throughput Analysis and Optimization} \vspace{-0.15cm} Define mean packet throughput as the reciprocal of the average time a node takes to successfully transmit a packet. We have the following theorem on users' MPT. \begin{theorem} \label{the:b} In FFR-based D-TDD small cell networks, MPT of a user with user-SAP distance $r$ can be derived as{ \vspace{-0.15cm} \begin{equation} {{ {\cal T}}_{{\rm{TX}}}(r)}={\sum\limits_{k = 1}^K {\displaystyle{ \left\{ \frac {{\bar \mu }_{k,r}^{\rm{TX}}-{\xi _{{\rm{TX}}}}} {1-{\xi _{{\rm{TX}}}}} \right\}_+}} \frac{f\left( k \right)} {1 - f\left( 0 \right)}},~{\rm{TX \in \{D, U\}}} \vspace{-0.15cm} \end{equation} where ${{\bar \mu }_{k,r}^{\rm{TX}}}= [{q_{{\rm{TX,in}}}(r)}{Q_{{\rm{TX,in}}}}(k){\mu _{{\rm{TX,in}}}(r)} \!\!+ \!{q_{{\rm{TX,e}}}(r)}{Q_{\rm{TX,e}}}(k)\\ {\mu _{{\rm{TX,e}}}(r)}]{p_{{\rm{TX}}}}$, $q_{{\rm{U,in}}}(r)\!\!= \!{{{\eta _1}\!\!\left( \!{{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}},\frac{{\theta {P_{\rm{s}}}}}{{{P_{\rm{u}}}}},r} \!\right)}}$, $q_{{\rm{D,in}}}(r)\!\!=\!{{{\eta _1}\!\!\left( \!{{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}},\theta ,r}\! \right)}}$, and $\left\{{a}\right\}_+={\rm{max}}\left\{a,0\right\}$.} \vspace{0.1cm} \begin{IEEEproof} {If ${\xi _{{\rm{TX}}}}<{\bar \mu }_{k,r}^{\rm{TX}}$, the DL and UL MPT in the $k$-th cell can be derived according to Little's law by calculating the ratio of the packet arrival rate to the mean packet number in the queuing system, i.e., ${{{\cal T}}_{{\rm{TX,}}k}}(r)= \frac{{{\xi _{{\rm{TX}}}}}}{{\sum\nolimits_{j = 0}^\infty {j{{\delta_{k,r}^{\rm{TX}} }}(j)} }}={{\frac{{\bar \mu }_{k,r}^{\rm{TX}}-{\xi _{{\rm{TX}}}}}{1-{\xi _{{\rm{TX}}}}} } }$. \\Otherwise, ${{{\cal T}}_{{\rm{TX,}}k}(r)}=0$. De-conditioning on $k$ by taking account of all possible non-empty cell cases, we have ${{{\cal T}}_{{\rm{TX}}}(r)} =\mathbb{E}\left[ {{{\cal T}}_{{\rm{TX,}}k}(r)}|k \ge 1\right]=\frac{{\sum\nolimits_{k = 1}^K { {{{\cal T}}_{{\rm{TX,}}k}(r)} f\left( k \right)} }}{{1 - f\left( 0 \right)}}$.} \end{IEEEproof} \end{theorem} \vspace{0.2cm} Further, by taking the average on $r$ while assuming that whether a packet transmission is successful is independent of whether the user is an interior or edge user, we can obtain the average DL and UL MPT of users as \vspace{-0.15cm} \begin{equation} {{ {\cal T}}_{{\rm{TX}}}}= {\sum\limits_{k = 1}^K {\displaystyle{ \left\{ \frac {{\bar \mu }_{k}^{\rm{TX}}-{\xi _{{\rm{TX}}}}} {1-{\xi _{{\rm{TX}}}}} \right\}_+}} \frac{f\left( k \right)} {1 - f\left( 0 \right)}},~{\rm{TX \in \{D, U\}}}.\label{eq:mpt} \vspace{-0.15cm} \end{equation} To maximize the average DL and UL MPT while offering performance guarantee for users at different locations, we should solve the following optimization problem (OP) \vspace{-0.2cm} \begin{subequations} \label{eq:op} \begin{align} \mathop {\max }\limits_{\theta ,L}\; ~&{{ {\cal T}}_{{\rm{TX}}}}\\ \rm{s.t.}~&{{ {\cal T}}_{{\rm{TX}}}(r)} \ge {\varpi _{{\rm{TX}}}},~r\in[0,R] \label{eq:con1} \vspace{-0.2cm} \end{align} \end{subequations} where ${\varpi _{{\rm{TX}}}}$ denotes the required minimum MPT, and $R$ is the cell radius. To make the problem feasible ${\varpi _{{\rm{TX}}}}$ should be reasonably set, since the network throughput is still constrained, as to be discussed in more detailed in Section \ref{sect: simulation results}. To address the OP, we use exhaustive search. Notice that, constraint (\ref{eq:con1}) holds if ${{ {\cal T}}_{{\rm{TX}}}(R)}\ge {\varpi _{{\rm{TX}}}}$, as users farther away from their tagged SAPs have smaller MPT. As such, the time complexity of exhaustive search here is at most ${\cal O}\left(N_{\theta} {\it \Gamma} \right)$ where $N_{\theta}$ denotes the number of different $\theta$'s values, provided that $\theta$ is searched with appropriate granularity. \vspace{-0.25cm} \section{Numerical Results} \label{sect: simulation results} In this section, we verify the proposed model through simulation in Matlab and compare the performance of small cell networks under FFR-based D-TDD with that under traditional and clustered D-TDD. The average MPT is obtained by averaging over 5000 arbitrary and independent network realizations of the PPP. The simulation area is $1600 \times 1600 \rm{m}^2$. For one specific realization, we simulate continuous 10000 time slots. Unless otherwise stated, we adopt the following system parameters\cite{Yang2017Packet}: ${\lambda _{\rm{s}}}{\rm{ = }}{10^{ - 4}}{\rm{/}}{{\rm{m}}^2}$, ${\lambda _{\rm{u}}}={10^{ - 2}}{\rm{/}}{{\rm{m}}^2}$, ${P_{\rm{s}}} = 30~{\rm{dBm}}$, ${P_{\rm{u}}} = 23~{\rm{dBm}}$, ${\xi _{\rm{D}}} = 0.08$, ${\xi _{\rm{U}}} = 0.04$, $K =50$, $\theta = 0~{\rm{dB}}$, $\alpha = 3.8$, $\Delta = 2$, ${\it\Gamma} = 20$, $L=1$, $T = 1~{\rm{dB}}$, $R=70~\rm{m}$. \vspace{-0.3cm} \begin{figure}[htbp] \begin{center} \includegraphics [clip=true,width=0.5\textwidth]{sim_num2.eps} \end{center} \vspace{-0.4cm} \caption{{STP and MPT under different SIR thresholds $T$. (a) STP. (b) MPT.}} \vspace{-0.15cm} \label{fig:STP} \end{figure} Fig. \ref{fig:STP} depicts the DL/UL STP and average MPT as a function of the SIR threshold $T$. Firstly, note that the numerical results are well matched with the simulation results, which verifies the accuracy of our analysis. Further, it is seen from Fig. \ref{fig:STP}(a) that interior users' STP remains unchanged when $T < \theta$. In this case, interior users' SIR on the interior sub-band must be larger than $T$, thus can always send packets successfully. When $T > \theta$, interior users' STP decreases with $T$ because the increase of $T$ raises the threshold for successful transmission. Similarly, edge users' STP always decreases with $T$. Consequently, we can find from Fig. \ref{fig:STP}(b) that the average MPT descends slightly when $T < \theta$ and the rate of descent increases otherwise. It is noteworthy from Fig. \ref{fig:STP}(b) that a small $L$ generates less MPT for both DL and UL transmissions. We analyze the impact of spectrum allocation between interior and edge users in more detail in the following figures. \begin{figure}[htbp] \begin{center} \includegraphics [clip=true,width=0.5\textwidth]{UserThroup.eps} \end{center} \vspace{-0.2cm} \caption{{MPT per user vs. user-SAP distance.}} \vspace{-0.3cm} \label{fig:UserThroup} \end{figure} In Fig. \ref{fig:UserThroup}, we study the MPT per user given different user-SAP distances $r$ under traditional, clustered, and FFR-based D-TDD. It can be seen that the users' MPT decreases monotonously with $r$ because the distant nodes are vulnerable to lower signal power and higher interference. However, it is noteworthy that FFR-based D-TDD can perform much better than the other two counterparts. Moreover, it is observed that for FFR-based D-TDD networks, when the user-SAP distance is small (e.g., $ < 70~\rm{m}$ in DL and $< 57~\rm{m}$ in UL), a smaller number $L$ of edge sub-bands in a cell generates larger users' MPT. This is because allocating less sub-bands to edge users essentially prevents the waste of resources for serving users in a poor communication environment. However, to improve the performance of users farther away from the SAPs, a larger setting of $L$ is more appropriate. To understand how FFR-based D-TDD can improve the average MPT while offering throughput assurance for each user, Fig. \ref{fig:ThroupOpt} shows the searching result of (\ref{eq:op}), with {$\theta \in \{-1, 0,...,4\}$~dB and $L \in \{1,3,5,7\}$}. To compare with a benchmark, we set ${\varpi _{{\rm{TX}}}}$ in (\ref{eq:con1}) as $\beta \varpi _{{\rm{TX}}}^{{\rm{Clu}}}$, where $\varpi _{{\rm{TX}}}^{{\rm{Clu}}}$ is the average MPT under clustered D-TDD and $\beta \! > \! 0$ is a scaling factor. From the simulation results, we have $\varpi _{{\rm{D}}}^{{\rm{Clu}}} \! = \! 0.456$~packets/slot and $\varpi _{{\rm{U}}}^{{\rm{Clu}}} \! = \! 0.159$~packets/slot. Setting $\beta \in (0,0.81)$, we have the optimal setting $(L^*,\theta ^*) \!=\! (5, 1 {\rm dB})$. If further increase $\beta$, we need a larger $L$ (e.g., 7) to satisfy the constraint according to Fig. \ref{fig:UserThroup} until the OP becomes infeasible. Given $\theta$, we find that both ${{ {\cal T}}_{{\rm{D}}}}$ and ${{ {\cal T}}_{{\rm{U}}}}$ increase first and then decrease with the increase of $L$. When $L$ is small, most of sub-bands are allocated to interior users, however, depending on the network traffic load, it is possible that the number of schedulable interior users is not large enough to fully utilize the allocated sub-bands. In this case, increasing $L$ offers a choice to improve the network performance by better balancing the spectrum consumption between the interior and edge users thus making ${{ {\cal T}}_{{\rm{TX}}}}$ increase accordingly. After reaching the peak point of ${{ {\cal T}}_{{\rm{TX}}}}$ at $L=5$, further increasing $L$ will result in a decrease in the number of served interior users and thus the average MPT deteriorates. With the optimal parameter setting $(L^*,\theta ^*) \!=\! (5, 1 {\rm dB})$, the average MPT of the proposed FFR-based D-TDD can increase up to $ {34\%}$ in DL and $ {32\%}$ in UL compared with clustered D-TDD. \vspace{-0.4cm} \begin{figure}[htbp] \begin{center} \includegraphics [clip=true,width=0.5\textwidth]{mptopt.eps} \end{center} \vspace{-0.2cm} \caption{{Average MPT optimization.}} \vspace{-0.3cm} \label{fig:ThroupOpt} \end{figure} \vspace{-0.05cm} \section{Conclusion} \label{sec:conclusion} \vspace{-0.15cm} In this letter, we have proposed a general model to study the effect of FFR on D-TDD small cell networks. We have derived accurate expressions to characterize the DL and UL MPT for users in the networks. By comparing the MPT performance under the proposed FFR-based D-TDD with those under traditional and clustered D-TDD, we have shown that FFR can improve the performance significantly. Furthermore, we can maximize the average MPT for FFR-based D-TDD small cell networks while ensuring each user' performance by adjusting edge and interior users' differentiation threshold and allocating sub-bands appropriately. { Extending the analytical framework to study the packet throughput, as well as devise dynamic frequency allocation strategies, in small cell networks operated under D-TDD and subjected to heterogeneous traffic load is one concrete direction for future work.} \begin{appendices} \section{Sketch of Proof of Theorem \ref{the:a}} \label{app:b} Take DL STP of cell-edge users as an example for analysis. If the receiving SIR on the allocated interior sub-band is less than $\theta$, the user is referred to as an edge user and transmits on the edge sub-band reassigned for it. For the edge user whose distance to its SAP is $r$, we have \vspace{-0.2cm} \begin{align} &\mu _{{\rm{D,e}}}^{}(r) \buildrel \Delta \over = \mathbb{P}({\gamma _{\rm{D,e}}} > T\left| {{\gamma _{\rm{D,in}}} < \theta } \right.)\nonumber \\ \overset{({\rm{a}})}{=} & \frac{ {\mathbb{E} \left[ {{\rm{exp}}\left( {{\rm{ - }}\frac{T{I_{{\rm{D}},{\rm{e}}}^{{\Phi _{\rm{s}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}}} \right)} \right]} {\mathbb{E} \left[ {{\rm{exp}}\left( {{\rm{ - }}\frac{T{I_{{\rm{D}},{\rm{e}}}^{{\Phi _{\rm{u}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}}} \right)} \right]}}{1- {\mathbb{E} \left[ {{\rm{exp}}\left( {{\rm{ - }}\frac{\theta{I_{{\rm{D}},{\rm{in}}}^{{\Phi _{\rm{s}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}}} \right)} \right]} {\mathbb{E} \left[ {{\rm{exp}}\left( {{\rm{ - }}\frac{\theta{I_{{\rm{D}},{\rm{in}}}^{{\Phi _{\rm{u}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}}} \right)} \right]} }- \label{eq:6}\\ & \frac{ \mathbb{E}\left[ {{\rm{exp}}\left( {{\rm{ - }}\frac{T{I_{{\rm{D}},{\rm{e}}}^{{\Phi _{\rm{s}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}} - \frac{\theta {I_{{\rm{D,in}}}^{{\Phi _{\rm{s}}}}} }{{{r^{-\alpha} }{P_{\rm{s}}}}} } \right)} \right] \mathbb{E}\left[{{\rm{exp}}\left( {{\rm{ - }}\frac{T I_{{\rm{D}},{\rm{e}}}^{{\Phi _{\rm{u}}}}}{{{r^{-\alpha } }{P_{\rm{s}}}}} - \frac{\theta I_{{\rm{D}},{\rm{in}}}^{{\Phi _{\rm{u}}}}}{{{r^{-\alpha} } {P_{\rm{s}}}}}} \right)}\right] }{1-{\mathbb{E} \left[ {{\rm{exp}}\left( {{\rm{ - }}\frac{\theta{I_{{\rm{D}},{\rm{in}}}^{{\Phi _{\rm{s}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}}} \right)} \right]} {\mathbb{E} \left[ {{\rm{exp}}\left( {{\rm{ - }}\frac{\theta{I_{{\rm{D}},{\rm{in}}}^{{\Phi _{\rm{u}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}}} \right)} \right]}} \nonumber \end{align} where step $(\rm{a})$ is derived from the fact that ${{g}_{{{{x}}_{\rm s}} ,{z_{\rm{e}}}}} $ and ${{g}_{{{{x}}_{\rm s}},{z_{\rm{in}}}}} $ are independent and identically distributed (i.i.d.). In the following, we provide the detailed deviation of $\mathbb{E}\!\left[{{\rm{exp}}\left( {{\rm{ - }}\frac{T{I_{{\rm{D}},{\rm{e}}}^{{\Phi _{\rm{s}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}}} \right)}\right]$ and $\mathbb{E}\!\left[{{\rm{exp}}\left( {{\rm{ - }}\frac{T{I_{{\rm{D}},{\rm{e}}}^{{\Phi _{\rm{s}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}} - \frac{\theta {I_{{\rm{D,in}}}^{{\Phi _{\rm{s}}}}} }{{{r^{-\alpha} }{P_{\rm{s}}}}} } \right)}\right]$ in (\ref{eq:6}). For other items in the equation, we omit the detailed derivation, as they can be calculated similarly. \begin{align} & {\mathbb{E} \left[ {{\rm{exp}}\left( {{\rm{ - }}\frac{T{I_{{\rm{D}},{\rm{e}}}^{{\Phi _{\rm{s}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}}} \right)} \right]}\nonumber\\ =&\prod\limits_{k = 1}^K {\mathbb{E}_{{{\rm{\Phi}}_{{\rm{s}}k}}, {\sigma_{x,{{{z}}_{\rm e}},k}},{g_{x,{{{z}}_{\rm e}}}} }}\left[ {\prod\limits_{x \in {{\rm{\Phi }}_{{\rm{s}}k}}\backslash \{ {x_{\rm{s}}}\} } {\exp \left( {\frac{T{{\sigma_{x,{{{z}}_{\rm e}},k}}}{{g_{x,{{{z}}_{\rm e}}}}}}{{ - {{{r^{-\alpha} }}}{{\left\| x \right\|}^\alpha }}}} \right)} } \right]\nonumber\\ \mathop =\limits^{({\rm{b})}} &\prod\limits_{k = 1}^K{ \!\exp\! \left\{ \!{ - {\lambda _{\rm{s}}} {f(k)}\!\! \!\!\int\limits_{{\mathbb{R}^2}\backslash b(0,r)}\! {\!\!\!\left[ {1 \!-\! {\mathbb{E} }\left[ {\exp \left( {\frac{T{{\sigma_{x,{{{z}}_{\rm e}},k}}}{{g_{x,{{{z}}_{\rm e}}}}}}{{ - {{{r^{-\alpha} }}{{\left\| x \right\|}^\alpha }}}}} \right)} \right]} \right]dx} } \!\right\}}\nonumber\\ =&\prod\limits_{k = 1}^K {\exp \left\{ { - {\lambda _{\rm{s}}}f(k)\int\limits_{{\mathbb{R}^2}\backslash b(0,r)} {\left[ {1 - \mathbb{P}({\sigma_{x,{{{z}}_{\rm e}},k}} = 1) } \right.} } \right.} \label{eq:8}\\ &\cdot \left. {\left. { {\mathbb{E}}\left[ {\exp \left( {\frac{{T{g_{x,{{{z}}_{\rm e}}}}}}{{ - {{r^{-\alpha} }{{\left\| x \right\|}^\alpha }}}}} \right)} \right] - \left( {1 -\mathbb{P}({\sigma_{x,{{{z}}_{\rm e}},k}} = 1)} \right)} \right]dx} \right\}\nonumber\\ =&\prod\limits_{k = 1}^K \exp \left\{ - {\lambda _{\rm{s}}}f(k)\mathbb{P}({\sigma_{x,{{{z}}_{\rm e}},k}} = 1)\right.\nonumber\\ &\cdot\left.\int\limits_{{\mathbb{R}^2}\backslash b(0,r)} {\left\{ 1 - { {\mathbb{E}}\left[ {\exp \left( {\frac{{T{g_{x,{{{z}}_{\rm e}}}}}}{{ - {{r^{-\alpha} }{{\left\| x \right\|}^\alpha }}}}} \right)} \right] } \right\}dx} \right\}\nonumber\\ =& \prod\limits_{k = 1}^K {\exp \left[ { -{\lambda _{\rm{s}}}f(k) p_{\rm{D}}{\chi _{{\rm{D,e}},k}}\int\limits_{{\mathbb{R}^2}\backslash b(0,r)}\!\! {(1 - \frac{1}{{1 + T{r^\alpha }{{\left\| x \right\|}^{ - \alpha }}}})} dx} \right]}\nonumber \\ \mathop =\limits^{({\rm{c})}}& {\exp \left({ - 2\pi {\lambda_{{\rm{D,e}}}}\int_r^\infty {\frac{1}{{1 + {T^{ - 1}}{r^{ - \alpha }}y^{\alpha}}}} ydy} \right)}\nonumber\\ \mathop =\limits^{({\rm{d})}}& {\exp \left( { - \pi{r^2} {\lambda_{{\rm{D,e}}}}{T^{\frac{2}{\alpha }}}\int_{{T^{ - 2/\alpha }}}^\infty {\frac{1}{{1 + {v^{\alpha /2}}}}dv} } \right)} \nonumber \label{eq:9} \end{align} where step $(\rm{b})$ is derived from the probability generating functional (PGFL) of PPP and $b(0,r)$ denotes the disk centered at the origin with radius $r$. We have ${\sigma_{x,{{{z}}_{\rm e}},k}} = 1$ if and only if SAP $x$ in the $k$-th tier is in DL transmission with probability $p_{\rm{D}}$, and SAP $x$ cell allocates sub-band ${{{z}}_{\rm e}}$ to one edge user of non-empty DL buffer with probability ${\chi_{{\rm{D,e}},k}} = \frac{1}{\Delta}\min \left( {\frac{{k{q_{{\rm{D,e}}}}}{{\Xi} _{k}^{\rm{D}}}}{L},1} \right)$. Thus $\mathbb{P}({\sigma_{x,{{{z}}_{\rm e}},k}} = 1)=p_{\rm{D}}{\chi _{{\rm{D,e}},k}} $. For ${q_{{\rm{D,e}}}}$ in ${\chi_{{\rm{D,e}},k}}$, we can find it by ${q_{{\rm{D,e}}}} =1-{q_{{\rm{D,in}}}}$, where ${q_{{\rm{D,in}}}}$ can be derived by first obtaining $q_{{\rm{D,in}}}(r)={{{\eta _1}\left( {{{{{\lambda}}} _{\rm {D,in}}},{{{{\lambda}}} _{\rm {U,in}}},\theta ,r} \right)}}$ according to its definition in a similar way as the denominator of (\ref{eq:6}) and then averaging it on $r$. Step $(\rm{c})$ converts the Cartesian coordinate into the polar coordinate and gives the interference range under the polar coordinate, and variable substitution $v = {\left( {y{r^{ - 1}}{T^{\rm{ - }}}^{1/\alpha }} \right)^2}$ is carried out in step $(\rm{d})$. \vspace{-0.2cm} \begin{align} &\mathbb{E}\left[ {{\rm{exp}}\left( {{\rm{ - }}\frac{T{I_{{\rm{D}},{\rm{e}}}^{{\Phi _{\rm{s}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}} - \frac{\theta{I_{{\rm{D}},{\rm{in}}}^{{\Phi _{\rm{s}}}}}}{{{r^{-\alpha} }{P_{\rm{s}}}}}} \right)} \right]\nonumber\\ =&\prod\limits_{k = 1}^K\! {{\mathbb{E}}\!\left[ {\prod\limits_{x \in \Phi _{{\rm{s}}k}^{}\backslash \{ {x_{\rm s}}\} }\!\!\! {{\mathbb{E}}}\! \left[\exp \! {\left( {\! - \frac{{T {\sigma_{x,{{{z}}_{\rm e}},k}}{g_{x,{{{z}}_{\rm e}}}} }}{{{r^{ - \alpha }}{{\left\| x \right\|}^\alpha }}} - \frac{{\theta {\sigma_{x,{{{z}}_{\rm in}},k}}{g_{x,{{{z}}_{\rm in}}}} }}{{{r^{ - \alpha }}{{\left\| x \right\|}^\alpha }}}} \right)}\! \right] \! }\right]}\nonumber\\ =&\prod\limits_{k = 1}^K {\exp } \left\{{ - {\lambda _{\rm{s}}}{p_{\rm{D}}}f(k)\!\!\!\!\!\int\limits_{{\mathbb{R}^2}\backslash b(0,r)}\!\! \!\!{\left[ {1\! \!-\!\! \left(\!\!1+ \!\!{\frac{{\chi _{{\rm{D,in}},k}}}{{1 + \theta {r^\alpha }{{\left\| x \right\|}^{ - \alpha }}}} - {\chi _{{\rm{D,in}},k}}} \!\!\right)} \right.} } \right.\nonumber\\ &\cdot\left. {\left. {\left( {1+\frac{{{\chi _{{\rm{D,e}},k}}}}{{1 + T{r^\alpha }{{\left\| x \right\|}^{ - \alpha }}}} -{{\chi _{{\rm{D,e}},k}}}} \right)} \right]xdx} \right\}\\ = &\prod\limits_{k = 1}^K {\exp } \left[ { - 2\pi {\lambda _{\rm{s}}}{p_{\rm{D}}}f(k){r^2}\zeta (T,\theta ,{\chi _{{\rm{D,in}},k}},{{\chi _{{\rm{D,e}},k}}}) } \right].\nonumber \end{align} It is noteworthy that the locations of scheduled UL users can be regarded as a Voronoi perturbed lattice process and approximated as PPP, thus the UL interference analysis is similar to that of the DL \cite{Yang2017Packet}. To study STP for interior users, we can adopt the same approach but set $\Delta$ to 1. \end{appendices} \renewcommand\refname{Reference}
{'timestamp': '2020-10-13T02:27:41', 'yymm': '2010', 'arxiv_id': '2010.05426', 'language': 'en', 'url': 'https://arxiv.org/abs/2010.05426'}
arxiv
\section{Introduction} \label{section 1} With the development of deep learning technology, pattern recognition based on deep neural network has been greatly developed, such as image recognition and speech recognition \cite{face-recognition,speech-recognition}. Although some deep learning methods have achieved great success, there are still many challenges and difficulties that need to be addressed in these applications. One of these challenges is that the test set may contain some classes that are not present in the training set. Unfortunately, the traditional deep neural network is incapable of detecting unknown classes. Therefore, open set recognition (\textbf{OSR}) was proposed to solve this kind of problem that the model needs to not only correctly classify known classes, but also identify unknown classes\cite{1-vs-set}. In contrast to OSR, the test set and the training set contain the same data categories in closed set recognition (\textbf{CSR}), and classifying known classes correctly corresponds to reducing the empirical risk. Therefore, OSR needs to reduce not only the empirical risk, but also the open space risk\cite{1-vs-set}, which corresponds to identifying unknown classes effectively. Due to the strong feature extraction ability, there is no doubt that deep neural network can do well in CSR. As shown in Fig.\ref{Softmax(test set)}, the LeNet++ trained with SoftMax can classify MNIST effectively. However, it can be seen from Fig.\ref{Softmax(open set)} that there is obvious overlap between known and unknown classes features. The overlapping of these features in the feature space is the direct cause of the open space risk. In order to reduce the two risks simultaneously, Yang \etal proposed the generalized convolutional prototype learning (\textbf{GCPL}) for robust classification and OSR\cite{GCPL,CPN}. It can be seen from Fig.\ref{GCPL(test set)} that the LeNet++ trained with GCPL can classify MNIST effectively. With regard to the open space risk, as shown in Fig.\ref{GCPL(open set)}, although much better than SoftMax, there are still three clusters of known features that overlap with unknown features. Similar to SoftMax, it will be seen from Section \ref{section 3} that the way GCPL trains the network has disadvantages in reducing the open space risk. \begin{figure*}[ht] \centering \subfigure[SoftMax(test set)] {\label{Softmax(test set)} \includegraphics[width=0.67\columnwidth]{Softmax_test_set.png} } \subfigure[GCPL(test set)] {\label{GCPL(test set)} \includegraphics[width=0.67\columnwidth]{GCPL_test_set.png} } \subfigure[SLCPL(test set)] { \label{SLCPL(test set)} \includegraphics[width=0.67\columnwidth]{SLCPL_test_set.png} } \subfigure[SoftMax(open set)] {\label{Softmax(open set)} \includegraphics[width=0.67\columnwidth]{Softmax_open_set.png} } \subfigure[GCPL(open set)] {\label{GCPL(open set)} \includegraphics[width=0.67\columnwidth]{GCPL_open_set.png} } \subfigure[SLCPL(open set)] { \label{SLCPL(open set)} \includegraphics[width=0.67\columnwidth]{SLCPL_open_set.png} } \caption{\textbf{The visualization results of LeNet++ on known and unknown classes}\cite{objectosphere}. In this figure, MNIST(gray) is used for training the LeNet++ network, while KMNIST(blue), SVHN(red), CIFAR10(green), CIFAR100 (yellow) and TinyImageNet(pink) are used for open set evaluation. The first row in the figure shows the visualization results on the MNIST test set under different methods. According to the second row of the figure, our SLCPL can reduce the open space risk more effectively than other methods.} \label{fig.1} \end{figure*} As shown in Figs.\ref{Softmax(open set)} and \ref{GCPL(open set)}, we already know that the direct cause of the open space risk is that known and unknown classes features overlap in the feature space. In other words, if we can figure out why they overlap, then it's possible to significantly reduce, or even eliminate the open space risk. Therefore, the distribution of known and unknown features is further studied in this paper. And then, we find the origin of the open space risk, which is critical to address the OSR problem. On the basis of understanding the origin of the open space risk, we propose the spatial location constraint prototype loss (\textbf{SLCPL}) for OSR, which adds a constraint term to control the spatial location of the prototypes in the feature space. As shown in Fig.\ref{SLCPL(test set)}, while effectively reducing the empirical risk, SLCPL controls the clustering of known classes in the edge region of the feature space. And it can be seen from Fig.\ref{SLCPL(open set)} that SLCPL can also reduce the open space risk effectively. Our contributions mainly focus on the following: \begin{itemize} \item The distribution of known and unknown features is analyzed in detail, and then we discusse the root cause of the open space risk in this paper. \item A novel loss function, SLCPL, is proposed to address the OSR problem. \item Many experiments and analyses have proved our theory about the origin of the open space risk and the effectiveness of the proposed loss function. \end{itemize} \section{Related Work} \subsection{Open Set Recognition} Scheirer \etal first defined the OSR issue in 2013\cite{1-vs-set}. When deep learning performance was not as good as it is today, most of the work on OSR was based on support vector machine, such as \cite{1-vs-set,w-svm,p_i-svm,BFHC-1,BFHC-2,SVM-64,SVM-65,EPCC}. Subsequently, the traditional method represented by support vector machine is gradually replaced by the deep neural network. The open space risk is called "agnostophobia" by Dhamija \etal. Apart from using LeNet++ to assess the open space risk, they also proposed a novel Objectosphere loss function for OSR\cite{objectosphere}. Bendale \etal proposed the OpenMax model, which replaces the SoftMax layer by the OpenMax layer to predict the probability of unknown classes\cite{OpenMax}. Ge \etal combined the characteristics of generative adversarial network\cite{GAN} and OpenMax, and proposed the G-OpenMax model, which trains deep neural network with generated unknown classes\cite{G-OpenMax}. Neal \etal proposed the OSRCI model for OSR, which also adds generated samples into the training phase\cite{OSRCI}. Some works based on the reconstruction idea also make important contributions to OSR, such as \cite{CROSR}. Although various algorithms or theories have been put forward to address the OSR problems, almost no one analyzes the root cause of the open space risk, and this paper will discuss this problem in Section \ref{section 3}. \subsection{Prototype Learning} The prototype is often regarded as one or more points in the feature space to represent the clustering of a specific category. Wen \etal proposed a center loss to improve the face recognition accuracy, and it can learn more discriminative features\cite{center_loss}. Similar to ~\cite{center_loss}, Yang \etal proposed the generalized convolutional prototype learning(GCPL) for robust classification\cite{GCPL}. Subsequently, this model was modified to convolutional prototype network(CPN) for OSR\cite{CPN}. Although GCPL can effectively improve the compactness of the feature clustering, as shown in the Figs.\ref{GCPL(test set)} and \ref{GCPL(open set)}, simply increasing intra-class compactness still creates the open space risk slightly. Therefore, this paper propose a novel loss function that adds spatial location constraints to the prototype to further reduce the open space risk. \section{The Nature of Open Set Recognition} \label{section 3} According to the Fig.\ref{fig.1}, we believe that studying the distribution of known classes and unknown classes in the feature space is the key to solving OSR problems. Therefore, This section try to figure out why the known class features and unknown class features may overlap in the feature space. \subsection{Feature Distribution of Known Classes} According to the different rules of feature distribution, we divide the feature distribution of known classes into two categories: the half open space distribution, and the prototype subspace distribution. \textbf{The half-open space distribution}. When the neural network is trained with SoftMax, the function of the last fully connected layer in the network is equivalent to the establishment of several hyper-planes in the feature space. These hyper-planes divide the feature space into several half-open spaces, with each known class occupying one corresponding half-open space. As shown in Fig.\ref{Softmax(test set)}, the $10$ known classes seem to be separated by $10$ potential rays drawn from the spatial origin, and entire $2$D feature space is divided into several half-open spaces by these potential rays. \textbf{The prototype subspace distribution}. When the neural network is trained with the prototype learning, the prototype subspace distribution is created. In this kind of distribution, the whole feature space is divided into several known class subspace and residual space(residual space is also called the open space) by the prototypes, and each known class subspace is represented as a hyper-sphere. As shown in Fig.\ref{GCPL(test set)}, each known class feature is distributed in the circle determined by the each prototype. Because GCPL does not limit the spatial location of the prototypes, the known features are possible to be distributed in the center region of the feature space. Moreover, the feature distribution of our SLCPL also falls into this category, but our model constrains the spatial location of the prototypes to be distributed in the edge region of the feature space, as shown in Fig.\ref{SLCPL(test set)}. In the supplementary material, we give more details and discussion about these two feature distribution. \subsection{Feature Distribution of Unknown Classes} From Figs.\ref{Softmax(open set)}, \ref{GCPL(open set)} and \ref{SLCPL(open set)}, we can see that whatever the unknown class is, its feature usually tend to be distributed in the center region of the entire feature space. Next, we try to explain the inevitability of this phenomenon. As we all know, convolution neural network(\textbf{CNN}) extracts the sample features through the convolution kernel. The convolution kernels of a trained network contain template information that matches the known classes well. In the test phase, the template contained in the convolution kernel is used to match the test samples. If they match well, the convolution operation will get a higher score; Otherwise, the score will be lower. The same goes for fully connected networks. \begin{figure}[ht] \centering \subfigure[The convolution kernel matches the sample.] {\label{convolution 1} \includegraphics[width=1.0\columnwidth]{convolution_1.jpg} } \subfigure[The convolution kernel doesn't match the sample.] {\label{convolution 2} \includegraphics[width=1.0\columnwidth]{convolution_2.jpg} } \caption{\textbf{The diagram of the convolution process}.} \label{convolution process} \end{figure} \begin{figure*}[ht] \centering \subfigure[SoftMax] {\label{softmax with 3 images} \includegraphics[width=0.67\columnwidth]{softmax_real_image.PNG} } \subfigure[GCPL] {\label{GCPL with 3 images} \includegraphics[width=0.67\columnwidth]{GCPL_real_image.PNG} } \subfigure[SLCPL] {\label{SLCPL with 3 images} \includegraphics[width=0.67\columnwidth]{SLCPL_real_image.PNG} } \caption{\textbf{The location diagram of three specific samples in the feature space}. The stars represent the spatial location of the three samples("cat", "2" and "8").} \label{fig.4} \end{figure*} \begin{figure}[ht] \centering \includegraphics[width=1.0\columnwidth]{cat_2_8.jpg} \caption{\textbf{The visualization results of the last convolution feature map in LeNet++}. Different $3$ columns(rows) correspond to different $3$ methods(samples). Since the last convolution feature map of the LeNet++ network is $128$ channels, each subfigure contains $128$ subgraphs.} \label{fig.5} \end{figure} As shown in Fig.\ref{convolution process}, we illustrate this matching process with two simple examples of convolution. When the convolution kernel matches the sample well, it can be seen from Fig.\ref{convolution 1} that the convolution operation can get the higher value feature. These flattened features determine the position of the sample in the feature space, and higher value features correspond to higher coordinate values in the feature space. On the contrary, as shown in Fig.\ref{convolution 2}, the mismatch between the sample and the convolution kernel will result in small coordinate values of the sample in the feature space, which will make the unmatched sample distributed in the center region of the feature space. In order to further illustrate this problem, we chose three specific samples, namely "cat", "2" and "8", and we performed visualization analysis on them. Their locations in the feature space are shown in Fig.\ref{fig.4}. Among them, the sample "cat" is located in the center region of the feature space. According to our theory, the value of the unknown feature should be less than the value of the known feature(it's strictly absolute value, but for convenience we don't make a clear specification as here). Therefore, we visualized the feature map after the last convolution operation in the LeNet++ network. As shown in Fig.\ref{fig.5}, The brighter the area, the higher the value. By comparing these $9$ subfigures, we can find the following patterns: \begin{itemize} \item In all three methods, the brightness of the "cat" feature is always lower than that of the samples "2" and "8". \item The brightness of the SoftMax feature map is significantly higher than that of GCPL and SLCPL. \item In the GCPL feature maps, the brightness of the samples "2" is slightly lower than that of the samples "8". \item In the SLCPL feature maps, the brightness of the samples "2" is almost equal to that of the samples "8". \end{itemize} All these phenomena confirm the correctness of our theory. The reason why the convolution kernel is not visualized here is that it is difficult for human eyes to recognize the template contained in the convolution kernel. More details are provided in the supplementary material. \textbf{Summary}. Finally, we summarize the origin of the open space risk: First, a CNN is trained with known classes, and most current training methods(such as SoftMax, GCPL) cannot avoid the known features distributed in the center region of the feature space. And then, because of the mismatch between unknown classes and the convolution kernel, unknown classes usually tend to be distributed in the center region of the feature space. Therefore, the open space risk occurs when known and unknown features overlap in the center region of the feature space. \section{Spatial Location Constraint Prototype Loss} According to the origin of the open space risk we explored in section \ref{section 3}, if we can control the known features to be distributed in the edge region of the feature space, it will reduce the open space risk effectively. Therefore, we propose the loss function SLCPL to accomplish this purpose. Since SLCPL is an improvement on GCPL, we will introduce GCPL first. \textbf{GCPL}. Given training set $D=\{(x_1,y_1), (x_2,y_2), \cdots\}$ with $N$ known classes, the label of original data $x_i$ is $y_i \in \{1,\cdots,N\}$. A CNN is used as a classifier, whose parameters and embedding function are denoted as $\theta$ and $\Theta$. The prototypes $O=\{O^i, i=1,2,\cdots,N\}$ are initialized randomly or with a distribution(such as a Gaussian distribution). For a training sample $(x,y)$, the GCPL loss function can be expressed by \begin{equation} \label{GCPL loss} l_G(x,y;\theta,O) = l(x,y;\theta,O) + \lambda pl(x;\theta,O), \end{equation} where the optimization of $l(x,y;\theta,O)$ is used to classify the different known classes, $\lambda$ is a hyper-parameter, and the constraint term $pl(x;\theta,O)$ is used to make the cluster more compact. Specifically, $l(x,y;\theta,O)$ can be expressed as \begin{equation} \begin{split} l(x,y;\theta,O) &= -\log p(y=k|x,\Theta,O) \\ &= -\log\frac{e^{-d(\Theta(x), O^k)}}{\sum_{i=1}^N e^{-d(\Theta(x), O^i)}}, \end{split} \end{equation} where the $d(\Theta(x), O^i)$ is the Euclidean distance between $\Theta(x)$ and $O^i$. And the constraint term $pl(x;\theta,O)$ can be expressed as \begin{equation} pl(x;\theta,O) = \|\Theta(x^k)- O^k\|^2_2, k=1,\cdots,N, \end{equation} where the $x^k$ is the training samples of class $k$. Under the optimization of Eq.\eqref{GCPL loss}, the known features extracted from the network will present the prototype subspace distribution, such as Fig.\ref{GCPL(test set)}. \textbf{SLCPL}. According to the theory introduced in this paper, as long as the known feature clusters can be constrained in the edge region of the feature space, the open space risk can be effectively reduced. Therefore, we proposed the spatial location constraint prototype loss based on GCPL: \begin{equation} \label{SLCPL loss} l_S(x,y;\theta,O) = l_G(x,y;\theta,O) + slc(O). \end{equation} In Eq.\eqref{SLCPL loss}, the spatial location constraint term $slc(O)$ can be expressed as \begin{equation} slc(O) = \frac{1}{N-1}\sum_{i=1}^N(r_i-\frac{1}{N}\sum_{j=1}^Nr_j)^2, \end{equation} where $r_i=d(O^i,O_c)$ and $O_c=\frac{1}{N}\sum_{i=1}^NO^i$. In other words, the term $slc(O)$ is the variance of the distances $r_i$ between the prototypes and the center $O_c$. Here, choosing $O_c$ instead of coordinate origin as the center is more beneficial to the optimization of the training process. By controlling the variance of these distances, the known feature clusters in Fig.\ref{GCPL(test set)} can be manipulated into the distributions in Fig.\ref{SLCPL(test set)}. \textbf{How to detect unknown classes}? In our method, known features are required to cluster. Therefore, the distance between the feature and the prototype can be used to measure the probability of which category it belongs to. Specifically, the probability that $x$ in the test set belongs to a known class can be determined by the following formula: \begin{equation} \label{probability} p(\hat y=k|x) \propto \ \exp\big(-\min_{k\in\{1,\cdots,N\}} d(\Theta(x), O^k)\big). \end{equation} Based on the distance distribution from the known features to the corresponding prototypes, a threshold value $\tau$ can be determined. When the distance between the sample feature and the prototype is greater than the threshold $\tau$, the sample will be identified as unknown class; Otherwise, the category is further determined according to Eq.\eqref{probability}. However, the optimal threshold is not easy to determine, so we provides a calibration-free measure of detection performance in the section \ref{section 5} for experiments. \section{Experiments} \label{section 5} \subsection{Experimental Settings} \label{section 5.1} \textbf{Datasets}. We provide a simple summary of these protocols for each data set. \begin{itemize} \item \textbf{MNIST}\cite{MNIST},\textbf{SVHN}\cite{SVHN},\textbf{CIFAR10}\cite{CIFAR}. Each of these three datasets contains $10$ classes. $6$ categories are randomly selected as known classes, and the remaining $4$ categories are unknown classes. \item \textbf{CIFAR+10},\textbf{CIFAR+50}. For these two datasets, $4$ known classes are randomly sampled from CIFAR10 for training. $10$ and $50$ classes are randomly sampled from CIFAR100 respectively, which are used as unknown classes. \item \textbf{TinyImageNet}\cite{TinyImageNet}. $20$ known classes and $180$ unknown classes are randomly sampled for evaluation. \end{itemize} \textbf{Evaluation Metrics}. We choose the accuracy and Area Under the Receiver Operating Characteristic(\textbf{AUROC}) curves to evaluate the performance of classifying known classes and identifying unknown classes respectively\cite{AUROC}. \textbf{Network Architecture}. In order to make a fair comparison with the evaluation results of Neal \etal\cite{OSRCI}, we also adopted the same encoder network structure for experiments. \textbf{Other Settings}. In our experiments, the hyper-parameter $\lambda$ is set to $0.1$. The momentum stochastic gradient descent (SGD-M) optimizer is used to optimize the classifier. The initial learning rate of the network is set to $0.1$, dropping to one-tenth of the original rate every $30$ epochs, and we train the network for $100$ epochs. \subsection{Ablation Study} An important factor affecting OSR performance is the openness, which is defined by \cite{1-vs-set}, and it can be expressed as \begin{equation} \mathbb{O} = 1 - \sqrt{\frac{2*N_{train}}{N_{test}+N_{target}}}, \end{equation} where $N_{train}$ is the number of known classes, $N_{test}$ is the number of test classes that will be observed during testing, and $N_{target}$ is the number of target classes that needs to be correctly recognized during testing. In this section, we analyze the proposed methods on CIFAR100\cite{CIFAR}, which consists of $100$ classes. We randomly sample $15$ classes out of $100$ classes as known classes and varying the number of unknown classes from $15$ to $85$, which means openness is varied from $18\%$ to $49\%$. The performance is evaluated by the macro-average F1-score in $16$ classes($15$ known classes and unknown). For ablation study, the network model only trained with $l(x,y;\theta,O)$ is denoted as prototype loss, abbreviated as \textbf{PL}. The experimental results are shown in Fig.\ref{Macro Average F1-score with openness}. The performance of PL, GCPL, and SLPL increases in successively, which proves the effectiveness of the proposed method. \begin{figure}[ht] \centering \includegraphics[width=1.0\columnwidth]{Openness_SLCPL.png} \caption{\textbf{Macro Average F1-score against varying Openness with different methods for ablation analysis}. } \label{Macro Average F1-score with openness} \end{figure} \subsection{Fundamental Experiments} Because OSR needs to reduce the empirical risk and the open space risk simultaneously, we conducted two experiments to explore the performance of the proposed method respectively. As shown in Tab.\ref{CSR results}, whether it is simple MNIST or complex CIFAR10, the CSR accuracy results of proposed method have an advantage in both mean and variance, which shows that our method can well reduce the empirical risk. Compared with GCPL, the constraint term $slc(O)$ proposed in this paper does not reduce the accuracy of CSR, but improves it. \begin{table}[ht] \begin{center} \begin{tabular}{|c|c|c|c|} \hline Method & MNIST(\%) & SVHN(\%) & CIFAR10(\%) \\ \hline\hline SoftMax\cite{OSRCI} & 99.5$\pm$0.2 & 94.7$\pm$0.6 & 80.1$\pm$3.2 \\ OpenMax\cite{OpenMax} & 99.5$\pm$0.2 & 94.7$\pm$0.6 & 80.1$\pm$3.2 \\ G-OpenMax\cite{G-OpenMax} & 99.6$\pm$0.1 & 94.8$\pm$0.8 & 81.6$\pm$3.5 \\ OSRCI\cite{OSRCI} & 99.6$\pm$0.1 & 95.1$\pm$0.6 & 82.1$\pm$2.9 \\ CROSR\cite{CROSR} & 99.2$\pm$0.1 & 94.5$\pm$0.5 & 93.0$\pm$2.5 \\ RPL\cite{RPL} & \textbf{99.8}$\pm$0.1 & 96.9$\pm$0.4 & 94.5$\pm$1.7 \\ GCPL\cite{CPN} & 99.7$\pm$0.1 & 96.7$\pm$0.4 & 92.9$\pm$1.2 \\ \hline\hline SLCPL & \textbf{99.8}$\pm$0.1 & \textbf{97.1}$\pm$0.3 & \textbf{94.6}$\pm$1.2 \\ \hline \end{tabular} \end{center} \caption{The closed set accuracy results test on various methods and datasets. Every value is averaged among five randomized trials. We report the corresponding results from \cite{CPN,OSRCI,CROSR}, and reproduce the RPL results from \cite{RPL}.} \label{CSR results} \end{table} \begin{table*} \begin{center} \begin{tabular}{|c|c|c|c|c|c|c|} \hline Method & MNIST(\%) & SVHN(\%) & CIFAR10(\%) & CIFAR+10(\%) & CIFAR+50(\%) & TinyImageNet(\%) \\ \hline\hline SoftMax\cite{OSRCI} &97.8$\pm$0.6&88.6$\pm$1.4&67.7$\pm$3.8&81.6$\pm$-&80.5$\pm$-&57.7$\pm$-\\ OpenMax\cite{OpenMax} &98.1$\pm$0.5&89.4$\pm$1.3&69.5$\pm$4.4&81.7$\pm$-&79.6$\pm$-&57.6$\pm$-\\ G-OpenMax\cite{G-OpenMax}&98.4$\pm$0.5&89.6$\pm$1.7&67.5$\pm$4.4&82.7$\pm$-&81.9$\pm$-&58.0$\pm$-\\ OSRCI\cite{OSRCI} &98.8$\pm$0.4&91.0$\pm$1.0&69.9$\pm$3.8&83.8$\pm$-&82.7$\pm$-&58.6$\pm$-\\ CROSR\cite{CROSR} &99.1$\pm$0.4&89.9$\pm$1.8 & - & - & - &58.9$\pm$-\\ RPL\cite{RPL} &99.3$\pm$-&95.1$\pm$-&\textbf{86.1}$\pm$-& 85.6$\pm$- & 85.0$\pm$- & 70.2$\pm$-\\ GCPL\cite{CPN} &99.0$\pm$0.2&92.6$\pm$0.6&82.8$\pm$2.1&88.1$\pm$-&87.9$\pm$-&63.9$\pm$-\\ \hline\hline SLCPL& \textbf{99.4}$\pm$0.1&\textbf{95.2}$\pm$0.8&\textbf{86.1}$\pm$1.4&\textbf{91.6}$\pm$1.7&\textbf{88.8}$\pm$0.7&\textbf{74.9}$\pm$1.4\\ \hline \end{tabular} \end{center} \caption{The AUROC results of the OSR test on various methods and datasets. Every value is averaged among five randomized trials. We report the corresponding results from \cite{CPN,OSRCI,CROSR,RPL}. Standard deviation values for state of the art are not available for CIFAR+10, CIFAR+50 and TinyImageNet.} \label{AUROC results} \end{table*} \begin{figure*}[ht] \centering \subfigure[t-SNE (MNIST, Plain CNN)] {\label{t-SNE-MNIST} \includegraphics[width=0.67\columnwidth]{Visualization_1.png} } \subfigure[t-SNE (open set, Plain CNN)] {\label{t-SNE-open-set} \includegraphics[width=0.67\columnwidth]{Visualization_2.png} } \subfigure[Distance distribution diagram (Plain CNN)] { \label{distance_1} \includegraphics[width=0.67\columnwidth]{Distance_Analysis.png} } \subfigure[2D-features (open set, LeNet++)] { \label{2D-open-set} \includegraphics[width=0.67\columnwidth]{SLCPL_open_set_2.png} } \subfigure[Distance distribution diagram (LeNet++)] { \label{distance_2} \includegraphics[width=0.67\columnwidth]{Distance_Analysis_2.png} } \caption{\textbf{The visualization and distance distribution diagram of two network structures}. The first row of this figure corresponds the experiment results of Plain CNN in section \ref{section 5}, and the dimension of Plain CNN's feature space is $128$, so we use t-SNE to visualize its features. And the second row of this figure corresponds the experiment results of LeNet++ in section \ref{section 1}.} \label{fig.6} \end{figure*} \begin{table*}[ht] \begin{center} \begin{tabular}{|c|c|c|c|c|} \hline Method &ImageNet-crop(\%) &ImageNet-resize(\%) &LSUN-crop(\%) &LSUN-resize(\%) \\ \hline\hline SoftMax\cite{OSRCI} &63.9 &65.3 &64.2 &64.7 \\ OpenMax\cite{OpenMax} &66.0 &68.4 &65.7 &66.8 \\ LadderNet+SoftMax\cite{CROSR} &64.0 &64.6 &64.4 &64.7 \\ LadderNet+OpenMax\cite{CROSR} &65.3 &67.0 &65.2 &65.9 \\ DHRNet+Softmax\cite{CROSR} &64.5 &64.9 &65.0 &64.9 \\ DHRNet+Openmax\cite{CROSR} &65.5 &67.5 &65.6 &66.4 \\ OSRCI\cite{OSRCI} &63.6 &63.5 &65.0 &64.8 \\ CROSR\cite{CROSR} &72.1 &73.5 &72.0 &74.9 \\ C2AE\cite{CGDL} &83.7 &82.6 &78.3 &80.1 \\ CGDL\cite{CGDL} &84.0 &83.2 &80.6 &81.2 \\ RPL\cite{RPL} &84.6 &83.5 &85.1 &87.4 \\ GCPL\cite{CPN} &85.0 &83.5 &85.3 &88.4 \\ \hline\hline SLCPL &\textbf{86.7} &\textbf{85.9} &\textbf{86.5} &\textbf{89.2} \\ \hline \end{tabular} \end{center} \caption{Open set recognition results on CIFAR10 with various outliers added to the test set as unknowns. The performance is evaluated by macro-averaged F1-scores in $11$ classes ($10$ known classes and $1$ unknown class). We report the experiment results from \cite{CROSR,CGDL}, and reproduce the GCPL and RPL from \cite{CPN,RPL}.} \label{ImageNet LSUN results} \end{table*} \begin{table}[ht] \begin{center} \begin{tabular}{|c|c|c|c|} \hline Method & Omniglot(\%) & M-noise(\%) & Noise(\%) \\ \hline\hline SoftMax\cite{OSRCI} &59.5 &80.1 &82.9 \\ OpenMax\cite{OpenMax} &78.0 &81.6 &82.6 \\ CROSR\cite{CROSR} &79.3 &82.7 &82.6 \\ CGDL\cite{CGDL} &85.0 &88.7 &85.9 \\ RPL\cite{RPL} &96.4 &92.6 &99.1 \\ GCPL\cite{CPN} &97.1 &93.5 &99.5 \\ \hline\hline SLCPL &\textbf{97.9} &\textbf{93.7} &\textbf{99.6} \\ \hline \end{tabular} \end{center} \caption{Open set recognition results on MNIST with various outliers added to the test set as unknowns. The rest of the information is similar to Tab.\ref{ImageNet LSUN results}.} \label{Omniglot results} \end{table} Similar to Tab.\ref{CSR results}, as the difficulty of OSR increases, it can be seen from Tab.\ref{AUROC results} that the performance difference between different methods becomes larger and larger. In this experiment, the method proposed in this paper has the strongest ability to identify unknown classes on all data sets. In particular, the comparison with GCPL results further proves the validity of the constraint term $slc(O)$ proposed in this paper. Compared with GCPL, only adding a constraint term to the loss function can greatly improve the OSR performance, which is derived from the analysis of the origin of the open space risk. \subsection{Visualization and Distance Analysis} In order to better illustrate the theory and model presented in this paper, this section presents the experiment results on SLCPL through visualization and distance analysis. For convenience, the network described in section \ref{section 5.1} is denoted here as Plain CNN. As shown in the first row of Fig.\ref{fig.6}, in this experiment, known classes come from $6$ categories in MNIST, while the remaining $4$ categories in MNIST are used as unknown classes, and this data category setting can be seen from the $10$ clusters in Fig.\ref{t-SNE-MNIST}. In the Fig.\ref{t-SNE-open-set}, KMNIST, SVHN, CIFAR10, CIFAR100 and TinyImageNet are used for open set evaluation, and it can be seen from this figure that the network can distinguish the known and unknown classes(open set), except that a few open set data features overlap with known features. In the Fig.\ref{distance_1}, we evaluated the distance distribution of known and unknown features to the center $O_c$, which corresponds to Fig.\ref{t-SNE-open-set}. As shown in Fig.\ref{distance_1}, most of the unknown features have smaller distances to the spatial center than the known features. In the second row of Fig.\ref{fig.6}, we show the experimental results when the network structure is LeNet++. The distance distribution in Fig.\ref{distance_2} corresponds to the feature distribution in Fig.\ref{2D-open-set}. As shown in Fig.\ref{distance_2}, almost all of the unknown features are less distant from the center of feature space than the known features. The distance analysis results of the two different network structures in Figs.\ref{distance_1} and \ref{distance_2} both prove the view of this paper that unknown features usually tend to be distributed in the center region of the feature space. In addition, although the results of these $2$ figures prove our theory, it is obvious that the performance in Fig.\ref{distance_2} is better than that in Fig.\ref{distance_1}, which may be related to the network architecture and the dimension size of the feature space. \subsection{Further Experiments} \textbf{Experiment I}. All samples from the $10$ classes in CIFAR10 are considered as known classes, and samples from ImageNet and LSUN are selected as unknown samples\cite{LSUN}. The Settings for data sets are the same as in \cite{CROSR}, and the other experimental settings are the same as in Section \ref{section 5.1}. The results are shown in Tab.\ref{ImageNet LSUN results}. \textbf{Experiment II}. All samples from the $10$ classes in MNIST are considered as known classes, and samples from Omniglot\cite{Omniglot}, MNIST-noise(denoted as M-noise) and Noise are selected as unknown samples. Omniglot is a data set containing various alphabet characters. Noise is a synthesized data set by setting each pixel value independently from a uniform distribution on $[0, 1]$. M-Noise is also a synthesized data set by adding noise on MNIST testing samples. The Settings for data sets are the same as in \cite{CROSR}, and the other experimental settings are the same as in Section \ref{section 5.1}. The results are shown in Tab.\ref{Omniglot results}. In these $2$ experiments, we can see from the results that on all given datasets, the proposed method is more effective than previous methods and achieves a new state-of-the-art performance. Especially, compared with GCPL, these results once again prove the validity of the constraint term $slc(O)$ proposed in this paper. \section{Conclusion} As mentioned in this paper, the difficulty of OSR lies in how to reduce the open space risk. To reduce the open space risk, we need to understand why it occurs first. Therefore, this paper explores the direct and root causes of the open space risk. As discussed in section \ref{section 3}, the distribution of known and unknown features determines the open space risk. Because of the mismatch between the unknown class samples and the network convolution kernel, the unknown features usually tend to be distributed in the center region of the feature space. Therefore, it is natural for us to think that if the known features can be distributed in the edge region of the feature space by adjusting the loss function, then the open space risk can be effectively reduced. Based on the above analysis and discussion, we propose the SLCPL loss function. Finally, a large number of experiments and analysis have proved our theory of the open space risk and the effectiveness of our SLCPL. {\small \bibliographystyle{unsrt}
{'timestamp': '2021-11-15T02:12:48', 'yymm': '2110', 'arxiv_id': '2110.11013', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.11013'}
arxiv
\section{Introduction} \IEEEPARstart{L}{earning} network topologies from data is very appealing. On the \textit{interpretable} side, the structure of a network reveals important descriptors of the network itself, providing to humans a prompt and explainable decision support system; on the \textit{operative} side, it is a requirement for processing and learning architectures operating on graph data, such as graph filters~\cite{coutino2019advances}. When this structure is not readily available from the application, a fundamental question is how to \textit{learn} it from data. The class of problems and the associated techniques concerning the identification of a network structure (from data) are known as graph topology identification (GTI), graph learning, or network topology inference~\cite{mateos2019connecting, dong2019learning}. While up to recent years the GTI problem has been focused on learning \textit{static} networks, i.e., networks which do not change their structure over time, the pervasiveness of networks with a \textit{time-varying} component has quickly demanded new learning paradigms. This is the case for biological networks~\cite{kim2014inference}, subject to changes due to genetic and environmental factors, or financial markets~\cite{mantegna1999hierarchical}, subject to changes due to political factors, among others. In these scenarios, a static approach would fail in accounting for the temporal variability of the underlying structure, which is strategic to, e.g., detect anomalies or discover new emerging communities. In addition, prior (full) data availability should not be considered as a given. In real time applications, data need to be processed on-the-fly with low latency to, e.g., identify and block cyber-attacks in a communication infrastructure, or fraudulent transactions in a financial network. Thus, another learning component to take into account, is the modality of data acquisition. Here, we consider the extreme case in which data are processed on-the-fly, i.e., a fully \textit{online} scenario. It is then clear how the necessity of having algorithms to learn time-varying topologies from online data is motivated by physical scenarios. For clarity, we elaborate on the three keywords - identification, time-varying and online - which constitute, other than the title of the present work, also its main pillars. \begin{itemize} \item \textit{Identification/learning}: it refers to the (optimization) process of learning the graph topology. \item \textit{Time-Varying/dynamic}: it refers to the temporal variability of the graph in its edges, in opposition to the static case. \item \textit{Online/streaming}: it refers to the modality in which the data arrive and/or are processed, in opposition to a batch approach which makes use of the entire bulk of data. \end{itemize} This emphasis on the terminology is important to understand the differences between the different existing works, presented next. \subsection{Related Works} \label{sec:related-works} Static GTI has been originally addressed from a statistical viewpoint and only in the past decade under a graph signal processing (GSP) framework~\cite{sandryhaila2013discrete}, in which different assumptions are made on how the data are coupled with the unknown topology; see \cite{mateos2019connecting, dong2019learning} for a tutorial. Only recently, dynamic versions of the static counterparts have been proposed. For instance, \cite{kalofolias2017learningtvgraphs, yamada2020time} learn a sequence of graphs by enforcing a prior (smoothness or sparsity) on the edges of consecutive graphs; similarly, the work in \cite{hallac2017network} extends the graphical Lasso \cite{friedman2008sparse} to account for the temporal variability, i.e., by estimating a sparse time-varying precision matrix. In addition to these works, the inference of causal relationships in the network structure, i.e., directed edges, has been considered in~\cite{baingana2017cascades, money2021online}. See~\cite{giannakis2018topology} for a review of dynamic topology inference approaches. The mentioned approaches tackle the dynamic graph learning problem by means of a two-step approach: \textit{i)} first, all the samples are collected and split into possibly overlapping windows; \textit{ii)} only then the topology associated to each window is inferred from the data, possibly constrained to be similar to the adjacent ones. This modus-operandi fails to address the \textit{online} (data-streaming) setting, where data have to be processed on-the-fly either due to architectural (memory, processing) limitations or (low latency) application requirements, such as real-time decision making. This line of work has been freshly investigated by~\cite{vlaski2018online}, which considers signals evolving according to a heat diffusion process, and by~\cite{shafipour2020online}, which assumes the data are graph stationary~\cite{marques2017stationary}. In~\cite{zaman2020online}, the authors consider a vector autoregressive model to learn causality graphs by exploiting the temporal dependencies, while~\cite{saboksayr2021online} proposes an online task-dependent (classification) graph learning algorithm, in which class-specific graphs are learned from labeled signals (training phase) and then used to classify new unseen data. Differently from these works, our goal here is to provide a general (model-independent) algorithmic framework for time-varying GTI from online data that can be specialized to a variety of static graph learning problems. In particular, the generalization given by the framework enables us to render a static graph learning problem into its time-varying counterpart and to solve it via novel time-varying optimization techniques~\cite{simonetto2020time}, providing a trade off between the solution accuracy and the velocity of execution. We introduce ad-hoc vectorization schemes for structured matrices to solve graph learning problems in the context of the Gaussian graphical model, the structural equation model, and the smoothness based model. All in all, a mature time-varying GTI framework for online data is yet to be conceived. This is our attempt to pave the way for a unified and general view of the problem, together with solutions to solve it. \subsection{Contributions} This paper proposes a general-purpose algorithmic blueprint which unifies the theory of learning time-varying graphs from online data. The specific contributions of this general framework are: \begin{enumerate} \item[a)] it is \textit{model-independent}, i.e., it can be analyzed in its abstract form and then specialized under different graph learning models. We show how to instantiate three such models, namely, the Gaussian graphical model (GGM), the structural equation model (SEM) and the smoothness-based model (SBM); \item[b)] it operates in \textit{non-stationary} environments, i.e., when the data statistics change over time. This is possible by expressing the considered models in terms of the sample covariance matrix, which can be then updated recursively for each new streaming sample with a user-defined function, which discards past information. \item[c)] it is \textit{accelerated} through a prediction-correction strategy, which takes into account the time-dimension. Its iterative nature enables a trade-off between following the optimal solution (accuracy) and an approximate solution (velocity). It also exhibits an implicit regularization of the cost function due to the limited iteration budget at each time-instant, i.e., similar solutions at closed time instants are obtained. \end{enumerate} \noindent\textit{Notation}: we use $x(i)$ and $X(i,j)$ to denote the $i$-th entry of the column vector $\bbx$ and the $ij$-th entry of the matrix $\bbX$, respectively. Superscripts $^\top$ and $^\dagger$ denote the transpose and the pseudoinverse of a matrix, respectively, while operators $\tr(\cdot)$ and $\operatorname{vec}(\cdot)$ denote the matrix trace and matrix vectorization, respectively. The vectors $\bb0$ and $\boldsymbol{1}$, and the matrix $\bbI$, denote the all-zeros vector, the all-ones vector, and the identity matrix, with dimension clarified in the context. The operators $\otimes$, $\odot$, $\oslash$ and $^\circ$ stand for Kronecker product, Hadamard (entry-wise) product, Hadamard (entry-wise) division and Hadamard (entry-wise) power, respectively. We have $[\; \cdot \; ]_{+}= \max(\bb0, \cdot)$, where the maximum operates in an entry-wise fashion. Also, $\iota_{\ccalX}(\cdot)$ is the indicator function for the convex set $\ccalX$, for which holds $\iota_{\ccalX}(\bbx)= 0$ if $\bbx \in \ccalX$ and $+ \infty$ otherwise. Given two functions $f(\cdot)$ and $g(\cdot)$, $f \circ g(\cdot)$ denotes their composition. A function $f(\cdot)$ with argument $\bbx \in \reals^N$, which is parametrized by the time $t$, is denoted by $f(\bbx;t)$. The gradient of the function $f(\bbx;t)$ with respect to $\bbx$ at the point $(\bbx;t)$ is denoted with $\nabla_\bbx f(\bbx;t)$, while $\nabla_{\bbx \bbx} f(\bbx;t)$ denotes the Hessian evaluated at the same point. The time derivative of the gradient, denoted with $\nabla_{t \bbx} f(\bbx;t)$, is the partial derivative of $\nabla_\bbx f(\bbx;t)$ with respect to the time $t$, i.e., the mixed first-order partial derivative vector of the objective. Finally, $\|\cdot\|_p$ denotes the $\ell_p$ norm of a vector or, for a matrix, the $\ell_p$ norm of its vectorization. The Frobenius norm of a matrix is denoted with $\|\cdot\|_F$. Without any subscript, the norm $\|\cdot\|$ indicates the spectral norm. \section{Problem Formulation} In this section, we formalize the problem of learning graphs from data. In Section~\ref{sec:s-GTI}, we introduce the static graph topology inference problem, where we also recall three well-known models from the literature. Then, in Section~\ref{sec: online-TV} we formulate the (online) dynamic graph topology inference problem. \subsection{Graph Topology Identification} \label{sec:s-GTI} We consider data living in a non-Euclidean domain described by a graph $\ccalG=\{\ccalV, \ccalE, \bbS\}$, where $\ccalV=\{1, \ldots, N\}$ is the vertex set, $\ccalE \subseteq \ccalV \times \ccalV$ is the edge set, and $\bbS$ is an $N \times N$ matrix encoding the topology of the graph. The matrix $\bbS$ is referred to as the graph shift operator (GSO) and typical instantiations include the (weighted) adjacency matrix $\bbW$~\cite{sandryhaila2013discrete} and the graph Laplacian $\bbL$~\cite{shuman2013emerging}. By associating to each node $i \in \ccalV$ a scalar value $x(i)$, we define $\bbx=[x(1), \ldots, x(N)]^\top \in \mathbb{R}^N$ as a \textit{graph signal} mapping the node set to the set of real numbers. Consider now the matrix $\bbX=[\bbx_1, \ldots, \bbx_T]$ that stacks over the columns $T$ graph signals generated from an unknown graph-dependent process $\ccalF(\cdot)$; i.e., $\bbX= \ccalF(\bbS)$. Then, a GTI algorithm aims to learn the graph topology, i.e., to solve the ``inverse'' problem (not always well defined): \begin{align} \label{eq:inverse} \bbS= \ccalF^{-1}(\bbX). \end{align} The function ${\mathcal F}(\cdot)$ basically describes how the data are coupled with the graph and its knowledge is crucial. The data and the graph alone are insufficient to cast a meaningful graph learning problem. On one side, we need to know how the data depends on the graph from which they are generated. On the other side, we have to enforce some prior knowledge on the graph we want to learn. \smallskip\noindent\textbf{Graph-data models.} The choice of a data model is the forerunner of any GTI technique and, together with the graph-data coupling priors (e.g., smoothness, bandlimitedness) differentiates the different approaches. Due to their relevance for this work, we recall three widely used topology identification methods, namely the Gaussian graphical model~\cite{dempster1972covariance}, the structural equation model~\cite{ullman2003structural}, and the smoothness-based model~\cite{kalofolias2016learn}. \makeatletter \renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}% {-1ex\@plus -1ex \@minus -.2ex}% {-0.5ex \@plus -.2ex {\normalfont\normalsize\itshape}} \makeatother \subsubsection{Gaussian graphical model (GGM)} assumes each graph signal $\bbx_t$ is drawn from a multivariate Gaussian distribution $\ccalN(\boldsymbol{\mu}, \mathbf{\Sigma})$ with mean $\boldsymbol{\mu}$ and positive-definite covariance matrix $\mathbf{\Sigma}$. By setting the graph shift operator to be the precision matrix $\bbS=\mathbf{\Sigma}^{-1}$, \emph{graph learning in a GGM amounts to precision matrix estimation}, which in a maximum likelihood (MLE) sense can be formulated as: \begin{align} \label{eq:ggm} \begin{array}{l} \underset{\bbS}{\operatorname{minimize}} -\log \operatorname{det}(\bbS) +\operatorname{tr}(\bbS \hat{\mathbf{\Sigma}}) \\ \;\;\; \text { s. t. } \quad \bbS \in \mathbb{S}_{++}^{N} \end{array} \end{align} where $\empcov= \frac{1}{T} \bbX\bbX^\top$ is the sample covariance matrix and $\mathbb{S}_{++}^{N}$ is the convex cone of positive-definite matrices. In this context, matrix $\bbS$ can be interpreted as the adjacency matrix (with self loops), although the problem can also be solved under some additional constraints forcing ${\bf S}$ to be a Laplacian~\cite{kumar2020unified}. \subsubsection{Structural equation model (SEM)} neglecting possible external inputs, and assuming an undirected graph, the SEM poses a linear dependence between the signal value $x_t(i)$ at node $i$ and the signal values at some other nodes $\{x_t(j)\}_{j\neq i}$, representing the endogenous variables, i.e.,: \begin{align} \label{eq:sem-model} x_t(i)= \sum_{j\neq i } S(i,j) x_t(j) + e_t(i), \quad t=1, \ldots, T \end{align} where $S(i,j)$ weights the influence that node $j$ exerts on node $i$, and $e_t(i)$ represents unmodeled effects. In this view, with $\bbS$ encoding the graph connectivity, model \eqref{eq:sem-model} considers each node to be influenced only by its one-hop neighbors. In vector form, we can write \eqref{eq:sem-model} as: \begin{align} \label{eq:sem-data-model} \bbx_t= \bbS\bbx_t + \bbe_t, \;\;\; t=1, \ldots, T, \end{align} with $S(i,i)=0$, for $i=1, 2, \ldots, N$. Also, we consider $\bbe_t$ white noise with standard deviation $\sigma_e$. Graph learning under a SEM implies estimating matrix $\bbS$ by solving: \begin{align} \label{eq:sem-estimation} \begin{array}{l} \underset{\bbS}{\operatorname{minimize}}\;\;\frac{1}{2T} \|\bbX - \bbS\bbX\|_F^2 + g(\bbS), \\ \;\;\; \text { s. t. } \;\;\bbS \in \ccalS \end{array} \end{align} where $\ccalS = \{\bbS \vert \operatorname{diag}(\mathbf{S})=\bb0, S(i,j)=S(j,i), i \neq j\}$, and $g(\bbS)$ is a regularizer enforcing $\bbS$ to have specific properties; e.g., sparsity. In this context, matrix $\bbS$ is usually interpreted as the adjacency matrix of the network (without self loops). The first term of \eqref{eq:sem-estimation} can be equivalently rewritten as: \begin{align} f(\bbS)\!=\!\frac{1}{2T} \|\bbX - \bbS\bbX\|_F^2\!=\! \frac{1}{2} \! [\tr(\bbS^2\empcov)\! -\!2 \tr(\bbS\empcov) \! +\! \!\tr(\empcov)]. \end{align} which highlights its dependence on $\empcov$. \subsubsection{Smoothness-based model (SBM)} assumes each graph signal $\bbx_t$ to be smooth over the graph $\ccalG$, where the notion of graph-smoothness is formally captured by the Laplacian quadratic form: \begin{align} \text{LQ}_{\ccalG}(\bbx_t):= \bbx_t^\top \bbL \bbx_t = \sum_{i \neq j} W(i,j) (x_t(i)- x_t(j))^2. \end{align} A low value of LQ$_{\ccalG}(\bbx_t)$ suggests that adjacent nodes $i$ and $j$ have similar values $x_t(i)$ and $x_t(j)$ when the edge weight $W(i,j)$ is high. Thus, the quantity: \begin{align} \label{eq:TV} \overline{\text{LQ}}_{\ccalG}(\bbX)= \frac{1}{T}\sum_{t=1}^T \text{LQ}_{\ccalG}(\bbx_t)= \frac{1}{T}\tr(\bbX^\top\bbL\bbX)=\tr( {\bf L} \hat{\boldsymbol \Sigma}) \end{align} represents the average signal smoothness on top of $\ccalG$, which can be rewritten as the graph-dependent function: \begin{align} \label{eq:smoothness-quantity} f(\bbS) = \tr(\Diag(\bbS \boldsymbol{1})\empcov ) - \tr(\bbS\empcov) \end{align} with $\bbS= \bbW$. Building upon this quantity, graph learning under a graph smoothness prior can be casted as: \begin{align} \label{eq:smoothness-estimation} \begin{array}{l} \underset{\bbS}{\operatorname{minimize}} \;\;\;f(\bbS) +g(\mathbf{S}) \\ \text { s. t. } \bbS \in \ccalS \end{array} \end{align} where the term $g(\bbS)$ accommodates for additional topological properties (e.g., sparsity) and also helps avoiding the trivial solution $\bbS=\bb0$. The set $\ccalS=\{\bbS \vert \operatorname{diag}(\mathbf{S})=\bb0, S(i,j)=S(j,i) \geq 0, i \neq j\}$ encodes the topological structure, which coincides with the set of hollow symmetric matrices (i.e., with zeros on the diagonal) with positive entries. \begin{remark} In~\cite{kalofolias2016learn}, the authors express the smoothness quantity \eqref{eq:TV} in terms of the weighted adjacency matrix $\bbW$ and a matrix $\bbZ \in \mathbb{R}_+^{N \times N}$ representing the row-wise (squared) Euclidean distance matrix of $\bbX$; i.e., $\tr(\bbX^\top\bbL\bbX)= \frac{1}{2} \tr(\bbW \bbZ)= \frac{1}{2}\|\bbW \odot \bbZ\|_1$. This formulation mainly brings the intuition that adding explicitly a sparsity term to the objective function would simply add a constant term to $\bbZ$. We favour \eqref{eq:smoothness-quantity} as a measure of graph signal smoothness since it fits within our framework, as will be clear soon. We emphasize however how the two formulations are equivalent, since $\empcov$ can be directly expressed as a function of $\bbZ$. \end{remark} \subsection{Online Time-Varying Topology Identification} \label{sec: online-TV} When the graph topology changes over time, the changing interactions are represented by the sequence of graphs $\{\ccalG_t=\{\ccalV, \ccalE_t, \bbS_t\}\}_{t=1}^\infty$, where $t \in {\mathbb N}_+$ is a discrete time index. This sequence of graphs, which is discrete in nature, can be interpreted as the sampling of some "virtual" continuous time-varying graph using the sampling period $h=1$. To relate our expressions to existing literature, we will make the parameter $h$ explicit in the formulas, yet it is important to remember that $h=1$. Together with the graph sequence $\{\ccalG_t\}_{t=1}^\infty$, we consider also streaming graph signals $\{\bbx_t\}_{t=1}^\infty$, such that signal $\bbx_t$ is associated to graph $\ccalG_t$. At this point, we are ready to formalize the time-varying graph topology identification (TV-GTI) problem. \vspace{0.2cm} \noindent \textbf{Problem statement.} \textit{Given an online sequence of graph signals $\{\bbx_t\}_{t=1}^{\infty}$ arising from an unknown time-varying network, the goal is to identify the time-varying graph topology $\{\ccalG_t\}_{t=1}^{\infty}$; i.e., to learn the graph shift operator sequence $\{\bbS_t\}_{t=1}^\infty$ from $\{\bbx_t\}_{t=1}^{\infty}$. On top of this, to highlight the trade-off between accuracy and low-latency of the algorithm's solution.} \vspace{0.2cm} Mathematically, our goal is to solve the sequence of time-invariant problems: \begin{align} \label{eq:probl-stat} \bbS_t^\star:= \argmin_\bbS F(\bbS;t) \quad t=1, 2, \ldots \end{align} where function $F(\cdot;t)$ is a time-varying cost function that depends on the data model [cf. Section~\ref{sec:s-GTI}], and the index $t$ makes the dependence on time explicit, which is due to the arrival of new data. Although we can solve problem \eqref{eq:probl-stat} for each $t$ separately with (static) convex optimization tools, the need of a low-latency stream of solutions makes this strategy unappealing. This approach also fails to capture the inherent temporal structure of the problem, i.e, it does not exploit the prior time-dependent structure of the graph, which is necessary in time-critical applications. To exploit also this temporal information, we build on recent advances of time-varying optimization \cite{simonetto2016class,simonetto2020time} and propose a general framework for TV-GTI suitable for non-stationary environments. The proposed approach operates on-the-fly and updates the solution as a new signal $\bbx_t$ becomes available. The generality of this formulation enables us to define a \textit{template} for the TV-GTI problem, which can be specialized to a variety of static GTI methods. The only information required is the first-order (gradient) and possibly second-order (Hessian) terms of the function. In the next section, we lay down the mathematics of the proposed approach. The central idea is to follow the optimal time-varying solution of problem \eqref{eq:probl-stat} with lightweight proximal operations \cite{martinet1970regularisation}, which can be additionally accelerated with a \textit{prediction-correction} strategy. This strategy, differently from other adaptive optimization strategies such as least mean squares and recursive least squares, uses an evolution model to predict the solution, and observes new data to correct the predictions. The considerations of Section~\ref{sec:dynamic-graph-learning} will be then specialized to the different data models of Section~\ref{sec:s-GTI} in Section~\ref{sec:network-models}, further analyzed theoretically in Section~\ref{sec:convergence-analysis}, and finally validated experimentally in Section~\ref{sec:numerical-result}. \section{Online Dynamic Graph Learning} \label{sec:dynamic-graph-learning} To maintain our discussion general, we consider the \textit{composite} time-varying function: \begin{align} \label{eq: composite} F(\bbS;t):= f(\bbS;t) + \lambda g(\bbS;t) \end{align} where $f: \mathbb{R}^{N \times N} \times {\mathbb N}_+ \rightarrow {\mathbb R}$ is a smooth\footnote{We use the term smoothness for functions and the term graph-smoothness for graph signals.} strongly convex function \cite{vial1983strong} encoding a fidelity measure and $g: \mathbb{R}^{N \times N} \times {\mathbb N}_+ \rightarrow {\mathbb R}$ is a closed convex and proper function, potentially non differentiable, representing possible regularization terms. For instance, function $f(\cdot)$ can be the GGM objective function of \eqref{eq:ggm}, the SEM least-squares term of \eqref{eq:sem-estimation}, or the SBM smoothness measure in~\eqref{eq:TV}. Solving a time-varying optimization problem implies solving the \textit{template} problem: \begin{align} \label{eq:time-varying} \bbS_t^\star:= \argmin_\bbS f(\bbS;t) + \lambda g(\bbS;t) \quad \text{for } t=1, 2, \ldots \end{align} In other words, the goal is to find the sequence of optimal solutions $\{\bbS_t^\star\}_{t=1}^\infty$ of \eqref{eq:time-varying}, which we will also call the \textit{optimal trajectory}. However, solving exactly problem \eqref{eq:time-varying} in real time is infeasible because of the computational and time constraints. The exact solution may also be unnecessary since by itself it still approximates the true underlying time-varying graph. Under these considerations, an online algorithm that updates the approximate solution $\hat{\bbS}_{t+1}$ of \eqref{eq:time-varying} at time $t+1$, based on the former (approximate) solution $\hat{\bbS}_{t}$ is highly desirable for low complexity and fast execution\footnote{Problem \eqref{eq:time-varying} also endows the constrained case, in which the function $g(\cdot)$ comprises indicator functions associated to each constraint.}. \subsection{Reduction} \label{subsec:reduction} Instrumental for the upcoming analysis is to observe that the number of independent variables of the graph representation matrix plays an important role in terms of storage requirements, processing complexity and, most importantly, in the correct computations of function derivatives with respect to those variables. Thus, when considering structured matrices, such as symmetric, hollow or diagonal, we need to take into account their structure. We achieve this by ad-hoc vectorization schemes through duplication and elimination matrices, inspired by~\cite{magnus2019matrix}. Consider a matrix $\bbS \in \reals^{N \times N}$ and its corresponding ``standard'' vectorization $ \operatorname{vec}(\bbS) \in \reals^{N^2}$. Depending on the specific structure of $\bbS$, different reduction and vectorization schemes can be adopted, leading to a lift from a matrix space to a vector space. The following spaces are of interest. \smallskip\noindent\textbf{h-space.} \label{subsec:h-space} If $\bbS$ is symmetric, the number of independent variables is $k=N(N+1)/2$, i.e., the variables in its diagonal and its lower (equivalently, upper) triangular part. We can isolate these variables by representing matrix $\bbS$ with its \textit{half-vectorization} form, which we denote as $\bbs=\operatorname{vech}(\bbS) \in \mathbb{R}^{k}$. This isolation is possible by introducing the elimination matrix $\bbE \in \mathbb{R}^{k \times N^2}$ and the duplication matrix $\bbD \in \mathbb{R}^{N^2 \times k}$ which respectively selects the independent entries of $\bbS$, i.e., $\bbE\operatorname{vec}(\bbS) =\bbs$, and duplicates the entries of $\bbs$, i.e, $\bbD\bbs = \operatorname{vec}(\bbS)$. We call this vector space as the half-vectorization space (h-space). \smallskip\noindent\textbf{hh-space.} If $\bbS$ is symmetric and hollow, the number of independent variables is $l=N(N-1)/2$, i.e., the variables on its strictly lower (equivalently, upper) triangular part. In this case, we can represent matrix $\bbS$ in its \textit{hollow half-vectorization} form, which we denote as $\bbs=\operatorname{vechh}(\bbS) \in \mathbb{R}^l$. This reduction is achieved by applying the hollow elimination and duplication matrices $\bbE_h \in \mathbb{R}^{l \times N^2}$ and $\bbD_h \in \mathbb{R}^{N^2 \times l}$, respectively, to the vectorization of $\bbS$. In particular, $\bbE_h$ extracts the variables of the strictly lower triangular part of the matrix, i.e., $\bbs = \bbE_h \operatorname{vec}(\bbS)$, while $\bbD_h$ duplicates the values and fills in zeros in the correct positions, i.e., $\operatorname{vec}(\bbS) = \bbD_h \bbs$. We refer to the associated vector space as the hollow half-vectorization space (hh-space). \smallskip\noindent With the above discussion in place, we can now illustrate the general framework in terms of vector-dependent functions $f(\bbs)$ for a vector $\bbs$, in contrast to matrix-dependent functions $f(\bbS)$, simplifying exposition and notation. However, we underline that the information embodied in $\bbS$ and $\bbs$ is the same. \subsection{Framework} We develop a prediction-correction strategy for problem \eqref{eq:time-varying} that starts from an estimate $\hat{\bbs}_t$ at time instant $t$, and \textit{predicts} how this solution will change in the next time step $t+1$. This predicted topology is then \textit{corrected} after a new datum $\bbx_{t+1}$ is available at time $t+1$. More specifically, the scheme has the following two steps: \begin{enumerate}[labelsep=0.1cm, leftmargin=*] \item[\textbf{(1)}] \hspace{-0.1cm} \textit{Prediction}: at time $t$, an approximate function $\hat{F}(\bbs;t+1)$ of the true yet \textit{unobserved} function $F(\bbs;t+1)$ is formed, using only information available at time $t$. Then, using this approximated cost, we derive an estimate $\bbs_{t+1|t}^\star$, of how the topology will be at time $t+1$, using only the information up to time $t$. This estimate is found by solving: % \begin{align} \label{eq:prediction} \bbs_{t+1\vert t}^\star:= \argmin_\bbs \hat{F}(\bbs;t+1). \end{align} % To avoid solving \eqref{eq:prediction} for each $t$, we find an estimate $\hat{\bbs}_{t+1\vert t}$ by applying $P$ iterations of a problem-specific descent operator $\hat{\ccalT}$ (e.g., gradient descent, proximal gradient) for which $\bbs_{t+1\vert t}^\star= \hat{\ccalT} \bbs_{t+1\vert t}^\star$, i.e., $\bbs_{t+1\vert t}^\star$ is a fixed point of $\hat{\ccalT}$. See Appendix~\ref{sec:app-a} for possible instances of $\hat{\ccalT}$. In other words, problem \eqref{eq:prediction} is solved recursively as: % \begin{align} \label{eq:prediction-step} \hat{\bbs}^{p+1}= \hat{\ccalT}\hat{\bbs}^p, \quad p=0,1, \ldots, P-1 \end{align} with $\hat{\bf s}^0=\hat{\bf s}_t$. Once $P$ steps are performed, the predicted topology is set to $\hat{\bbs}_{t+1 \mid t}= \hat{\bbs}^{P}$, which approximates the solution of \eqref{eq:prediction} and, in turn, will be close to $\bbs_{t+1}^{\star}$ at time $t+1$. For our framework, we consider a Taylor-expansion based prediction to approximate the first term of $F(\cdot; t+1)$, i.e., $f(\cdot; t+1)$ [cf. \eqref{eq: composite}], leading to the following quadratic function: % \begin{align} \label{eq:approximate-function} \nonumber \hat{f}(\bbs; t+1)&= \frac{1}{2} \bbs^\top \nabla_{\bbs\bbs} f\left(\hat{\bbs}_{t} ; t\right) \bbs +\big[\nabla_{\bbs} f\left(\hat{\bbs}_{t} ; t\right)+ \\ &+ h \nabla_{t \bbs} f\left(\hat{\bbs}_{t} ; t\right)-\nabla_{\bbs \bbs} f\left(\hat{\bbs}_{t} ; t\right) \hat{\bbs}_{t}\big]^\top\bbs \end{align} % where $\nabla_{\bbs \bbs} f (\cdot) \in \mathbb{R}^{N \times N}$ is the Hessian matrix of $f(\cdot)$ with respect to $\bbs$ and $\nabla_{t \bbs} f(\cdot) \in \mathbb{R}^{N}$ is the partial derivative of the gradient of $f(\cdot)$ w.r.t. time $t$. To approximate the second term of $F(\cdot; t+1)$, i.e., $g(\cdot; t+1)$ [cf. \eqref{eq: composite}], we use a one step-back prediction, i.e., ${\hat{g}(\bbs; t+1)= g(\bbs; t)}$. This implies that $\hat{g}(\cdot)$ does not depend on $t$, which in turn makes the constraint set and the regularization term independent of time, an assumption usually met in state-of-the-art topology identification~\cite{mateos2019connecting}. Henceforth, we will omit this time dependency. \item[\textbf{(2)}] \textit{Correction}: at time $t+1$ the new data $\bbx_{t+1}$ and hence the cost function $F(\bbs;t+1)$ becomes available. Thus, we correct the prediction $\hat{\bbs}_{t+1\vert t}$ by solving the correction problem: % \begin{align} \label{eq:correction} \bbs_{t+1}^\star:= \argmin_\bbs F(\bbs;t+1). \end{align} % Also in this case, we solve \eqref{eq:correction} with iterative methods to obtain an approximate solution $\hat{\bbs}_{t+1}$ by applying $C$ iterations of an operator $\ccalT$. In other words, the correction problem \eqref{eq:correction} is addressed through the recursion: % \begin{align} \label{eq:correction-step} \hat{\bbs}^{c+1}= \ccalT\hat{\bbs}^c, \quad c=0,1, \ldots, C-1 \end{align} with $\hat{\bf s}^0=\hat{\bf s}_{t+1|t}$. Once the $C$ steps are performed, the correction graph $\hat{\bbs}_{t+1}$ is set to $\hat{\bbs}_{t+1}= \hat{\bbs}^{C}$, which will approximate the solution $\bbs_{t+1}^{\star}$ of \eqref{eq:correction}. \end{enumerate} \begin{algorithm}[t] \begin{algorithmic}[1] \Require Feasible $\hat{\bbS}_0$, $f(\bbS; t_0)$, $P$, $C$, operators $\hat{\ccalT}$ and $\ccalT$ \State $\hat{\bbs}_0 \xleftarrow[]{}$ ad-hoc vectorization of $\hat{\bbS}_0$ \For{$t=0,1, \ldots$} \State // \textit{Prediction} \State Initialize the predicted variable $\hat{\bbs}^0= \hat{\bbs}_t$ \For{$p= 0,1, \ldots, P-1$} Predict $\hat{\bbs}^{p+1}$ with \eqref{eq:prediction-step} \EndFor Set the predicted variable $ \hat{\bbs}_{t+1 \mid t}= \hat{\bbs}^{P}. $ \State // \textit{Correction - time $t+1$: new data arrive} \State Initialize the corrected variable $\hat{\bbs}^0= \hat{\bbs}_{t+1 \mid t}$ \For{$c= 0,1, \ldots, C-1$} Predict $\hat{\bbs}^{c+1}$ with \eqref{eq:correction-step} \EndFor Set the corrected variable $\hat{\bbs}_{t+1}= \hat{\bbs}^{C}$ \EndFor \end{algorithmic} \caption{Online Time-Varying Graph Topology Inference} \label{alg:complete} \end{algorithm} \smallskip\noindent Algorithm~\ref{alg:complete} shows the pseudocode for the general online TV-GTI framework. \begin{remark} We point out that the framework can adopt different approximation schemes, such as extrapolation-based techniques, and can also include time-varying constraint sets. The choice of approximation-scheme depends on the properties of the problem itself along with the required prediction accuracy. For an in-depth theoretical discussion regarding different prediction approaches and relative convergence results, refer to~\cite{bastianello2020primal}. \end{remark} \section{Network Models and Algorithms} \label{sec:network-models} In this section, we specialize the proposed framework to the three static topology inference models discussed in Section~\ref{sec:s-GTI}. Notice that the data dependency of data-driven graph learning algorithms is exerted via the empirical covariance matrix $\empcov$ of the graph signals; we have already shown this for the three considered models of Section~\ref{sec:s-GTI}. In other words, graph-dependent objective functions of the form $F(\bbS)$ could be explicitly expressed through their parametrized version $F(\bbS; \empcov)$. This rather intuitive, yet crucial observation, is central to render the proposed framework model-independent and adaptive, as explained next. \noindent\textbf{Non-stationarity.} Relying on the explicit dependence of function $F(\cdot)$ on $\empcov$ and envisioning non-stationary environments, we let the algorithm be adaptive by discarding past information. That is, function $F(\bbS; t)$ in \eqref{eq: composite} can be written as $F(\bbS; \empcov_t)$, with $\empcov_t$ the empirical covariance matrix, up to time $t$, with past data gradually discarded. This makes the framework adaptive and model-independent. The adaptive behavior can be shaped by, e.g., the exponentially-weighted moving average (EWMA) of the covariance matrix: \begin{align} \label{empcov-rule} \empcov_t= \gamma\empcov_{t-1} + (1- \gamma)\bbx_t\bbx_t^\top \quad t=1, 2 \ldots \end{align} where the forgetting factor $\gamma \in (0,1)$ downweighs (for $\gamma \rightarrow 0$) or upweighs (for $\gamma \rightarrow 1$) past data contributions. For stationary environments, an option is the infinite-memory matrix covariance update $\empcov_t= \frac{t-1}{t}\empcov_{t-1} + \frac{1}{t}\bbx_t \bbx_t^\top$. \subsection{Time-Varying Gaussian Graphical Model} The GGM problem \eqref{eq:ggm}, adapted to a time-varying setting following template \eqref{eq:time-varying} leads to: \begin{subequations} \begin{align} \label{eq:f-ggm} f(\bbS; t) &= -\log \operatorname{det}(\bbS) +\operatorname{tr}(\bbS \hat{\mathbf{\Sigma}}_{t})\\ g(\bbS;t) &= \iota_{\mathbb{\ccalS}}(\bbS) \end{align} \end{subequations} where $\ccalS= \mathbb{S}_{++}^N$. In this case $g(\cdot)$ encodes the constraint set of positive definite matrices and the regularization parameter is $\lambda=1$. Since $\bbS$ is symmetric, we use the half-vectorization $\bbs=\operatorname{vech}(\bbS) \in \mathbb{R}^{k}$ to reduce the number of independent variables from $N^2$ to $k=N(N+1)/2$. Then, the gradient and the Hessian of the function $f(\cdot)$ in the h-space are respectively: \vspace{-0.5mm} \begin{subequations} \begin{align} \label{eq:gradient-ggm} \nabla_\bbs f(\bbs; t)&= \bbD^{\top} \operatorname{vec} (\hat{\mathbf{\Sigma}}_t - \bbS^{-1}) \\ \vspace{1cm} \label{eq:hessian-ggm} \nabla_{\bbs \bbs} f(\bbs; t) &= \bbD^{\top} (\bbS \otimes \bbS )^{-1} \bbD. \end{align} \end{subequations} Likewise, the discrete-time derivative of the gradient is given by the partial mixed-order derivative~\cite{simonetto2016class}: \begin{align} \label{eq: time-derivative-ggm} \nabla_{t \bbs} f(\bbs ; t)=\bbD^{\top} \operatorname{vec} (\hat{\mathbf{\Sigma}}_{t} - \hat{\mathbf{\Sigma}}_{t-1}). \end{align} Note the Hessian term \eqref{eq:hessian-ggm} is time-independent, while the time-derivative of the gradient \eqref{eq: time-derivative-ggm} is graph-independent. Now, by defining $\hat{\bbs}_t:= \operatorname{vech(\hat{\bbS}_t)} \in \mathbb{R}^{k}$, we can particularize Algorithm~\ref{alg:complete} to: \begin{itemize} \item \textbf{Prediction:} with $\hat{\bbs}^{0}$ initialized as $\hat{\bbs}^{0}= \hat{\bbs}_t$, the prediction update is : \begin{align} \label{eq:prediction-ggm} \hat{\bbs}^{p+1} &= \mathbb{P}_{\ccalS}[\hat{\bbs}^{p} - 2\alpha_t (\nabla_\bbs f(\hat{\bbs}_{t} ; t) + \nonumber \\ &+ \nabla_{\bbs \bbs} f(\hat{\bbs}_{t} ; t)\left(\hat{\bbs}^{p}-\hat{\bbs}_{t}\right) + h \nabla_{t \bbs} f(\hat{\bbs}_{t} ; t) ) ] \end{align} for $p=0,1, \ldots, P-1$, where $\alpha_t$ is a (time-varying) step size. Equation~\eqref{eq:prediction-ggm} entails a descent step along the approximate function $\hat{f}(\cdot; t+1)$ in~\eqref{eq:approximate-function}, followed by the projection onto the convex set $\ccalS$; see Appendix~\ref{sec:app-a} for the definition of $\mathbb{P}_{\ccalS}(\cdot)$. Then, the prediction $\hat{\bbs}_{t+1 \mid t}$ is set to $\hat{\bbs}_{t+1 \mid t}= \hat{\bbs}^{P}$. \item \textbf{Correction}: by setting $\hat{\bbs}^{0}\!=\! \hat{\bbs}_{t+1 \mid t}$, the correction update is: \begin{equation} \label{eq:correction-ggm} \hat{\bbs}^{c+1} =\mathbb{P}_{\ccalS} \left[ \hat{\bbs}^{c} - \beta_t \nabla f(\hat{\bbs}^c; t+1) \right] \end{equation} for $c=0,1, \ldots, C-1$, where $\beta_t$ is a (time-varying) step size. Equation~\eqref{eq:correction-ggm} entails a descent step along the true function $f(\cdot; t+1)$, followed by the projection onto the set $\ccalS$. The correction $\hat{\bbs}_{t+1}$ is finally set to $\hat{\bbs}_{t+1}= \hat{\bbs}^{C}$. \end{itemize} \noindent The prediction step \eqref{eq:prediction-ggm} instantiates \eqref{eq:prediction-step} to $\hat{\ccalT}= \mathbb{P}_\ccalS \circ (I - \alpha_t \nabla_{\bbs} \hat{f} )(\cdot)$, where $I(\cdot)$ is the identity function $I(\bbs)=\bbs$. Similarly, the correction step \eqref{eq:correction-ggm} instantiates \eqref{eq:correction-step} to $\ccalT= \mathbb{P}_\ccalS \circ (I - \beta_t \nabla_{\bbs}f )(\cdot)$. The overall computational complexity of one PC iteration is dominated by the matrix inversion and matrix multiplication, incurring a cost of $\ccalO(N^3)$. A correction-only algorithm would also incur a cost of $\ccalO(N^3)$ per iteration. See Appendix~\ref{app:complexity} for details. \subsection{Time-Varying Structural Equation Model} The SEM problem \eqref{eq:sem-estimation}, adapted to a time-varying setting with sparsity-promoting regularizer, leads to [cf. \eqref{eq:time-varying}]: \begin{subequations} \begin{align} \label{eq:f-sem} f(\bbS; t) &= \frac{1}{2} [\tr(\bbS^2\empcov_t) -2 \tr(\bbS\empcov_t) + \tr(\empcov_t)]\\ \label{eq:g-sem} g(\bbS;t) &= \|\bbS\|_{1} + \iota_{\mathbb{\ccalS}}(\bbS) \end{align} \end{subequations} where $\ccalS=\{ \bbS \in \mathbb{S}^N \vert \operatorname{diag}(\bbS)=\bb0, S(i,j)=S(j,i), i \neq j\}$ is the set of hollow symmetric matrices, and $\|\bbS\|_{1}=\|\operatorname{vec}(\bbS)\|_1$. Since $\bbS$ is symmetric and hollow, we operate on the hh-space to make the problem unconstrained and reduce the number of independent variables from $N^2$ to $l=N(N-1)/2$, through its hollow half-vectorization form $\bbs=\operatorname{vechh}(\bbS) \in \mathbb{R}^l$. In the hh-space, equations \eqref{eq:f-sem} and \eqref{eq:g-sem} become: \begin{subequations} \begin{align} \label{eq:f-sem-vec} f(\bbs; t) &= \frac{1}{2}\bbs^\top \bbQ_t \bbs -2 \bbs^\top \hat{\bbsigma}_t + \frac{1}{2}\hat{\sigma}_t \\ \label{g-sem-vec} g(\bbs;t) &= 2\|\bbs\|_1 \end{align} \end{subequations} where $\bbQ_t:=\bbD_h^\top(\empcov_t \otimes \bbI)\bbD_h$ with $\otimes$ denoting the Kronecker product, $ \hat{\bbsigma}_t=\operatorname{vechh}(\empcov_t)$, and $\hat{\sigma}_t= \tr(\empcov_t)$. Since $\bbQ_t \succeq 0$, \eqref{eq:f-sem-vec} is convex. To solve the time-varying SEM (TV-SEM) problem, we derive the gradient and the Hessian of function $f(\cdot)$ in the hh-space as: \begin{subequations} \begin{align} \label{eq:gradient-sem} \nabla_\bbs f(\bbs; t) &= \bbQ_t \bbs -2 \hat{\bbsigma}_t \\ \vspace{1cm} \label{eq:hessian-sem} \nabla_{\bbs \bbs} f(\bbs; t) &= \bbQ_t \end{align} \end{subequations} Notice here how the Hessian is time-varying and independent on $\bbs$, differently from the GGM case. The time derivative of the gradient is given by the partial mixed-order derivative: \begin{align} \label{eq:time-gradient-sem} \nabla_{t\bbs}f(\bbs; t)= \frac{1}{h}[ (\bbQ_t - \bbQ_{t-1})\bbs -2 (\hat{\bbsigma}_t - \hat{\bbsigma}_{t-1})] \end{align} Now, by defining $\hat{\bbs}_t:= \operatorname{vechh}(\hat{\bbS}_t) \in \mathbb{R}^l$, we can particularize Algorithm~\ref{alg:complete} to \begin{itemize} \item \textbf{Prediction:} set $\hat{\bbs}^0=\hat{\bbs}_t$. Then, the prediction is the proximal-gradient update: \begin{subequations} \label{eq: steps-sem} \begin{align} \label{eq:prediction-sem-1} \bbu^p &= \hat{\bbs}^p - \alpha_t [\nabla_\bbs f(\hat{\bbs}_{t} ; t) + \nonumber \\ &+ \nabla_{\bbs \bbs} f(\hat{\bbs}_{t} ; t)\left(\hat{\bbs}^{p}-\hat{\bbs}_{t}\right) + h \nabla_{t \bbs} f(\hat{\bbs}_{t} ; t)]\\ \label{eq:prediction-sem-2} \hat{\bbs}^{p+1}&= \operatorname{sign}(\bbu^p) \odot [|\bbu^p|- 2\alpha_t\lambda\boldsymbol{1} ]_+ \end{align} \end{subequations} for $p=0, \ldots, P$. Equation~\eqref{eq:prediction-sem-1} entails a descent step along the approximate function $\hat{f}(\cdot; t+1)$ in~\eqref{eq:approximate-function}, followed by the non-negative soft-thresholding operator in~\eqref{eq:prediction-sem-2}, which sets to zero all the (negative) edge weights of the graph obtained after the gradient descent in \eqref{eq:prediction-sem-1}. See Appendix~\ref{sec:app-a} for the formal definition of proximal operator, leading to \eqref{eq:prediction-sem-1} and \eqref{eq:prediction-sem-2}. The final prediction $\hat{\bbs}_{t+1\vert t}$ is set to $\hat{\bbs}_{t+1\vert t}= \hat{\bbs}^P$. % \smallskip\item \textbf{Correction:} set $\hat{\bbs}^0=\hat{\bbs}_{t+1\vert t}$. Then, the correction is the proximal-gradient update: \begin{subequations} \label{eq: steps-sem-correction} \begin{align} \label{eq:correction-sem-1} \bbu^c&= \hat{\bbs}^c - \beta_t \nabla f(\hat{\bbs}^c; t+1)\\ \label{eq:correction-sem-2} \hat{\bbs}^{c+1}&= \operatorname{sign}(\bbu^c) \odot [|\bbu^c|- 2\beta_t\lambda\boldsymbol{1} ]_+ \end{align} \end{subequations} for $c=0, \ldots, C-1$. Equation~\eqref{eq:correction-sem-1} entails a descent step along the true function $f(\cdot; t+1)$, followed by the non-negative soft-thresholding operator in~\eqref{eq:correction-sem-2}. Finally, $\hat{\bbs}_{t+1}=\hat{\bbs}^C$. \end{itemize} \noindent The prediction step \eqref{eq: steps-sem} instantiates \eqref{eq:prediction-step} to $\hat{\ccalT}= \prox_{\lambda g, \alpha_t} \circ (I - \alpha_t \nabla_{\bbs}\hat{f}) (\cdot)$. Similarly, the correction step \eqref{eq: steps-sem-correction} instantiates \eqref{eq:correction-step} to $\ccalT= \prox_{\lambda g, \beta_t} \circ \ (I - \beta_t \nabla_{\bbs}f )(\cdot)$. The overall computational complexity of one PC iteration is dominated by the computation of matrix $\bbQ_t$, incurring a cost of $\ccalO(N^3)$. A correction-only algorithm would also incur a cost of $\ccalO(N^3)$ per iteration. See Appendix~\ref{app:complexity} for details. \subsection{Time-Varying Smoothness-based Model} The SBM model \eqref{eq:smoothness-estimation} adapted to a time-varying setting is: \begin{subequations} \begin{align} \label{eq:f-smm} f(\bbS; t) &= \tr(\Diag(\bbS \boldsymbol{1})\empcov_t ) - \tr(\bbS\empcov_t)\\ \label{eq:g-smm} g(\bbS;t) &= \frac{\lambda_1}{4}\|\bbS\|_F^2 - \lambda_2 \boldsymbol{1}^\top \log (\bbS \boldsymbol{1}) + \iota_{\mathbb{\ccalS}}(\bbS) \end{align} \end{subequations} where $\ccalS=\{\bbS \in \mathbb{S}^N \vert {\rm diag}({\bf S}) = {\bf 0}, S(i,j) \!=\!S(j,i) \geq 0, i \neq j\}$ is the set of hollow symmetric matrices. The log barrier term $\log (\bbS \boldsymbol{1})$ is applied entry-wise and forces the nodes degree vector $\bbd=\bbS \boldsymbol{1}$ to be positive while avoiding the trivial solution. The Frobenius norm term $\|\bbS\|_F^2$ controls the sparsity of the graph. By operating in the hh-space, equations~\eqref{eq:f-smm} and \eqref{eq:g-smm} become\footnote{We move the log-barrier and Frobenius norm terms of $g(\cdot)$ function \eqref{eq:g-smm} into the $f(\cdot)$ function to fit the structure of the general template.}: \begin{subequations} \begin{align} \label{eq:f-smm-vec} f(\bbs;t) & \!= \bbs^\top(\bbK^\top \hat{\bbsigma}_d\!- \! 2\hat{\bbsigma}_t)\! -\! \lambda_2\boldsymbol{1}^\top \log (\bbK\bbs)\! +\! \frac{\lambda_1}{2} \|\bbs\|^2\\ % \label{eq:g-smm-vec} g(\bbs;t) & = \iota_{\mathbb{R}_+}(\bbs) \end{align} \end{subequations} where $\bbK \in \{0,1\}^{N \times l}$ is the binary matrix such that $\bbd=\bbS\boldsymbol{1}= \bbK \bbs$, $\hat{\bbsigma}_d= \diag(\empcov_t)$ and $\hat{\bbsigma}_t= \operatorname{vechh}(\empcov_t)$. To apply the proposed framework to solve the time-varying SBM (TV-SBM) problem, we derive the gradient and the Hessian of function $f(\cdot)$ in the hh-space as follows: \begin{subequations} \begin{align} \label{eq:gradient-smm} \nabla_\bbs f(\bbs; t) &= \lambda_1\bbs - \lambda_2 \bbK^\top (\boldsymbol{1} \oslash \bbK\bbs) + \bbz_t \\ \vspace{1cm} \label{eq:hessian-smm} \nabla_{\bbs \bbs} f(\bbs; t) &= \lambda_1\bbI + \lambda_2 \bbK^\top \Diag(\boldsymbol{1}\oslash (\bbK\bbs)^{\circ 2})\bbK \end{align} \end{subequations} where $\oslash$ and $^\circ$ represent the Hadamard division and power, respectively. The time derivative of the gradient is given by the partial mixed-order derivative: \begin{align} \label{eq:time-grad-sbm} \nabla_{t\bbs}f(\bbs; t)= \frac{1}{h} (\bbz_t - \bbz_{t-1}) \end{align} where $\bbz_t= \bbK^\top \hat{\bbsigma}_d\!- \! 2\hat{\bbsigma}_t$. Now, by defining $\hat{\bbs}_t:= \operatorname{vechh}(\hat{\bbS}_t) \in \mathbb{R}^l$, we can particularize Algorithm~\ref{alg:complete} to: \begin{itemize} \item \textbf{Prediction:} with $\hat{\bbs}^{0}$ initialized as $\hat{\bbs}^{0}= \hat{\bbs}_t$, the prediction update is: \begin{align} \label{eq:prediction-smm} \hat{\bbs}^{p+1} &=\mathbb{P}_{\bbs \succeq \bb0}[\hat{\bbs}^{p} - 2\alpha_t (\nabla_\bbs f(\hat{\bbs}_{t} ; t) + \nonumber \\ &+ \nabla_{\bbs \bbs} f(\hat{\bbs}_{t} ; t)\left(\hat{\bbs}^{p}-\hat{\bbs}_{t}\right) + h \nabla_{t \bbs} f(\hat{\bbs}_{t} ; t) ) ] \end{align} for $p=0,1, \ldots, P-1$. Equation~\eqref{eq:prediction-smm} entails a descent step along the approximate function $\hat{f}(\cdot; t+1)$ in~\eqref{eq:approximate-function}, followed by the projection onto the non-negative orthant. Then, the prediction $\hat{\bbs}_{t+1 \mid t}$ is set to $\hat{\bbs}_{t+1 \mid t}= \hat{\bbs}^{P}$. \item \textbf{Correction}: by setting $\hat{\bbs}^{0}= \hat{\bbs}_{t+1 \mid t}$, the correction update is: \begin{equation} \label{eq:correction-smm} \hat{\bbs}^{c+1} =\mathbb{P}_{\bbs \succeq \bb0} \left[ \hat{\bbs}^{c} - \beta_t \nabla f(\hat{\bbs}^c; t+1) \right], \end{equation} for $c=0,1, \ldots, C-1$. Equation~\eqref{eq:correction-smm} entails a descent step along the true function $f(\cdot; t+1)$, followed by the projection onto the non-negative orthant. Finally, $\hat{\bbs}_{t+1}= \hat{\bbs}^{C}$. \end{itemize} \noindent The prediction step \eqref{eq:prediction-smm} instantiates \eqref{eq:prediction-step} to $\hat{\ccalT}= \mathbb{P}_{\bbs \succeq \bb0} \circ (I - \alpha_t \nabla_{\bbs} \hat{f} )(\cdot)$. Similarly, the correction step \eqref{eq:correction-smm} instantiates \eqref{eq:correction-step} to $\ccalT= \mathbb{P}_{\bbs \succeq \bb0} \circ (I - \beta_t \nabla_{\bbs}f )(\cdot)$. The overall computational complexity per iteration is dominated by the computation of the gradient $\nabla_\bbs f(\bbs; t)$ (or the Hessian if $P>1$), incurring a cost of $\ccalO(N^2)$ (or $\ccalO(N^3)$ if $P>1$). See Appendix~\ref{app:complexity} for details. \section{Convergence Analysis} \label{sec:convergence-analysis} In this section, we first discuss the convergence of Algorithm~\ref{alg:complete} and the associated error bounds. As solver we consider the proximal gradient $\hat{\ccalT}=\ccalT=\prox_{g,\rho} \circ (I - \rho \nabla_\bbs f)(\cdot)$~\cite{ryu2016primer, combettes2011proximal}. Then, we show how the parameters of the three introduced models are involved in the bounds. To ease notation, we use $\bbs \in \mathbb{R}^{p}$ to indicate the vectorization of matrix variable $\bbS \in \mathbb{R}^{N \times N}$ [cf. Section~\ref{subsec:reduction}]. For this analysis, we need the following mild assumptions. \begin{assumption} \label{ass1} The function $ f:\mathbb{R}^{p} \times {\mathbb N}_+ \rightarrow {\mathbb R}$ is $m$-strongly convex and $L$-smooth uniformly in $t$, i.e., ${m \bbI \preceq \nabla_{\bbs \bbs} f(\bbs;t) \preceq L \bbI, \;\; \forall \; \bbs, t}$, while the function $g:\mathbb{R}^{p} \times {\mathbb N}_+ \rightarrow \mathbb{R} \cup \{+ \infty\}$ is closed convex and proper, or $g(\cdot; t)=0 $, for all $t \in \mathbb{N_+}$. \end{assumption} This guarantees that problem~\eqref{eq:time-varying} admits a unique solution for each time instant, which in turn guarantees uniqueness of the solution trajectory $\{\bbs_t^\star\}_{t=1}^\infty$. \begin{assumption}\label{ass2} The gradient of function $f(\cdot)$ has bounded time derivative, i.e. $\exists \; C_0 >0 $ such that $\|\nabla_{t\bbs}f(\bbs;t)\| \leq C_0 \; \forall \; \bbs \in \mathbb{R}^p, t \in \mathbb{N}_+$. \end{assumption} This guarantees that the solution trajectory is Lipschitz in time. \begin{assumption}\label{ass3} The predicted function $\hat{f}(\cdot; t+1)$ is $m$-strongly convex and $L$-smooth uniformly in $t$; and $\hat{g}(\cdot; t+1)$ is closed, convex and proper. \end{assumption} This implies that the prediction problem \eqref{eq:prediction} belongs to the same class as the original problem, i.e., the functions of the two problems share the same strong convexity and Lipschitz constants $m$ and $L$. Therefore, the same solver can be applied for the prediction and correction steps, i.e., $\hat{\ccalT}= \ccalT$. \begin{assumption} \label{ass:graph} The matrix $\bbS$ of \eqref{eq: composite} has finite entries, i.e., $- \infty \!<S(i,j)\!<\! + \infty$, for all $i,j$ \end{assumption} This guarantees $\|\bbS\| < + \infty$, i.e., $\bbS$ is a bounded operator, and it holds in practical scenarios. In particular, it is known that (finite) weighted graphs exhibit bounded eigenvalues, see \cite{zhan2005extremal}\cite{das2008sharp}. Notably, if $\bbS$ is a normalized Laplacian, then $\|\bbS\|\!=\! 2$. \smallskip\noindent Similarly, assumptions~\ref{ass1}-\ref{ass3} are mild and hold for the considered models, as we show next. \begin{prop} The three considered models of Section~\ref{sec:network-models} can be $m$-strongly convex and $L$-smooth uniformly in $t$, for some scalar $m$ and $L$, as supported by the following claims. \begin{claim} Denote with $\xi>0$ and $0 < \chi < \infty$ the minimum and maximum admissible eigenvalues of the precision matrix $\bbS$, respectively; i.e., consider the set $\ccalS=\{\bbS \in \mathbb{S}_{++}^N \vert \xi \bbI \! \preceq \! \bbS \! \preceq \! \chi \bbI \}$. Then, for the TV-GGM function $f(\cdot;t)$ in \eqref{eq:f-ggm}, it holds: \begin{align} m = 1/\chi \quad \quad L= 2/ \xi. \end{align} \end{claim} \begin{claim} Denote with $\lambda_{\text{min}}$ and $\lambda_{\text{max}}$ the smallest and highest eigenvalues for the set of empirical covariance matrices obtained with graph signals obeying~\eqref{eq:sem-data-model}. Then, for the TV-SEM function $f(\cdot;t)$ in \eqref{eq:f-sem-vec}, it holds: \begin{align} m =\lambda_\text{min} \quad \quad L = 2 \lambda_{\text{max}}. \end{align} \end{claim} \begin{claim} Consider the TV-SBM function $f(\cdot;t)$ in \eqref{eq:f-smm-vec}, and recall that the log-barrier term avoids isolated vertices, i.e., $\bbd \succ \bb0$. Denote with $d_\text{min} > 0$ the minimum degree of the GSO search space. Under these assumptions, it holds: \begin{align} m = 2 \lambda_1 \quad \quad L = 2 \lambda_2 (N-1) d_\text{min}^{-2}. \end{align} See Appendix~\ref{proof:bounds} for a proof of Claim~1-3. \end{claim} \end{prop} Thus, Assumption~\ref{ass1} holds since the Hessian of $f(\cdot;t)$ is bounded over time and $g(\cdot; t)$ is closed, convex and proper by problem construction; Assumption~\ref{ass2} holds since $\nabla_{t\bbs}f(\bbs;t)$ is the difference between bounded vectors which involve covariance matrices not too different from each other (one is the rank-one update of the other), which is finite as long as the graph signals are bounded, see~\eqref{empcov-rule} and, e.g., ~\eqref{eq:time-grad-sbm}. Assumption~\ref{ass3} holds since $\hat{f}(\cdot; t+1)$ is a quadratic approximation of $f(\cdot;t)$ [cf.~\eqref{eq:approximate-function}] and $\hat{g}(\cdot; t+1)= g(\cdot;t)$, thus inheriting the properties of $f(\cdot; t)$ and $g(\cdot; t)$, which satisfy Assumption~\ref{ass1}. With this in place, we are now ready to show two different error bounds incurred during the prediction and correction steps performed by Algorithm~\ref{alg:complete}, describing its sub-optimality as function of the model and algorithm's parameters. First, we show the error bound between the optimal prediction solution $\bbs_{t+1 \vert t}^\star$ and the associated optimal correction $\bbs_{t+1}^\star$, which solve problems \eqref{eq:prediction} and \eqref{eq:correction}, respectively. \begin{prop} Let Assumptions~\ref{ass1}-\ref{ass3} hold. Consider also the Taylor expansion based prediction~\eqref{eq:approximate-function} for $f(\cdot; t)$ and the one-step back prediction for $g(\cdot; t)$. Then, the distance between the optimal prediction solution $\bbs_{t+1 \vert t}^\star$, solving problem \eqref{eq:prediction}, and the associated optimal correction $\bbs_{t+1}^\star$, solving problem \eqref{eq:correction}, is upper bounded by: \begin{align} \label{eq:instantaneous-error} \| \bbs_{t+1 \vert t}^\star - \bbs_{t+1}^\star \| \leq \frac{2L}{m} \|\hat{\bbs}_t - \bbs_t^\star\| + \frac{2 C_0 h}{m}(1 + \frac{L}{m}) \end{align} where $\hat{\bbs}_t$ is the approximate solution of the correction problem \eqref{eq:correction} at time $t$. \end{prop} \begin{proof} Follows from \cite[Lemma 4.2]{bastianello2020primal} in which constant $D_0=0$ by considering a static function $g(\cdot)$. \end{proof} This bound enables us to measure how far the prediction is from the true corrected topology at time $t+1$. It depends on the estimation error $\hat{\bbs}_t - \bbs_t^\star$ achieved at time $t$, the ratio $L/m$ and the variability of the function gradient $\nabla_{t\bbs}f(\bbs;t)$. The bound suggests that a small gap can be achieved if \textit{i)} the ratio $L/m$ is small, which for the three considered models translates in having a small condition number for the involved covariance matrices or GSOs; and \textit{ii)} the time-gradient $\nabla_{t\bbs}f(\bbs;t)$ at consecutive time steps does not change significantly, which holds when the considered models have similar covariance matrices at adjacent time instants, i.e., the data statistics do not change too rapidly (see e.g.~\eqref{eq: time-derivative-ggm} and \eqref{eq:time-gradient-sem}). \smallskip\noindent Finally, we bound the error sequence $\{ \|\hat{\bbs}_t - \bbs_t^\star\|_2, t=1, 2, \ldots\}$ achieved by Algorithm~\ref{alg:complete} by means of the following non-asymptotic performance guarantee, which is an adaptation of \cite[Proposition 5.1]{bastianello2020primal}. \begin{theorem} \label{theorem:error} Let Assumptions~\ref{ass1} and \ref{ass3} hold, and consider two scalars $\{d_t, \phi_t\} \in \reals_{+}$ such that: \begin{align} \|\bbs_{t+1}^\star - \bbs_t^\star\| \leq d_t \quad \text{and} \quad \| \bbs_{t+1 \vert t}^\star - \bbs_{t+1}^\star \| & \leq \phi_t \end{align} for any $t \in \mathbb{N}_+$. Let also the prediction and correction steps use the same step-sizes $\rho_t= \alpha_t= \beta_t$. Then, by employing $P$ prediction and $C$ correction steps with the proximal gradient operator $\ccalT=\prox_{g,\rho_t} \circ (I - \rho_t \nabla_\bbs f)(\cdot)$, the sequence of iterates $\{\hat{\bbs}_{t}\}$ generated by Algorithm~\ref{alg:complete} satisfies: \begin{align} \label{eq:error-bound} \|\hat{\bbs}_{t+1} \!-\! \bbs_{t+1}^\star\|_2 \!\leq\! q_t^C (q_t^P \|\hat{\bbs}_{t} - \bbs_{t}^\star\| \!+\! q_t^P d_t \!+\! (1+ q_t^P) \phi_t) \end{align} where $q_t= \max\{|1 - \rho_t m_t|, |1- \rho_t L_t| \} \in (0,1)$ is the contraction coefficient \cite{beck2017first}. \end{theorem} \begin{proof} Follows from \cite[Proposition 5.1]{bastianello2020primal} and \cite[Lemma 2.5]{bastianello2020primal}, with variables $\lambda= q_t$ and $\chi=\beta=1$. \end{proof} Theorem~\eqref{eq:error-bound} states that the sequence of estimated graphs $\{\bbs_t\}_{t \in \mathbb{N}_+}$ hovers around the optimal trajectory $\{\bbs_t^\star\}_{t \in \mathbb{N}_+}$ with a distance depending on: \textit{i)} the numbers $P$ and $C$ of iterations; \textit{ii)} the estimation error achieved at the previous time instant $\|\hat{\bbs}_{t} - \bbs_{t}^\star\|$; and \textit{iii)} the quantities $d_t$ and $\phi_t$. Moreover, \eqref{eq:error-bound} is a contraction (i.e., $q_t^{C+P}<1$) when $\rho_t < 2/L_t$; in this case the initial starting point $\hat{\bbs}_0$ does not influence the error $\hat{\bbs}_{t+1} \!-\! \bbs_{t+1}^\star$ asymptotically, since the first term in~\eqref{eq:error-bound} vanishes. However, the terms $d_t$ and $\phi_t$ keep impacting the error also asymptotically, as long as the problem is time-varying; if the problem becomes static, i.e., the solution stops varying, then $d_t=\phi_t=0$, and the overall error asymptotically goes to zero. \begin{comment} The bound can then be generalized by taking a constant step size $\rho < 2/ \sup\{L_t\}$. Let $q:= \sup_{t \in \mathbb{N}}\{q_t\}$, $d:= \sup_{t \in \mathbb{N}}\{d_t\}$ and $\phi:= \sup_{t \in \mathbb{N}}\{\phi_t\}$. Then, an upper bound for the asymptotic error can be established as follows: \begin{align} \label{eq:asymptotic-error} \underset{t \to \infty}{\lim \sup} \; \|\hat{\bbs}_{t} - \bbs_{t}^\star\|_2 = \frac{q^C}{1- q^{C+P}}(q^P d + (1+ q^P \phi)) \end{align} That is, the output of Algorithm~\ref{alg:complete} hovers (asymptotically) around the optimal trajectory $\{\bbs_t^\star\}_{t \geq T_0}$, for some $T_0 \in \mathbb{N}_+$. This distance is bounded by a number depending on the maximum drifting and the maximum prediction error incurred during the algorithm's iterations. In addition, it is important to notice how the initial condition, i.e. the starting condition, does not influence the asymptotic error. Specializing \eqref{eq:asymptotic-error} to the Taylor-expansion based prediction for $f(\cdot)$ and the one-step back prediction for $g(\cdot)$, if $q^C (q^P + 2 \frac{L}{m}(1+q^p)) <1$ then we can bound the asymptotic error by \cite[Theorem 5.6]{bastianello2020primal}: \begin{align} \label{eq:asymptotic-error-taylor} \underset{t \to \infty}{\lim \sup} \; \|\hat{\bbs}_{t} - \bbs_{t}^\star\|_2 = \frac{q^C C_0 h}{m} \frac{q^P + 2 (1+ \frac{L}{m})(1+q^P)}{1- q^C(q^P+2 \frac{L}{m}(1+q^P))} \end{align} \end{comment} \section{Numerical Results} \label{sec:numerical-result} In this section, we show with numerical results how Algorithm~\ref{alg:complete}, specialized to the three models (TV-GGM, TV-SEM, TV-SBM), can track the offline solution~\eqref{eq:time-varying} obtained by the respective instantiations. For all the experiments, we initialize the empirical covariance matrix $\empcov_0$ with some samples acquired prior to the analysis. We consider $P=1$ prediction steps and $C=1$ correction steps, which is the challenging setting of having the minimum iteration budget for streaming scenarios. We measure the convergence of Algorithm~\ref{alg:complete} via the normalized squared error (NSE) between the algorithm's estimate $\hat{\bbs}_t$ and the optimal (offline) solution $\bbs_t^\star$: \begin{align} \text{NSE}(\hat{\bbs}_t, \bbs_t^\star) = \frac{\|\hat{\bbs}_{t} - \bbs_{t}^\star\|_2^2}{\|\bbs_{t}^\star\|_2^2}. \end{align} We use CVX \cite{grant2008cvx} as solver for the offline computations, and report the required computational time in seconds achieved by Algorithm~\ref{alg:complete} and CVX. \begin{figure*}% \centering \begin{subfigure}{0.33\textwidth} \centering \captionsetup{justification=centering} \vspace{.1cm} \includegraphics[width=.87\textwidth, trim= 0.6cm 0.1cm 1cm 0.75cm, clip=true]{figures/NMSE_GGM_piecewise_N18_T20000_gamma0dot999_alpha0dot01000_beta0dot01000_initSamples100.eps}% \vspace{-.2cm} \caption{\textbf{TV-GGM.} $N\!=\!18$, $\alpha\!=\beta\!=\!10^{\!-\!2}\!$, $\gamma\!=\!99.9\!\times\!10^{\!-\!2}$ \newline}% \label{ltop}% \end{subfigure}% \begin{subfigure}{0.33\textwidth} \centering \captionsetup{justification=centering} \includegraphics[width=.95\textwidth, trim= 0 0 0 5mm, clip=true]{figures/NMSE_SEM_piecewise_N28_T3000_gamma0dot990_lambda0dot500_alpha0dot001_beta0dot001_initSamples100.eps} \vspace{-.2cm} \caption{\textbf{TV-SEM.} $N\!=\!28$, $\alpha\!=\beta\!=\!0.1\!\times\!10^{\!-\!2} $, \newline $\lambda\!=\!0.5$, $\gamma\!=\!99\!\times\!10^{\!-\!2}$}% \label{ctop}% \end{subfigure}% \begin{subfigure}{0.33\textwidth} \centering \captionsetup{justification=centering} \includegraphics[width=.95\textwidth, trim= 0 0 0 5mm, clip=true]{figures/NMSE_SBM_piecewise_N28_T5000_gamma0dot990_lambdaone10dot000_lambdatwo10dot000_alpha0dot001_beta0dot001_initSamples100.eps}% \vspace{-.2cm} \caption{\textbf{TV-SBM.} $N\!=\!28$, $\alpha\!=\beta\!=\!0.1\!\times\!10^{\!-\!2}$, \newline $\lambda_1\!=\!10$, $\lambda_2\!=\!10$, $\gamma\!=\!99\!\times\!10^{\!-\!2}$}% \label{rtop}% \end{subfigure}% \\ \begin{subfigure}{0.33\textwidth} \centering \captionsetup{justification=centering} \includegraphics[width=.95\textwidth, trim= 0 0 0 5mm, clip=true]{figures/NMSE_GGM_sinusoidal_N18_T10000_gamma0dot999_alpha0dot00100_beta0dot00100_initSamples20.eps}% \vspace{-.2cm} \caption{\textbf{TV-GGM.} $N\!=\!18$, $\alpha\!=\beta\!=\!0.1\!\times\!10^{\!-\!2} $, \newline $\gamma\!=\!99.9\!\times\!10^{\!-\!2}$ }% \label{lbot}% \end{subfigure}% \begin{subfigure}{0.33\textwidth} \centering \captionsetup{justification=centering} \includegraphics[width=.95\textwidth, trim= 0 0 0 5mm, clip=true]{figures/NMSE_SEM_sinusoidal_N28_T5000_gamma0dot990_lambda0dot050_alpha0dot005_beta0dot005_initSamples100.eps}% \vspace{-.2cm} \caption{\textbf{TV-SEM.} $N\!=\!28$, $\alpha\!=\beta\!=\!0.5\!\times\!10^{\!-\!2} $, $\lambda\!=\!5e\!-\!2$, $\gamma\!=\!99\!\times\!10^{\!-\!2}$}% \label{cbot}% \end{subfigure}% \begin{subfigure}{0.33\textwidth} \centering \captionsetup{justification=centering} \includegraphics[width=.95\textwidth, trim= 0 0 0 5mm, clip=true]{figures/NMSE_SBM_sinusoidal_N28_T5000_gamma0dot990_lambdaone1dot000_lambdatwo10dot000_alpha0dot001_beta0dot001_initSamples100.eps}% \vspace{-.2cm} \caption{\textbf{TV-SBM.} $N=28$, $\alpha\!=\beta\!= \!0.1\!\times\!10^{\!-\!2} $, $\lambda_1=1$, $\lambda_2=10$, $\gamma=\!99\!\times\!10^{\!-\!2}$}% \label{rbot}% \end{subfigure}% \vspace{-.2cm} \caption{Normalized squared error (NSE) for the piecewise-constant (top row) and smooth (bottom row) synthetic scenarios between our online solution $\hat{\bbs}_t$ (or the other variants reported in the legend) with respect to the offline solution $\bbs_t^\star$ obtained with CVX. For the piecewise-constant scenario, it is also illustrated the NSE between the PC solution and the batch solution (green curve). Stochastic implementations are available for a subset of methods due to numerical instabilities caused by the rank-one matrix operations involved.} \label{fig:NMSE}\vspace{-4mm} \end{figure*} \subsection{Synthetic Data} \label{sec:synthetic} We generate a synthetic (seed) random graph $\bbS_0$ of $N$ nodes using the GSP toolbox~\cite{perraudin2014gspbox}. Then, edges abide two different temporal evolution patterns: \textit{i)} \textit{piecewise constant}; and \textit{ii) }\textit{smooth} temporal variation. Finally, we generate the stream of data according to the three considered models [cf. Section~\ref{sec:network-models}] for $T$ time instants. \smallskip\noindent \textbf{Piecewise.} For the piecewise constant scenario, we randomly select $\lceil N/2 \rceil$ nodes of the initial graph $\bbS_0$ and double the weight of their edges, after $T/2$ samples. Then, for $t= \{1, \ldots, T\}$ we generate each graph signal $\bbx_t$ according to the three models: $1)$ for the TV-GGM, we use $\bbx_t \sim \ccalN(\mathbf{0},\mathbf{\Sigma}_t)$, where $\mathbf{\Sigma}_t= \bbS_t^{-1}$; $2)$ for the TV-SEM we use $\bbx_t= (\bbI - \bbS_t)^{-1}\bbe_t$ [cf.~\eqref{eq:sem-data-model}], with noise variance $\sigma_e^2= 0.5$; and $3)$ for the TV-SBM we use $\bbx_t \sim \ccalN(\mathbf{0}, \bbL_t^\dagger + \sigma_e^2 \bbI_N)$ as in~\cite{dong2016learning} with $\sigma_e^2= 0.5$ \smallskip\noindent \textbf{Smooth.} For the smooth scenario, starting from the initial graph $\bbS_0$, the evolution pattern follows an edge-dependent behavior, $S_t(i,j)= S_0(i,j) ( 1 + e^{-0.01ijt})$ for $t= \{1, \ldots, T\}$. This means that each edge follows an exponential decaying behavior, with the decaying factor depending on the edge itself. The data are generated as in the piecewise constant scenario. \noindent For the results, we will compare the following methods: \begin{itemize} \item \textbf{Prediction-correction (PC)} \emph{red curve}: this is the proposed Algorithm~\ref{alg:complete} specialized to one of the three models, with $P=C=1$ \item \textbf{Correction-only (CO)} \emph{cyan curve}: this is a prediction-free algorithm which only considers the original problem~\eqref{eq:correction} and applies $C=1$ iteration of the recursion~\eqref{eq:correction-step}. It is equivalent to Algorithm~\ref{alg:complete} with $P=0, C=1$. We consider this algorithm to study the benefits of the prediction step performed by PC. \item \textbf{Correction-correction (CC)} \emph{blue curve}: this is a prediction-free algorithm which only considers the original problem~\eqref{eq:correction} and applies $C=2$ iterations of the recursion~\eqref{eq:correction-step}. It is equivalent to Algorithm~\ref{alg:complete} with $P=0, C=2$. This is a more fair comparison than CO, since the number of iterations is the same as the one of PC. \item \textbf{Stochastic gradient descent (SGD)} \emph{ochre curve}: this is a prediction-free and memory-less version of the algorithm which only considers the last acquired graph signal. That is, the empirical covariance matrix $\empcov_t=\bbx_t\bbx_t^\top$ in~\eqref{empcov-rule} is just a rank-one update, achieved by setting $\gamma=0$. We consider this to show how much the temporal variability of the function, captured by the time-derivative of the gradient in PC, affects the algorithm's convergence. \item \textbf{Prediction-correction rank-one (PC-1)} \emph{purple curve}: this is a rank-one (stochastic) implementation of the PC algorithm; i.e., $\empcov_t= \bbx_t\bbx_t^\top$ for the update in~\eqref{empcov-rule}, and $P=C=1$. Notice that, differently from SGD, it also uses the time-derivative of the gradient, which in this case is the difference between two rank-one covariance matrices (thus the length of the memory is equal to one). We consider this algorithm to check the impact of the prediction step in a stochastic implementation of PC; \item \textbf{Correction-correction rank-one (CC-1)} \emph{orange curve}: this is a rank-one (stochastic) implementation of the CC algorithm; i.e., it considers $\empcov_t= \bbx_t\bbx_t^\top$ for the update in~\eqref{empcov-rule}, and $P=0, C=2$. It can be seen as a two-step SGD, and we consider it to study whether the prediction step of PC-1 is beneficial for stochastic implementations. \end{itemize} \noindent In addition, for the piecewise constant scenario, we also report (green curve) the NSE between the PC solution and the batch solution obtained having all the relevant data in advance, i.e., the solution that would be obtained with a static graph learning algorithm on the intervals where the graph remains constant. In general, a fair comparison can be made within the rank-one implementations (SGD, PC-1 and CC-1) and within the memory-aware ones (PC, CO, CC). \smallskip\noindent \textbf{Results.} The NSE achieved by Algorithm~\ref{alg:complete} for the three models is shown in Fig.~\ref{fig:NMSE}, for both the piecewise constant (top row) and smooth (bottom row) scenarios. We use fixed step sizes for all the experiments. Notice that the only effect of the functions' hyperparameters is to shape the batch solution $\bbs_t^\star$ (and hence the time-varying trajectory $\hat{\bbs}_t$ at convergence). Thus, we run Algorithm~\ref{alg:complete} with different hyperparameters\footnote{The search space intervals for the hyperparameters are the following: $\alpha, \beta \in (0.01, 1) \times 10^{-2}$, $\lambda \in (0.005, 5)$, $\lambda_1, \lambda_2 \in (1,10)$ , $ \gamma \in \{97,99, 99.9\} \times 10^{-2}$.} and manually select them by ensuring that the trivial and complete graphs are excluded; the selected ones are displayed, together with the other algorithm's parameters, in the captions of Fig.~\ref{fig:NMSE}. \smallskip\noindent\textit{GGM.} Fig.~\ref{ltop} and Fig.~\ref{lbot} show the results for the piecewise constant and smooth scenarios, respectively. In both scenarios, the PC solution converges to the optimal offline counterpart and, for the piecewise constant, also to the batch solution(s). This demonstrates the adaptive nature of Algorithm~\ref{alg:complete} to react to changes in the data statistics. While for the piecewise constant scenario PC and CC offer the same convergence speed (which is expected, as explained in \textit{``Does prediction help?''}), for the smooth scenario, the PC algorithm exhibits a faster convergence with respect to the prediction-free competitors CO and CC. This is because the temporal variability of the function (and of its gradient) is captured by the prediction step and exploited to fasten the convergence. \smallskip\noindent\textit{SEM.} Similar considerations hold for the TV-SEM, whose results are illustrated in Fig.~\ref{ctop} and Fig.~\ref{cbot}. In both scenarios, PC and CC offer the same convergence rate (which also converge to the batch solution for the constant scenario), faster than a CO and SGD implementation. Interestingly, after the triggering event at $T/2$, SGD can track the optimal solution faster than CO with performances similar to PC and CC. A possible justification may be the memory-less nature of SGD, i.e., it only considers the last sample for the gradient evaluation, thus discarding past data. This renders the SGD more reactive to adapt to sudden changes of the data statistics compared to the memory-aware alternatives, which however exhibit similar performances thanks to the extra iteration they can benefit. \smallskip\noindent\textit{SBM.} Finally, the TV-SBM results are shown in Fig.~\ref{rtop} and Fig.~\ref{rbot}. Also in this case, the PC solution converges to the offline counterpart for the two scenarios and faster than the prediction-free versions of the algorithm CC and CO. In particular, while in the piecewise constant scenario PC converges faster than CC and the rank-one implementations, in the smooth scenario the rank-one implementations exhibit faster convergent behavior with respect to the non-stochastic implementations. Similar to what has been said for the TV-SEM results, a possible reason can be the memory-aware characteristics of the non-stochastic methods; that is, while the information present in past data can be beneficial in the static scenario and thus help PC and CC to have a more reliable estimate of the true underlying (static) covariance matrix (and of the gradient), it may slow down the process in non-stationary environments with time-varying covariance matrices as in the smooth scenario. \smallskip\noindent \textit{Required time.} An important metric to consider in time-sensitive applications is the average time per iteration. We report this information in Table~\ref{tab:time}, for the PC step and CVX, relative to the three considered models and settings in the top row of Fig.~\ref{fig:NMSE}. \begin{table}[t] \centering \caption{Average time (expressed in seconds) required to compute the PC and the CVX solution at each time instant.} \label{tab:time} {\normalsize \begin{tabular}{ p{2.5cm}||p{2.5cm}|p{2.5cm} } \hline &PC & CVX\\ \hline TV-GGM & $0.110 \times 10^{-2}$ & $3.6$\\ TV-SEM & $0.824 \times 10^{-2}$ & $2.0$ \\ TV-SBM & $0.023 \times 10^{-2}$ & $3.6$\\ \hline \end{tabular} } \vspace{-.3cm} \end{table} \noindent Combining the information of the table and that of the plots in Fig.~\ref{fig:NMSE}, it is clear how trading off the knowledge of the optimal solution for savings in terms of time seems an excellent compromise. Each prediction-correction step requires indeed around three orders of magnitude less time than the CVX counterpart, leading to a NSE at least smaller than $10e-1$. \smallskip\noindent\textit{Does prediction help?} Notice how in the piecewise constant scenario, the PC strategy does not seem to offer a major advantage with respect the CC strategy. Although this behavior could be hypothesized (since the setting is static), it is here empirically confirmed. To can gain more insights we look at the structure of the prediction step (e.g., \eqref{eq:prediction-ggm}), where the components playing a role in the descent direction are: the gradient $\nabla_\bbs f(\cdot)$; the Hessian $\nabla_{\bbs \bbs} f(\cdot)$; and the time-derivative of the gradient $\nabla_{t\bbs} f(\cdot)$. Since we use $P=1$, i.e., only one prediction step, the term $(\hat{\bbs}^p -\hat{\bbs}_t=\bb0)$ that multiplies the Hessian does not contribute to the descent step. The added value of the prediction step with respect to a general (correction) descent method, in this case, would be only provided by the time-gradient $\nabla_{t\bbs} f(\cdot)$ (since the gradient $\nabla_\bbs f(\cdot)$ is common to either the prediction and the correction step). In the piecewise constant scenario, however, the underlying (true) covariance matrix is time-invariant within the two stationary intervals, leading to a zero time-derivative of the gradient (cf.~\eqref{eq: time-derivative-ggm}). This means that in static scenarios, with $P=1$, the prediction step boils down to a correction step. Differently, for $P=2$, the contribution of the second-order information may speed up the convergence, as illustrated in Fig.~\ref{fig:GGM_multiP} for TV-GGM, with respect to a correction-only algorithm using $C=3$. \begin{figure}[h!] \centering \begin{subfigure}{0.25\textwidth}% \includegraphics[scale=0.3]{figures/NMSE_multiP_GGM_multiP_piecewise_N10_T10000_gamma0dot999_alpha0dot01000_beta0dot00100_initSamples100.eps}% \caption{}% \label{fig:GGM_multiP}% \end{subfigure}% \begin{subfigure}{0.25\textwidth}% \vspace{.2cm} \includegraphics[scale=0.3]{figures/NormTimeGradient_GGM_sinusoidal_N18_T10000_gamma0dot999_alpha0dot00100_beta0dot00100_initSamples20.eps}% \caption{} \label{fig:time-derivative}% \end{subfigure}% \label{fig:misc} \caption{(a): NSE of PC with $P=2$ and $C=1$, CO with $C=1$ and CC with $C=3$ for the piecewise constant scenario; (b) Norm of the time-derivative of the gradient as a function of the iteration index for the smooth scenario. } \end{figure} In the smooth scenario, the temporal variability of the gradient captured by the time-derivative of the gradient $\nabla_{t\bbs}f(\cdot)$, plays a role in the prediction step, which can improve the convergence speed of the algorithm. The (bounded) norm of this vector over time is illustrated in Fig.~\ref{fig:time-derivative} for the TV-GGM smooth scenario of Fig.~\ref{lbot}; this norm is linked to the constant $C_0$ introduced in Assumption~\ref{ass2} and the error in \eqref{eq:instantaneous-error}. \smallskip\noindent All in all, the results indicate the convergence of Algorithm~\ref{alg:complete} to the optimal offline counterpart and its capability to track it in non-stationary environments. The algorithm also converges to the batch solutions of the two stationary intervals, obtained with all the relevant data. A defining characteristic of Algorithm~\ref{alg:complete} is its ability to naturally enforce similar solutions at each iteration, achieved with an early stopping of the descent steps, governed by the parameters $P$ and $C$. That is, the algorithm adds an implicit \textit{temporal} regularization to the problem which needs to be explicitly added when working with the entire batch of data. \smallskip\noindent Given these results and insights, we can outline a few principles that can be adopted when considering Algorithm~\ref{alg:complete} for learning problems: \begin{itemize} \item The prediction step with $P=1$ can be beneficial when the underlying data statistics change over time, so that the time-variability of the gradient can be exploited. Otherwise, in a complete static scenario, it coincides with a correction step. \item Increasing $P$ can improve the convergence speed when the approximated cost function is a good surrogate of the cost function in the next time instant. \item Memory-less (stochastic) variants of the algorithm can be suitable in fast-changing environments, due to their ability to discard past information and react quickly to changes in data statistics. \end{itemize} Being confident on the convergence of the algorithm, we now corroborate its performance with real data. \subsection{Real Data} \label{subsection:real data} We now test the three considered algorithms on real data. Among other indicators employed in the simulations to assess the performance of the algorithm, we use the graph temporal deviation $\text{TD}(t):= \|\hat{\bbs}_t - \hat{\bbs}_{t-1}\|_2$, which measures the global variability on the edges of the graph for different time instants. To gain further insights on the network evolution over time, we consider additional metrics (such as number of edges and temporal gradient norm) and visual analysis tools which will be introduced in the application-specific scenario at hand. In this case, the hyperparameters of each function are chosen in such a way that the inferred graphs are neither trivial nor complete, and interpretable patterns consistent with real events are visible from the plots of the employed metrics. \smallskip\noindent \textbf{TV-GGM for Stock Price Data Analysis.} \textit{Data description:} we collect historical stock (closing) prices relative to the S\&P500 Index for seven pharmaceutical companies over the time period August $12$th $2019$ to August $10$th $2021$ using~\cite{yahoo}. The collected data include the economic crisis related to the COVID-19 pandemic, followed by the vaccination campaign. The companies of interest are Pfizer (PFE), Astrazeneca (AZN), Johnson \& Johnson (JNJ), GlaxoSmithKline (GSK), Moderna (MRNA), Novavax (NVAX) and Sanofi (SNY). Our goal is to leverage the TV-GGM in order to explore the relationships among these companies over time and observe the possible structural changes due to market instabilities. \begin{figure*}% \centering \begin{subfigure}{0.33\textwidth} \centering \captionsetup{justification=centering} \includegraphics[width=0.95\textwidth, height=5cm, trim =0.7cm 0.2cm 1cm 0.5cm , clip=true, keepaspectratio=true]{figures/price_pharma.eps}% \vspace{-.2cm} \caption{}% \label{fig:logprice}% \end{subfigure}% \begin{subfigure}{0.33\textwidth} \centering \captionsetup{justification=centering} \includegraphics[width=0.95\textwidth, trim= 1cm 0cm 1cm 0.3cm, clip=true, keepaspectratio=true]{figures/TD_pharma.eps} \vspace{-.2cm} \caption{}% \label{fig:TD_Pharma}% \end{subfigure}% \begin{subfigure}{0.33\textwidth} \centering \captionsetup{justification=centering} \includegraphics[width=0.95\textwidth]{figures/Graphs_pharma.eps}% \vspace{-.2cm} \caption{}% \label{fig:graphs_pharma}% \end{subfigure}% \vspace{-.2cm} \caption{(a) Standardized time series for the period August 12th 2019 - August 10th 2021; (b) graph temporal deviation for the stock market graph inferred with TV-GGM. The sharp peaks around March 2020 and after January 2021 happen consistently with real events; (c) inferred topologies at four different dates of interest. The absence of an edge between two nodes indicates their conditional independence.} \label{fig:pharma_all}\vspace{-5mm} \end{figure*} \textit{Results:} We consider $T = 504$ measurements (working days in August 2019 - August 2021) as graph signals $\{\bbx_t\}$ for the $N=7$ quantities of interest, which are further standardized, i.e., each variable is centered and divided by its empirical standard deviation; see Fig.~\ref{fig:logprice} for a plot of the standardized time series. We run the TV-GGM algorithm for different values of the forgetting factor $\gamma$, and monitor the evolution of the metrics earlier introduced. The value $\gamma = 0.75$ yielded results most consistent with the data behavior. It is clear from Fig.~\ref{fig:logprice} and the TD indicator in Fig.~\ref{fig:TD_Pharma} that around March 2020 and after January 2021 the market has changed significantly, due to the instability generated by the pandemic and by the follow-up starting vaccination campaign. The sharp peaks in Fig.~\ref{fig:TD_Pharma} around around the same period are a consequence of the dynamic inter-relationships among the companies; the inferred graph changes substantially in the two periods of interest and TD captures the market variability. To really enjoy the visualization potential offered by graphs as a tool, we show in Fig.~\ref{fig:graphs_pharma} snapshots of the inferred time-varying graph at four different dates of interest. Common among the four graphs is the presence of the edge connecting MRNA and NVAX, and the edge connecting AZN and SNY. The pharmaceutical companies associated to the endpoints of each of these two edges also show a similar trend in Fig.~\ref{fig:logprice}. Notice moreover that since the sparsity pattern of the precision matrix reveals conditional independence among the variables indexed by its zero entries, these graphs enable us to visually inspect such independence over time. Although the information endowed in these graphs may carry a financial significance, we leave this possible knowledge-discovery task out of this manuscript, to avoid misleading or erroneous interpretations. \smallskip\noindent \textbf{TV-SEM for Temperature Monitoring.} \textit{Data description:} for this experiment we consider the publicly available weather dataset\footnote{Data available at \hyperlink{https://www.met.ie/climate/available-data/historical-data}{https://www.met.ie/climate/available-data/historical-data}} provided by the Irish Meteorological Service, which contains hourly temperature (in $^{\circ}$C) data from 25 stations across Ireland. We monitor the temperature evolution over the sensor network for the period January 2016 to May 2020, and leverage the TV-SEM to infer the time-varying features of the graph learned by the algorithm. \textit{Results:} for the analysis we consider $T=38713$ measurements as graph signals $\{\bbx_t\}$ for the $N=25$ stations under consideration, standardizing the data as done in the previous experiment; Fig.~\ref{fig:ireland_time_series} depicts the standardized time series. It is interesting to notice the sinusoidal-like behavior of the aggregate time-series, due to higher (lower) temperature during the summer (winter) period, resulting in a smooth signal profile. \begin{figure}[h] \begin{subfigure}{0.95\columnwidth} \centering \includegraphics[width=\textwidth, trim= 1cm 0cm 1cm 0cm , clip= true]{figures/ireland_timeseries.eps}% \vspace{-.2cm} \caption{}% \label{fig:ireland_time_series}% \end{subfigure} \begin{subfigure}{0.95\columnwidth} \centering \includegraphics[width=\textwidth, height=5cm, keepaspectratio=true]{figures/edgePattern_ireland.eps}% \caption{} \label{fig:edgePattern_ireland} \end{subfigure} \caption{ (a) Standardized time series for the 25 Irish weather stations and (b) evolution of each edge weight over time.} \end{figure} Fig.~\ref{fig:edgePattern_ireland} illustrates the sparsity pattern of the time-varying graph and the importance of the weights at every time instant. This \textit{learn-and-show} feature offered by Algorithm~\ref{alg:complete} gives us the ability to visualize the learning behavior of the algorithm on-the-fly, a strength of low-cost iterative algorithms w.r.t. batch counterparts. From the figure (and the observed almost zero graph temporal deviation, which is not illustrated here) a consistent temporal homogeneity is visible, i.e., the graph does not change significantly over adjacent time instants. In other words, nodes influencing each other in a particular time instant, are likely to influence each other in other time instants. A reasonable explanation is given by the smooth and regular pattern exhibited by the time-series of Fig.~\ref{fig:ireland_time_series}, which is a consequence of the meteorological similarity over time, and by their high correlation coefficient. An interesting trend arises when observing the number of edges of the graph inferred over time, shown in Fig.~\ref{fig:numberedges_ireland}. Although in adjacent time instants the number does not change abruptly, a pattern can be identified over a longer time span. In particular, during winter and summer there is a sharp increment in the number of edges, with respect to autumn and spring where there is a significant reduction. To ease the visualization, the vertical red lines are placed in correspondence of the winter period of every year, while blue lines in correspondence of the autumn period. A possible reason for this phenomenon is given by the reduced variability of the temperature among the stations during summer and winter, and a higher variability during spring and autumn, leading to different graphs. \begin{figure*}% \centering \captionsetup{justification=centering} \begin{subfigure}{0.4\textwidth} \includegraphics[width=.95\textwidth, trim= 0 0 0 2cm]{figures/numberEdges_ireland.eps} \caption{} \label{fig:numberedges_ireland} \end{subfigure}% % % \centering \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=.95\textwidth]{figures/autumn_ireland.eps}% \caption{Oct 2016}% \label{autumn_graph}% \end{subfigure}% % % % \begin{subfigure}{0.3\textwidth} \centering \captionsetup{justification=centering} \includegraphics[width=.95\textwidth]{figures/winter_ireland.eps} \caption{Jan 2017}% \label{winter_graph}% \end{subfigure}% % \caption{Ireland temperature dataset. (a) Number of edges of the inferred graph over time. The red vertical lines correspond to January 15 of each year (winter), while the blue vertical line correspond to October 15 (autumn); snapshot of the inferred time-varying graph during (b) October 2016 (autumn graph) and (c) January 2017 (winter graph). Notice how stations close in space tend to be connected.} \label{fig:ireland_dataset}\vspace{-5mm} \end{figure*} For the sake of visualization, we also report the inferred graphs for October 2016 (autumn) and January 2017 (winter). In line with our previous comments regarding Fig.~\ref{fig:numberedges_ireland}, a lower number of edges is visible in the autumn graph with respect to the winter graph; in particular, edges present in the autumn graph are also present in the winter one. Finally, notice how stations close in space tend to be connected, thus showing how stations close to each other have a greater influence with respect to stations farther away in space. \smallskip\noindent \textbf{TV-SBM for Epileptic Seizure Analysis.} \textit{Data description:} we use electrocorticography (ECoG) time series collected during an epilepsy study at the University of California, San Francisco (UCSF) Epilepsy Center, where an 8 × 8 grid of electrodes was implanted on the cortical brain's surface of a 39-year-old woman with medically refractory complex partial seizure~\cite{kramer2008emergent}. The grid was supplemented by two strips of six electrodes: one deeper implanted over the left suborbital frontal lobe and the other over the left hippocampal region, thus forming a network of $76$ electrodes, all measuring the voltage level in proximity of the electrode, which is an evidence of the local brain activity. The sampling rate is $400$ Hz and the measured time series contains the 10 seconds interval preceding the seizure (pre-ictal interval) and the 10 seconds interval after the start of the seizure (ictal interval). Our goal is to leverage the TV-SBM in order to explore the dynamics among different brain areas at the seizure onset. \textit{Results:} for our analysis we consider $T=3200$ time instants as graphs signals $\{\bbx_t\}$ for the $N=76$ electrodes, which are further filtered (over the temporal dimension) at $\{60, 180\}$Hz to remove the spurious power line frequencies, and standardized as explained in the previous experiments. Fig.~\ref{fig:TD_epilepsy} shows the graph temporal deviation, where we observe an increasing and protracted variability of the TD shortly after the seizure onset (red vertical line), proving TD to serve as an indicator of network alteration suitable for time-varying scenarios. To visualize the on-the-fly learning behavior of the algorithm, in Fig.~\ref{fig:numberedges_epilepsy} we show the evolution of (a fraction\footnote{For visualization, we show $500$ random edges, since we recall that the number of total edges in an undirected graph of $N$ nodes is $N(N-1)/2$.} of) the edge weights over time. In the first half of the time-horizon, we notice the presence of stronger edges with respect to the second half, where the graph is sparser. We show two snapshots of the time-varying graph in Fig.~\ref{fig:graphEpilepsy}, for the time instants $1500$ (pre-ictal) and $1800$ (ictal), where we also report the closeness centrality of each node, which expresses how ``close'' a node is to all other nodes in the network (calculated as the average of the shortest path length from the node to every other node in the network). During the ictal interval, the graph tends to be more disconnected and its nodes to have a lower closeness centrality value, especially in the lower part of the graph. In addition, we observe how the number of (strong) edges and the closeness centrality value drop in the ictal graph, especially in the lower part of the graph. This is consistent with the findings in \cite{kramer2008emergent} and indicates that, on average, signals in the pre-ictal interval behave more similar to each other as opposed to the signals in the ictal interval. \begin{figure}[h!] \centering \includegraphics[width=0.95\columnwidth, height= 4cm, keepaspectratio=true]{figures/TD_epilepsy.eps}% \vspace{-.1cm} \caption{Graph temporal deviation for the epilepsy study. The red line indicates the seizure onset. During the ictal interval, a higher temporal deviation can be observed, indicating that the inferred graph is changing substantially.}% \label{fig:TD_epilepsy} \vspace{-5mm} \end{figure} \begin{figure*}% \centering \captionsetup{justification=centering} \begin{subfigure}{0.33\textwidth} \includegraphics[width=.95\textwidth]{figures/pattern_epilepsy.eps} \caption{} \label{fig:numberedges_epilepsy} \end{subfigure}% % % \centering \begin{subfigure}{0.7\textwidth} \centering \includegraphics[scale=0.5, trim= 1cm 1cm 1cm 0cm, clip=true]{figures/graph_pre_post_epilepsy.PNG}% \caption{}% \label{fig:graphEpilepsy}% \end{subfigure}% % \vspace{-.2cm} \caption{Epilepsy dataset. (a) evolution of each edge weight over time; (b) snapshots of the inferred time-varying graph at time instant 1500 and 1800. The color of an edge indicates its weight, with darker colors indicating higher weights, while the color of a node indicates the closeness centrality of such node, with brighter colors indicating higher values of closeness centrality.} \vspace{-5mm} \end{figure*} \section{Conclusion} In this manuscript, we proposed an algorithmic template to learn time-varying graphs from streaming data. The abstract time-varying graph learning problem, where the data influence is expressed through the empirical covariance matrix, is casted as a composite optimization problem, with different terms regulating different desiderata. The framework, which works in non-stationary environments, lies upon novel iterative time-varying optimization algorithms, which on one side exhibit an implicit temporal regularization of the solution(s), and on the other side accelerate the convergence speed by taking into account the time variability. We specialize the framework to the Gaussian graphical model, the structural equation model, and the smoothness-based model, and we propose ad-hoc vectorization schemes for structured matrices central for the gradient computations which also ease storage requirements. The proposed approach is accompanied by theoretical performance guarantees to track the optimal time-varying solution, and is further validated with synthetic numerical results. Finally, we learn time-varying graphs in the context of stock market, temperature monitoring, and epileptic seizures analysis. The current line of work can be enriched by specializing the framework to other static graph learning methods present in literature, possibly considering directed graphs, by implementing distributed versions of the optimization algorithms, and by applying the developed models in other real-world applications. \appendices \section{} \label{sec:app-a} Consider the multi-valued function $\ccalT: \reals^N \to \reals^N$, which we will refer to as \textit{operator}. Here, we briefly review some operator theory concepts used in this manuscript; see \cite{bauschke2011convex}. \noindent \textbf{Projection operator.} Given a point $\bbx \in \mathbb{R}^N$, we define projection of $\bbx$ onto the convex set $\ccalC \subseteq \mathbb{R}^N$ as: \begin{align} \mathbb{P}_{\ccalC}(\bbx):= \argmin_{\bbz \in \ccalC} \frac{1}{2} \|\bbz - \bbx\|_2 \end{align} \noindent \textbf{Proximal operator.} Consider the convex function $g: \mathbb{R}^N \to \mathbb{R}$. We define the proximal operator of $g(\cdot)$, with penalty parameter $\rho > 0$, as: \begin{align} \prox_{g,\rho}(\bbx):= \argmin_\bbz \{g(\bbz) + \frac{1}{2 \rho} \|\bbz -\bbx\|_2^2\} \end{align} For some functions, the proximal operator admits a closed form solution \cite[Ch.~6]{beck2017first}. In particular: \begin{itemize} \item if $g(\bbx)= \iota_{\ccalC}(\bbx)$ then $\prox_g(\bbx)= \mathbb{P}_\ccalC(\bbx)$, i.e., it is the projection of $\bbx$ onto the convex set $\ccalC$. \item if $g(\bbx)= \lambda \|\bbx\|_1$ then $\prox_g(\bbx)= \operatorname{sign}(\bbx) \odot [\bbx - \lambda\boldsymbol{1}]_+ $, i.e., it is the soft-thresholding operator. \end{itemize} Consider the convex minimization problem: \begin{align} \label{eq:com} \min_\bbx f(\bbx) + g(\bbx) \end{align} with $f, g: \mathbb{R}^N \to \mathbb{R}$ convex. It can be shown that problem \eqref{eq:com} admits at least one solution~\cite{combettes2005signal}, which can be found by the fixed point equation: \begin{align} \bbx= \prox_{g,\rho}(\bbx- \rho \nabla f(\bbx)) \end{align} \section{} \label{proof:bounds} \begin{proof}[Proof of Claim 1: TV-GGM] Recall the expression of the Hessian in \eqref{eq:hessian-ggm}, i.e., $\bbH (\bbS)= \bbD^{\top} (\bbS \otimes \bbS )^{-1} \bbD$ and that matrix $\bbS \in \ccalS$ is the precision matrix, with $\ccalS=\{\bbS \in \mathbb{S}_{++}^N \vert \xi \bbI \preceq \bbS \preceq \chi \bbI \}$. For the strong convexity, notice that since $\bbS \succ 0$, then also $\bbH(\bbS) \succ0$. Indeed, by exploiting the semi-orthogonality of matrix $\bbD/\sqrt{2}$, we have: \begin{align} &\lambda_{\text{min}}(\bbH(\bbS)) = \min_{\|\bbx\|=1} \bbx^\top \bbD^{\top} (\bbS \otimes \bbS )^{-1} \bbD \bbx \\ \nonumber &\geq \min_{\|\bbx\|=1} \bbx^\top \frac{\bbD^{\top}}{\sqrt{2}} (\bbS \otimes \bbS )^{-1} \frac{\bbD}{\sqrt{2}} \bbx = \min_{\|\bby\|=1} \bby^\top (\bbS \otimes \bbS )^{-1} \bby \\\nonumber &= \min_{\|\bbz\|=1} \sum_{i=1}^N \sum_{j=1}^N \frac{ z_iz_j}{\lambda_i(\bbS)\lambda_j(\bbS)} \geq \frac{1}{\lambda_{\text{max}}^2(\bbS)}= 1/ \chi^2 \end{align} For the Lipschitz continuity of the gradient, we have \begin{align} \|\bbD^\top (\bbS \otimes \bbS )^{-1}\bbD\| &\leq \|\bbD\|^2 \|(\bbS \otimes \bbS )^{-1} \| \\ = \nonumber 2 \|(\bbS \otimes \bbS )^{-1}\| &= \nonumber 2 \|\bbS^{-1} \otimes \bbS^{-1}\| \\ = \nonumber 2 \sqrt{\lambda_{\text{min}}(\bbS)^{-2}} &= \nonumber 2/\xi \end{align} \end{proof} \begin{proof}[Proof of Claim 2: TV-SEM] Denote with $\lambda_{\text{min}}$ and $\lambda_{\text{max}}$ the smallest and highest eigenvalues for the set of empirical covariance matrices obeying the SEM model. Recall the expression of the Hessian in \eqref{eq:hessian-sem}, i.e. $\bbH (\bbS; t)= \bbQ_t$, where $\bbQ_t:=\bbD_h^\top(\empcov_t \otimes \bbI)\bbD_h$. Since $\bbD_h / \sqrt{2}$ is a semi-orthogonal matrix, we have: \begin{align} &\lambda_{\text{min}}(\bbH(\bbS)) = \min_{\|\bbx\|=1} \bbx^\top \bbD_h^\top(\empcov_t \otimes \bbI)\bbD_h \bbx \\ \nonumber &\geq \min_{\|\bby\|=1} \bby^\top (\empcov_t \otimes \bbI ) \bby = \min_{\|\bbz\|=1}\sum_{i=1}^N \lambda_i(\empcov_t) z_i^2 \geq \lambda_{\text{min}} \end{align} where $\lambda_{\text{min}}$ is the smallest eigenvalue of $\empcov_t$. For the Lipschitz continuity of the gradient, we have: \begin{align} \|\bbD_h^\top(\empcov_t \otimes \bbI)\bbD_h\| &\leq 2 \|\empcov_t \otimes \bbI\| = 2\lambda_{\text{max}} \end{align} \end{proof} \begin{proof}[Proof of Claim 3: TV-SBM] For the strong convexity it suffices to notice that for $m >0$, $f(\bbs;t) - \frac{m}{2} \|s\|^2 = \bbs^\top\bbz_t - \lambda_2 \boldsymbol{1}^\top \log (\bbK\bbs) + (\lambda_1 - \frac{m}{2}) \|\bbs\|^2$ is convex. In turn, this implies that strong convexity of $f(\cdot; t)$ is guaranteed for $0<m\leq 2\lambda_1$. For the Lipschitz continuity of the gradient, recall that nodal degree vector $\bbd \succ 0$. Denote with $d_\text{min}$ the minimum degree of the GSO search space. Also, recall the expression of the Hessian $\bbH= \bbK^\top \Diag(\boldsymbol{1}\oslash (\bbK\bbs)^{\circ 2})\bbK$. Then: \begin{align} \|\bbK^\top \Diag(\boldsymbol{1}\oslash (\bbK\bbs)^{\circ 2})\bbK\| & \! \leq \! \|\bbK\|^2 \max (\boldsymbol{1}\oslash (\bbK\bbs)^{\circ 2})) \\ \nonumber = \|\bbK\|^2 d_\text{min}^{-2} &= 2 (N-1) d_\text{min}^{-2}, \end{align} where we made use of \cite[Lemma 1]{saboksayr2021online} for the bound of $\bbK$. \end{proof} \section{} \label{app:complexity} The computational (arithmetic) complexity per iteration of Algorithm~\ref{alg:complete} is dominated by the rank-one covariance matrix update in $\ccalO(N^2)$ and by the method-specific gradient computations involved in the prediction and correction steps (and eventually Hessian, if $P>1$ [cf. Section~\ref{sec:numerical-result} ``\emph{Does prediction help?}'' ]). Such method-specific computational complexities are shown next, together with a discussion on the costs for the offline counterparts. \smallskip\noindent \textbf{TV-GGM.} The worst case scenario computational complexity of the gradient $ \nabla_\bbs f(\bbs; t)$ in~\eqref{eq:gradient-ggm} is $\ccalO(N^3)$, which is due to the matrix inversion. This cost might be lowered exploiting the sparsity pattern of the sparse triangular factor of $\bbS$ or, in our case, exploiting the fact that it is a small perturbation with respect to the previous iterate. The multiplication with matrix $\bbD^\top$ has a cost of $\ccalO(N^2)$, since $\bbD \in \mathbb{R}^{N^2 \times N(N+1)/2}$ has at most two $1$'s in each column and exactly one $1$ in each row. The worst case scenario computational complexity of the Hessian $\nabla_{\bbs \bbs} f(\bbs; t)$ in~\eqref{eq:hessian-ggm} would be $\ccalO(N^3)$. However, because the Hessian is used in a matrix-vector multiplication [cf. \eqref{eq:prediction-ggm}], its factorization leads to a cost for the prediction step of $\ccalO(N^3)$. Indeed, exploiting the Kronecker product, the Hessian can be written as $\bbD^\top(\bbS^{-1} \otimes \bbI_N)( \bbI_N \otimes \bbS^{-1})\bbD$; then, the multiplication of the Hessian for a vector simply entails the succession of four sparse matrix-vector multiplications all with a cost of $\ccalO(N^3)$. The term $\nabla_{t \bbs} f(\bbs ; t)$ in~\eqref{eq: time-derivative-ggm} has a computational complexity of $\ccalO(N^2)$. Thus the overall computational complexity per iteration is $\ccalO(N^3)$. \smallskip\noindent \textbf{TV-SEM.} The overall cost is dominated by the computation of $\bbQ_t=\bbD_h^\top(\empcov_t \otimes \bbI)\bbD_h$, which is present in the gradients and the Hessian. The matrix-matrix multiplication(s) have a cost of $\ccalO(N^3)$, since $\bbD_h \in \mathbb{R}^{N^2 \times N(N-1)/2}$ has at most two $1$'s in each column and exactly one $1$ in each row. Thus the overall computational complexity per iteration is $\ccalO(N^3)$. \smallskip\noindent \textbf{TV-SBM.} Each column of $\bbK$ has exactly two non-zero entries (and each row has $N-1$ non-zero entries), thus $\bbK\bbs$ has a computational cost of $2|\ccalE|$, with $|\ccalE|$ the number of edges of the graph represented by $\bbS$ (in other words, $\|\bbs\|_0$). The operation $\bbK^\top (\boldsymbol{1} \oslash \bbK\bbs)$ has a cost of $\ccalO(N^2)$. The computational complexity of the Hessian is $\ccalO(N^3)$, since it is the weighted sum of $N$ outer products of vectors which are $(N-1)$-sparse in the same positions. Thus the overall computational complexity per iteration is $\ccalO(N^2)$ if $P=0,1$ and $\ccalO(N^3)$ if $P>1$. \smallskip\noindent \textbf{Offline.} The computational complexity for each time instant $t$ incurred by an offline solver to solve instances of problem~\eqref{eq:time-varying} depends by its algorithm-specific implementation closely related to the problem structure. The three problems we consider are (converted into) semidefinite programs (SDPs) and solved, in our case, by SDPT3, a Matlab implementation of infeasible primal-dual path-following algorithms, which involves the computation of second-order information. Since these computations are continuously repeated, for a fixed time instant $t$, till the algorithm convergence (say $I$ iterations), a trivial lower bound for computing the offline solution for the three considered problems is $\bbOmega(IN^3)$. To this cost must be also added the cost of other solver-specific steps which we do not explicitly consider here. \bibliographystyle{IEEEtran}
{'timestamp': '2022-05-25T02:16:05', 'yymm': '2110', 'arxiv_id': '2110.11017', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.11017'}
arxiv
\section{Introduction} Healthcare delivery operates in a resource limited environment where demand can sometimes exceed supply, resulting in situations where providers have to make difficult decisions of who to prioritize to receive scarce resources. Having a framework to guide such decisions is critical, particularly with growing threats of pandemics, natural disasters, and mass casualty events that make the healthcare system vulnerable to situation where demand vastly exceeds supply of critical healthcare resources. Triage of health resources in such situations has garnered quite a bit of attention from the Operations Management (OM) community \citep{jacobson2012priority,mills2013resource,sun2018patient}. The primary focus of prior work has been to determine how care should be rationed. In this work, we develop a machine learning methodology that considers how data can be used to guide these decisions in an {\it interpretable} manner and what criteria should be considered in these life-or-death decisions. Triage guidelines are often implemented during high stress, complex situations. As such, triage algorithms need to be systematic, simple and intuitive in order to facilitate adoption and to ease the decision burden on the provider. In 2012, the National Academy of Medicine identified an ethical framework for triage~\citep{gostin2012crisis}. In this framework, the primary component which the operations community has focused on is `the duty to steward resources', which calls for withholding or withdrawing resources from patients who will not benefit from them. In this work, we take a data-driven approach to develop triage guidelines for ventilator allocation in order to maximize lives saved. Such decisions are ethically challenging and such an objective can sometimes be in tension with other critical elements such as fairness. We will also examine how the ethics and fairness criteria can be incorporated into such decisions. On the one hand, government officials have issued pre-specified and transparent utilitarian \textit{triage} guidelines for preventing loss of life, promote fairness, and support front-line clinicians~\citep{christian2014triage,zuckerventilator,piscitello2020variation}. In the United States, 26 states have scarce resource allocation guidelines ~\citep{babar2006direct}. These guidelines emphasize simplicity, and can often be represented as decision trees of small depth~\citep{breiman1984classification,bertsimas2017optimal}. However, these guidelines have never been used in practice, and are not constructed in a \textit{data-driven} way, but rather via expert opinion of clinicians, policy makers, and ethicists. Therefore, it is not known how well they perform for the intended purpose of directing scarce resources to those most likely to benefit. In addition, we cannot ethically perform a prospective study to determine the efficacy (or performance) of such policies. On the other hand, there is a large body of literature in the OM community on the management of healthcare resources, including breast magnetic resonance imaging~\citep{hwang2014patterns}, patient scheduling~\citep{bakker2017dynamic}, ICU beds~\citep{chan2012optimizing,kim2015icu}, mechanical ventilators and high-flow nasal cannula~\citep{gershengorn2021impact,anderson2021rationing}. Because the health of each patient evolves dynamically over time, the problem of scarce resource allocation is inherently \textit{sequential} in nature. In theory, one can leverage the tools from OM and Machine Learning (ML) to compute new allocation guidelines. Markov Decision Processes (MDPs) and queueing theory are tools that are commonly used to find optimal sequences of decisions in a stochastic environment~\citep{Puterman,whitt2002stochastic}. With such methodologies, optimal policies can often be numerically computed efficiently using iterative algorithms; however, the optimal policies may not have an interpretable structure. This is often referred to as \textit{black-box} policies in the ML community~\citep{rudin2019stop}. To obtain practical operational guidelines, it is necessary to obtain \textit{interpretable} decision rules that can easily be explained and implemented by the medical staff and discussed with the practitioners. This becomes even more important for the ethically challenging task of triaging scarce life-sustaining resources. In this case, what constitutes an appropriate input into the model may be contested. For instance, age is a strong predictor of outcomes for patients infected with Sars-CoV-2, but ethicists disagree about the appropriateness of using age in triage decisions~\citep{may2020age}. For triage algorithms to be used in practice, triage rules must be exposed for public debate, and therefore, interpretability is a key property. In certain settings, simple index-based triage rules can be shown to perform well (e.g. , the $c\mu$-rule for multiclass queues with Poisson arrivals~\citep{van1995dynamic}. However, these works typically assume static patient health status and/or a limited number of patient classes (e.g. two classes in \cite{van1995dynamic}). The complexity of these problems arises from the capacity constraint which creates externalities across different patients. In contrast, we consider a setting where the health status of each patient evolves dynamically (and stochastically) overtime. This richer state-space for the patient state substantially increases the computational complexity of our model and renders existing approaches for triage intractable. As such, we develop a model that explicitly incorporates the dynamic patient health state and approximates the capacity constraint through appropriately calibrated cost parameters. Our goal in this paper is to develop allocation guidelines that are both \textit{data-driven} and \textit{interpretable}. To do so, we propose a new model for interpretable sequential decision-making, based on decision trees. We then apply this methodology to develop guidelines for ventilator allocation for COVID-19 patients. The COVID-19 pandemic has highlighted the challenge of managing life-saving health resources as demand for intensive care unit beds, critical appliances such as mechanical ventilators, and therapies such as dialysis all were in short supply in many countries. Shortages of ventilators and oxygen have occurred in Italy and India, amongst other countries \citep{rosenbaum2020facing,kotnala2021clinical}. Given the ongoing risks of emerging infectious diseases~\citep{zumla2016infectious} and the projected increase in frequency of extreme weather events~\citep{woodward2018climate}, hospitals are increasingly vulnerable to conditions that may result in periods of scarcity of life-sustaining resources even after the COVID-19 pandemic subsides. We utilize the question of ventilator allocation for COVID-19 patients as a canonical example of how our methodology can be used to develop data-driven, interpretable triage guidelines for such settings. Our main contributions can be summarized as follows: \begin{itemize} \item \textbf{Interpretable policies for MDPs.} We propose a framework to derive interpretable decision rules with good performances for sequential decision-making problems, based on decision trees. In particular, we model the evolution of the health of the patient as an MDP and we focus on \textit{tree policies}, which have a tree-like structure, and provide intuitive and explainable decision rules for MDPs. We highlight the challenges of computing optimal tree policies by showing that this problem is a generalization of computing optimal classification trees, which is known to be NP-hard. \item \textbf{Properties of optimal tree policies.} By construction, the set of policies we consider is constrained to have a tree-like structure. Therefore, the properties of optimal tree policies are in stark contrast with the classical properties for unconstrained MDPs. We show that optimal tree policies may depend on the initial condition, and may even be history-dependent. However, we show that an optimal tree policy can be chosen to be deterministic. Therefore, we propose an adaption of value iteration, a classical algorithm which returns an unconstrained, Markovian policy, to ensure the resulting policy is a tree policy. We also show that an optimal tree policy can always be chosen to be deterministic (though it may be history-dependent). \item \textbf{Algorithm for tree policies.} We develop an algorithm for computing a tree policy. Since computing history-dependent policies may be intractable, we focus on finding Markovian tree policies. Our algorithm performs dynamic programming recursions akin to Bellman recursions but forces the visited policies to be tree policies. \item \textbf{Application to mechanical ventilators allocations.} We apply our novel model and algorithm to compute interpretable triage guidelines for ventilator allocations for COVID-19 patients. We leverage a data set of 807 COVID-19 patients intubated at an urban academic medical center in New York City and build an MDP model to obtain interpretable triage guidelines. We compare them to the official New York State (NYS) guidelines and First-Come-First-Served (FCFS) guidelines. We find that our proposed tree policy may lead to up to a $25\%$ decrease in excess deaths, compared to the NYS and FCFS rules. Compared to NYS guidelines, our novel triage policy is less aggressive and exclude less patients. \end{itemize} \noindent \textbf{Outline.} This rest of this paper is organized as follows. The end of this section is devoted to a brief literature review. In Section \ref{sec:model}, we introduce our Markov Decision Process (MDP) model. In Section \ref{sec:interpretable}, we introduce our tree policies for MDPs, we present the properties of optimal tree policies and we present our algorithm to compute good tree policies. In Section \ref{sec:Monte-learning-simu-setup}, we present our numerical study (data set, MDP model, simulation model), applying our framework to mechanical ventilator allocations for COVID-19 patients. We discuss our empirical results in Section \ref{sec:Monte-learning-simu-results}, where we detail our comparison of various triage guidelines under different levels of ventilator shortages. \subsection{Related literature} Our work primarily builds upon (i) triage guidelines for scarce healthcare resources, (ii) decision trees and MDPs for decision making in healthcare, and (iii) recent advances to compute interpretable decisions in sequential decision-making. \noindent \textbf{Triage guidelines in the Operations Management literature.} There is a large body of literature in the operations management (OM) and medical literature on designing efficient triage guidelines for allocations of scarce healthcare resources. In a broad sense, the usual objective is of \textit{doing the greatest good for the greatest number}~\citep{frykberg2005triage}. For instance, \cite{sacco2007new} proposes to use linear programming to determine priorities among patients in the hospitals, and \cite{jacobson2012priority} rely on sample-path methods and stochastic programming for computing policies for assignments to key resources (such as ambulances and operating rooms) in the aftermath of mass-casualty events. \cite{kim2015icu} estimates the impact of ICU admission denials on the outcomes of the patients. Triage conditions can be tailored to various situations, including austere conditions and imperfect information~\citep{argon2009priority,childers2009prioritizing,li2010approximate,sun2018patient} or specific health conditions, such as burn-injured patients~\citep{chan2013prioritizing}. Note that triage guidelines are also of interest in other area of OM, e.g. allocating customers to servers~\citep{dobson2011impact,alizamir2013diagnostic}. Other works analyze directly the regimes where triage may or may not be beneficial~\citep{sun2019triage}, and the impact of available capacity on triage decisions~\citep{chen2020effects}. \tb{Perhaps most similar to our paper is the work in \cite{anderson2021rationing}. The authors also look at the NYS ventilator allocation guidelines and compare to two guidelines they developed which incorporate machine learning predictors (regularized logistic regressions) beyond just the Sequential Organ Failure Assessment (SOFA) score. We take a different methodological approach. While \cite{anderson2021rationing} focus on the prediction of survivability and length-of-ventilation, we develop a methodology to identify a tree-based policy to allocate ventilators, emphasizing the interpretability of our decision guidelines.} More generally, the efficiency of the triage guidelines are often demonstrated numerically and, in some instances, some structural properties of optimal policies can be derived theoretically. Many of these works focus on index policies in order to facilitate implementation, even if the optimal policy is quite complex. The indices are often derived from aggregate metrics which capture factors like survival risk, length-of-stay, and/or risk of mis-triage. However, such approaches can obscure clinical features resulting in lack of \textit{interpretability} and are not easily explainable to the medical staff. \noindent \textbf{Decision trees and MDPs in healthcare.} Tree-based models are popular in general classification tasks, and specifically in healthcare applications. Indeed, they provide a decision model that often achieves high classification accuracy based on simple decision rules. Classical heuristics such as CART \citep{breiman1984classification} and C4.5 \citep{quinlan2014c4} scale well but often return suboptimal trees, while optimal solutions can be computed with integer programming~\citep{bertsimas2017optimal}. In healthcare, decision trees have been used in a number of settings including diagnosing heart diseases \citep{shouman2011using}, developing novel non-linear stroke risk scores \citep{orfanoudaki2020machine}, and predicting survival probability of the patients~\citep{bertsimas2020optimal}. As the scope of applications of decision trees to healthcare decision-making is very large, we refer the reader to the reviews in \cite{tomar2013survey} and \cite{dhillon2019machine}. Most of these applications are based on static \textit{predictions} (e.g., diagnosis) of the diseases and do not take into account the dynamic evolution of the health of the patient over time. In contrast, we build upon the Markov Decision Process (MDP) literature to better model the impact of our decisions over time. Markov Decision Processes (MDPs) provide a simple framework for the analysis of \textit{sequential} decision rules. This is the reason why MDPs are widely used in many healthcare applications, where the evolution of the patient's health impacts the sequence of decisions chosen over time. The use of Markov models in healthcare can be traced back to \cite{beck1983markov}. In particular, MDPs have been used, among others, for kidney transplantation \citep{mdp-kidney}, HIV treatment recommendations \citep{mdp-HIV}, cardiovascular controls for patients with Type 2 diabetes \citep{mdp-steimle} and determining proactive transfer policies to the ICU \citep{grand2020robust}. We refer the reader to \cite{mdp-med-1} for reviews of applications of MDP to healthcare. \noindent \textbf{Interpretable sequential decision-making.} Decision trees are efficient where there is a single decision epoch. This is the setting where there has been the most traction of interpretable machine learning in healthcare settings~\citep{khan2008predicting,amin2018performance,bertsimas2020optimal}. In contrast, MDPs are suitable for modeling sequential decisions but do not, a priori, incorporate interpretability constraints. Recently, there has been some works toward developing methods for interpretable policies in sequential decision-making(not necessarily specific to the healthcare setting). \cite{bravo2020mining} propose to explain the optimal unconstrained policies with decision trees, applying their framework to classical operations problems such as queuing control and multi-armed bandit (MAB). However, this may be misleading, as there is no guarantee that the novel explainable, suboptimal policies have the same performance as the unconstrained, optimal policies \citep{rudin2019stop}. \cite{ciocan2018interpretable} introduce the notion of tree policies for stopping time problems and design an algorithm returning an interpretable stopping policy. Their algorithm builds upon top-down approaches for computing classification trees given a data set of observations and labels. Note that the set of actions for a stopping time problem is $\{$\textit{go, stop}$\}$. In contrast, we focus on MDPs where the set of actions can be any finite set. Additionally, we characterize the theoretical properties of optimal tree policies, which may be history-dependent but can always be chosen to be deterministic. Finally, our algorithmic framework is also different from \cite{ciocan2018interpretable}. In particular, \cite{ciocan2018interpretable} modifies an algorithm for computing classification trees (CART, from~\cite{breiman1984classification}) to compute stopping time policies. In contrast, we modify an algorithm for computing MDP policies (value iteration) by exploiting an algorithm for classification trees as a subroutine at every iteration (see Algorithm \ref{alg:VI-OTP}), to force value iteration to only visit tree policies. Our overall algorithm is independent of the subroutine used to compute decision trees, and heuristics or optimal methods can be chosen, depending of the preference for fast computations or accuracy of the decision trees returned. \section{Model of sequential decisions}\label{sec:model} Our goal is to develop guidelines for determining which patients to allocate (or not) a healthcare resource. We consider the dynamic evolution of patient health and how to utilize this information in making triage decisions. We consider a finite-horizon Markov Decision Process (MDP) to model the patient health evolution and we develop a methodology to compute policies, which admit simple \textit{tree} representations at every decision epoch. In Section \ref{sec:Monte-learning-simu-setup}, we will examine the application of our methodology to ventilator allocations for COVID-19 patients. We consider a fairly general setting of sequential resource allocation in healthcare. Patient health evolves stochastically over time. We consider the allocation of a single type of healthcare resource (e.g., ICU beds, mechanical ventilator, specialized nurses, medications) to different patients. The nature of the allocation guideline is \textit{sequential}; the decision can be revisited multiple times and can depend on: 1) the current resource capacity, 2) the current health condition of the focal patient and its potential subsequent improvement and deterioration, and 3) the current health conditions of all other patients and their potential subsequent improvements and deteriorations. Because of the capacity constraint, the decision of allocating a resource (as well as how much) to a single patient impacts the ability to treat other current and, possibly, future patients. While most prior works reduce the state-space by restricting to two classes of patients and/or ignoring the evolution of patient health, the richer model of patient health is an important component of our data-driven approach to triage. \subsection{Evolution of Patient Health and Action Space} We model the health condition of each patient according to a finite-state Markov Chain. We let $s_{t} \in \mathbb{S}_{t}$ denote the health state of a patient in period $t$. Each state represents the health condition which may include information such as vital signs and lab values, as well as comorbidities and demographics. In our specific application to mechanical ventilator allocation we will consider multi-dimensional states, but our model allows for more general, arbitrary (finite) set of states. The vector $\bm{p}_{1}$ represents the likelihood to start in each state in $\mathbb{S}_{1}$. In contrast to the existing OM triage literature, we allow for an arbitrary (finite) number of patient health states that evolve stochastically depending on the action taken. At each period $t$, let $\mathbb{A}_{t}$ denote the set of discrete possible actions. For example, one could consider a binary decision of whether to intubate or extubate a patient when considering ventilator allocations. Alternatively, one could consider different levels of drug dosages -- $\{\sf 100mg, 200mg, 300mg\}$ -- for medication allocation. Once an action $a_{t}$ is chosen based on a policy, the patient transitions to the next state $s_{t+1} \in \mathbb{S}_{t+1}$ with probability $P_{s_{t}a_{t}s_{t+1}}$. The transitions represent the health evolution of the patient toward future states. We assume that the transitions are \textit{Markovian} to keep the model tractable. Terminal states in $\mathbb{S}_{H}$ represent the status at discharge, typically in the set $\{ {\sf deceased, alive} \}$. For conciseness, we assume that the set of states $\mathbb{S}_{1}, ..., \mathbb{S}_{H}$ attainable at period $t=1,...,H$, are disjoint. This allows use to consider transition kernels and costs that do not depend of the current period. \subsection{Capacity Constraint} Explicitly modeling both the complex patient health evolution over time and the capacity constraint of the shared resource leads to a high-dimensional MDP formulation, which is intractable. When considering the multi-patient allocation problem, a common assumption is that the dynamics of the patients are independent: they are only linked by the utilization of the common resource. This can be seen as a form of weakly coupled processes~\citep{adelman2008relaxations}, and a relaxation of this multi-patients allocation problem can be obtained as a classical Markov Decision Process (MDP), describing the health evolution and resource allocation to a single patient, with adequate penalization of the costs vectors. As such, to facilitate some tractability to derive interpretable policies, we consider the allocation for an individual patient and implicitly incorporate the capacity constraint via appropriately defined cost parameters. In particular, in each period $t$, a cost $c_{s_{t}a_{t}}$ reflects the cost incurred given the patient health state $s_t$ and action taken $a_t$. Intuitively, one would expect that the cost is non-decreasing in the amount of resources allocated to the patient. The cost parameters reflect the (potentially multiple) objective(s) of the decision maker and can incorporate 1) patient risk of bad outcomes, 2) costs of using healthcare resources (both explicit as well as opportunity costs), and 3) potential risks associated with the action (e.g., complications). The costs can be increased to deter the decision maker from using too much resources compared to a model without any capacity constraint. More rigorously, \cite{adelman2008relaxations} show that the Lagrangian relaxation of a weakly coupled multi-agent decision process results in a single-agent decision process with costs augmented by a factor proportional to the Lagrange multiplier. While our model ultimately focuses on a single patient with dynamic health state and accounts for the capacity constraint via the cost formulation, we note that the focus on a single patient is the standard approach in designing triage algorithms in the medical community. In particular, the majority of triage guidelines are myopic, and they are only executed when the capacity constraint is met. When there are any available resources, resources are allocated myopically (i.e., to patients that require them) without concern about the future potential of running out of capacity~\citep{zuckerventilator,white2020framework}. \subsection{Objective function and decision rule}\label{sec:nominal-MDP} The goal of the decision maker is to minimize the expected cost $C(\pi)$ associated with a \textit{policy} $\pi=\left(\pi_{1},...,\pi_{H}\right)$, which is a sequence of \textit{decision rules} $\pi_{t}$ over a finite horizon $H$. Each decision rule $\pi_{t}$ maps a \textit{history up to period t}, $h_{t}=(s_{1},a_{1},...,s_{t-1},a_{t-1},s_{t})$, to a distribution over the possible actions in $\mathbb{A}_{t}$. The cumulative expected cost associated with a policy $\pi$, $C(\pi)$, is calibrated to capture the balance between clinical objectives (e.g., optimizing survival of the patient) and costs of using resources. It is defined as \begin{equation}\label{eq:expected-cost} C(\pi) = \mathbb{E}^{\pi, \boldsymbol{P}} \left[ \sum_{t=1}^{H} c_{s_{t}a_{t}} \; \bigg| \; s_{1} \sim \bm{p}_{1} \right]. \end{equation} For a fixed Markovian policy $\pi$, we can associate a collection of \textit{value functions} $\left( \bm{v}_{t}^{\pi} \right)_{t \in [H]} \in \mathbb{R}^{\mathbb{S}_{1} \times .... \times \mathbb{S}_{H}}$, defined recursively as \begin{align*} v^{\pi}_{H,s} & = \sum_{a \in \mathbb{A}_{H}} \pi_{H,sa} c_{H,sa}, \forall \; s \in \mathbb{S}_{H},\\ v^{\pi}_{t,s} & = \sum_{a \in \mathbb{A}_{t}} \pi_{t,sa} \left(c_{sa} + \sum_{s' \in \mathbb{S}_{t+1}} P_{sas'} v^{\pi}_{t+1,s'} \right), \forall \; s \in \mathbb{S}_{t}, \forall \; t \in [H-1]. \end{align*} For each period $t \in [H]$ and state $s \in \mathbb{S}_{t}$, $v^{\pi}_{t,s}$ represents the cumulative expected cost from period $t$ to period $H$, starting from state $s$: \[v^{\pi}_{t,s} = \mathbb{E}^{\pi, \boldsymbol{P}} \left[ \sum_{t'=t}^{H} c_{s_{t'}a_{t'}} \; \bigg| \; s_{t} = s \right].\] From the definition of the cost $C(\pi)$ as in \eqref{eq:expected-cost}, we have $C(\pi) = \bm{p}_{1}^{\top}\bm{v}^{\pi}_{1}$. Crucially, an optimal policy $\pi^{*}$ which minimizes the expected cost \eqref{eq:expected-cost} can be chosen to be \textit{Markovian} ($\pi^{*}_{t}$ only depends of the current state $s_{t}$ and not of the whole history $h_{t}$), and \textit{deterministic} (for each state $s_{t}$, $\pi^{*}_{t}$ chooses a degenerate distribution over $\mathbb{A}_{t}$ with weight $1$ on one action and $0$ everywhere). Additionally, $\pi^{*}$ can be computed using the following \textit{value iteration} algorithm~\citep{Puterman}: the value functions $\left( \bm{v}_{t}^{*} \right)_{t \in [T]} \in \mathbb{R}^{\mathbb{S}_{1} \times .... \times \mathbb{S}_{H}}$ of an optimal policy $\pi^{*}$ follow the \textit{Bellman optimality equation} \eqref{eq:Bellman-recursion}: \begin{equation}\label{eq:Bellman-recursion} \begin{aligned} v^{*}_{H,s} & = \min_{a \in \mathbb{A}_{H}} c_{H,sa}, \forall \; s \in \mathbb{S}_{H},\\ v^{*}_{t,s} & = \min_{a \in \mathbb{A}_{t}} c_{sa} + \sum_{s' \in \mathbb{S}_{t+1}} P_{sas'} v^{*}_{t+1,s'}, \forall \; s \in \mathbb{S}_{t}, \forall t \in [H-1], \end{aligned} \end{equation} and an optimal policy $\pi^{*}$ can be chosen as the policy that maps each state $s \in \mathbb{S}_{t}$ to the action attaining the $\arg \min$ in the \textit{Bellman equations} \eqref{eq:Bellman-recursion}. \section{Interpretable Policies}\label{sec:interpretable} In a healthcare setting, interpretability of the decisions is crucial to operationalize the guidelines and facilitate practical implementation of the policies, generate buy-in from policy makers and providers, and mitigate obscuring of any potential ethical issues. A priori, the optimal policy for a classical, unconstrained MDP instance may not have any interpretable structure. In this work, we use a model of interpretable decisions based on \textit{decision trees} \citep{breiman1984classification}. Intuitively, the goal is to compute an efficient policy for the finite-horizon MDP problem, which can be succinctly represented as an interpretable decision tree at each decision period. \subsection{Classification trees}\label{subsec:classification-trees} We start with a brief introduction to decision trees. Decision trees are widely used in classification problems \citep{breiman1984classification,bertsimas2017optimal}. We use the following definition of a decision tree and present two examples of decision trees in $\mathbb{R}^{3}$ in Figure \ref{fig:example-trees}. \begin{definition} Let $\mathcal{D}$ be a set of $m$ data points $(\bm{x}_{i},y_{i})$ where $\bm{x}_{i} \in \mathbb{R}^{p}$ are \textit{observations} and $y_{i}$ are \textit{labels} in $\mathcal{L}$, where $\mathcal{L}$ is a finite subset of $\mathbb{N}$. A classification \textit{tree} $T$ is a map $\mathbb{R}^{p} \rightarrow \{1, ..., K \}$, with $K \in \mathbb{N}$, which \textit{recursively} partitions $\mathbb{R}^{p}$ into $K$ disjoint sub-regions (called \textit{classes)}, using \textit{branch} nodes and \textit{leaf} nodes. Branch nodes rely on \textit{univariate} splits such as $x_{1} \leq 2$ or $x_{3} \leq 8$. The point $i$ follows the left branch if it satisfies the splitting condition, otherwise it follows the right branch. Each leaf defines a sub-region of $\mathbb{R}^{p}$, resulting from the sequence of splits leading to this leaf. Each sub-region is uniquely identified with a \textit{class} $c \in [K]$. Each class $c$ is then mapped to a probability distribution $\bm{\mu}_{c} \in \Delta(\mathcal{L})$ over the set of labels. The scalar $\mu_{cy}$ represents the probability that points belonging to the class $c$ are assigned label $y \in \mathcal{L}$. \end{definition} \begin{figure} \center \begin{subfigure}{0.40\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/Tree_ex_1} \caption{Deterministic tree.} \label{fig:tree-deterministic} \end{subfigure} \begin{subfigure}{0.40\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/Tree_ex_2} \caption{Randomized tree.} \label{fig:tree-randomized} \end{subfigure} \caption{Example of two decision trees with three branching nodes, four classes (indicated by the four colors at the leaves) and two labels $y_{1}, y_{2}$. The tree in Figure \ref{fig:tree-deterministic} is deterministic: at each class, a unique label ($y_{1}$ or $y_{2}$) is assigned. The tree in Figure \ref{fig:tree-randomized} is randomized: at each class, a probability distribution over $\{y_{1},y_{2}\}$ is assigned. Since there are only two labels, we only show $\mathbb{P}(y_{1})$ at each leaf.} \label{fig:example-trees} \end{figure} We write $\mathcal{T}(\mathcal{X},[K],\mathcal{L})$ as the set of decision trees defining $K$ sub-regions of the set $\mathcal{X} \subset \mathbb{R}^{p}$ and mapping these sub-regions to labels in $\mathcal{L}$. We write $C_{\sf tree}(T)$ the expected weighted \textit{classification error} of $T$: \begin{equation}\label{eq:classification-error-randomized} C_{\sf tree}(T) = \sum_{c=1}^{K} \sum_{i=1}^{m} \sum_{\ell \in \mathcal{L}} \omega_{i,\ell} 1_{ \{ T(\bm{x}_{i}) = c \}} \mu_{c\ell}, \end{equation} where $\left(\omega_{i,\ell} \right)_{i,\ell}$ are the weights associated with classifying observation $\bm{x}_{i}$ with a label of $\ell \in \mathcal{L}$. Typically, $C_{\sf tree}(T)$ simply counts the expected number of misclassified data points and $\omega_{i,\ell} = 0$ if and only if $\ell = y_{i}$, otherwise $\omega_{i,\ell}=1$. Note the bilinear terms $1_{ \{ T(\bm{x}_{i}) = c \}} \mu_{c\ell}$ in the definition \eqref{eq:classification-error-randomized} of $C_{\sf tree}(T)$; $C_{\sf tree}(T)$ can be expressed as a linear objective using standard reformulation techniques (see Appendix \ref{app:reformulation-linear-cost-function}). The Classification Tree (CT) optimization problem is to compute a classification tree which minimizes the expected classification error \eqref{eq:classification-error-randomized}: \begin{equation}\label{eq:cart}\tag{CT} \begin{aligned} \min & \; C_{\sf tree}(T) \\ & T \in \mathcal{T}(\mathcal{X},[K], \mathcal{L}) \end{aligned} \end{equation} Classical heuristics for \eqref{eq:cart} such as CART \citep{breiman1984classification} scale well but often return suboptimal trees. Optimal classification trees can be computed using reformulations as Mixed-Integer Linear Programming \citep{bertsimas2017optimal}. A certain number of \textit{interpretability constraints} can be incorporated in the set $\mathcal{T}(\mathcal{X},[K],\mathcal{L})$, including upper bounding the \textit{depth} of the tree, defined as the maximum number of splits leading to a sub-region. Smaller trees are easier to understand as they can be drawn entirely and prevent over-fitting~\citep{bertsimas2017optimal}. \subsection{Tree policies for Markov Decision Processes} Decision trees are a popular framework for finding interpretable classification rules, but are not a priori suitable for sequential decision-making. We develop an analogous notion of decision trees for MDPs, which we refer to as \textit{tree policies}. Intuitively, a policy $\pi$ is called a \textit{tree policy} if at every period $t$, the decision rule $\pi_{t}$ can be represented as a decision tree which assigns labels (actions, or treatments) from $\mathbb{A}_{t}$ to observations (states, or health conditions) from $\mathbb{S}_{t}$. In particular, we have the following definition. Recall that from our definition of a decision tree in Section \ref{subsec:classification-trees}, we see a tree $T$ as a map from the set of observations in $\mathbb{R}^{p}$ to a label in $\{1,...,K\}$, i.e., we have $T: \mathbb{R}^{p} \rightarrow \{1,...,\}$. \begin{definition}\label{def:tree-policies} Let $\mathcal{M}=(H,\mathbb{S},\mathbb{A},\bm{P},\bm{r},\bm{p}_{1})$ be an MDP instance. A policy $\pi= \left(\pi_{1},...,\pi_{H} \right)$ is a \textit{tree policy} if there exists some $K_{1},...,K_{H} \in \mathbb{N}$, and a sequence of classification trees $T = \left(T_{t} \right)_{t \in [H]}$ where $T_{1} \in \mathcal{T}(\mathbb{S}_{1},[K_{1}],\mathbb{A}_{1}), ..., T_{H} \in \mathcal{T}(\mathbb{S}_{H},[K_{H}],\mathbb{A}_{H})$ such that for any period $t \in [H]$, for any two states $s_{1},s_{2} \in \mathbb{S}_{1},$ for any history up to period $t$ $h_{t} = (s_{1},a_{1},...,s_{t-1},a_{t-1})$, we have \[T_{t}(s_{1}) = T_{t}(s_{2}) \Rightarrow \pi_{t,(h_{t},s_{1})a}=\pi_{t,(h_{t},s_{2})a}, \forall \; a \in \mathbb{A}_{t}.\] We define $\Pi_{T}$ the class of policies that are compatible with a particular sequence of classification trees $T$: \[ \Pi_{T} = \{ \pi \; | \; T_{t}(s_{1})=T_{t}( s_{2}) \Rightarrow \pi_{t,(h_{t},s_{1})a}=\pi_{t,(h_{t},s_{2})a}, \forall \; s_{1},s_{2} \in \mathbb{S}_{t}, \forall \; a \in \mathbb{A}_{t}, \forall \; h_{t} = (s_{1},a_{1},...,s_{t-1},a_{t-1}), \forall \; t \in [H] \}.\] We define $\mathbb{T}$ the set of all sequence of decision trees admissible for the MDP instance $\mathcal{M}$: \[\mathbb{T} = \{ T = \left(T_{t} \right)_{t \in [H]} \; | \; T_{t} \in \mathcal{T}(\mathbb{S}_{t},[K_{t}],\mathcal{L}_{t}), \forall \; t \in [H]\}.\] \end{definition} Note that we have defined tree policies that are a priori history-dependent. While this is more complex than simply considering Markovian policies, we will show that an optimal tree policy can be history-dependent (see Proposition \ref{prop:properties-optimal-policy}), which is in contrast to the situation for classical unconstrained MDP where an optimal policy can be chosen to be Markovian. Note also that multiple tree policies can be associated with the same tree $T$, as different actions may be chosen at the leaves of tree $T$. For instance, consider the examples of Figure \ref{fig:example-tree-policies}. The decision rules from Figure \ref{fig:tree-policy-deterministic} and Figure \ref{fig:tree-policy-randomized} both have the structure of the decision tree represented in Figure \ref{fig:tree-zero}, but if $x_{1} \leq 8$, in Figure \ref{fig:tree-policy-deterministic} the action $a_{2}$ is chosen with probability $1$, whereas in Figure \ref{fig:tree-policy-randomized}, action $a_{2}$ is chosen with probability $0.65$. \begin{figure} \center \begin{subfigure}{0.30\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/Tree_ex_0} \caption{Decision tree $T$ with four classes and no labels. } \label{fig:tree-zero} \end{subfigure} \begin{subfigure}{0.30\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/Tree_policy_ex_1} \caption{Deterministic decision rule. } \label{fig:tree-policy-deterministic} \end{subfigure} \begin{subfigure}{0.30\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/Tree_policy_ex_2} \caption{Randomized decision rule.} \label{fig:tree-policy-randomized} \end{subfigure} \caption{Example of a tree $T$ (Figure \ref{fig:tree-zero}), a deterministic tree policy in $\Pi_{T}$ (Figure \ref{fig:tree-policy-deterministic}) and a randomized tree policy in $\Pi_{T}$ (Figure \ref{fig:tree-policy-randomized}). }\label{fig:example-tree-policies} \end{figure} Our goal is to compute an optimal tree policy, i.e., our goal is to solve the \textit{Optimal Tree Policy} (OTP) problem: \begin{equation}\label{eq:otp}\tag{OTP} \min_{T \in \mathbb{T}} \min_{\pi \in \Pi_{T}} \; C(\pi) \end{equation} \noindent \textbf{Relations with classification trees.} With a horizon of $H=1$, a tree policy is simply a decision rule that maps each state $s \in \mathbb{S}_{1}$ to a class $c \in [K]$ using a decision tree, then maps each class to an action $a \in \mathbb{A}_{1}$. If we identify the set of states $\mathbb{S}_{1}$ with the set of observations and the set of actions $\mathbb{A}_{1}$ with the set of labels, we see that instances of \eqref{eq:otp} (with $H=1$) and instances of \eqref{eq:cart} are equivalent. The costs for the MDP instance play the role of the weights in the definition of the classification error \eqref{eq:classification-error-randomized} in the classification tree instance. We provide a formal proof of Proposition \ref{th:equivalence-cart-otp} in Appendix \ref{app:equivalence-otp-cart}. \begin{proposition}\label{th:equivalence-cart-otp} Any instance of \eqref{eq:otp} with $H=1$ can be reduced to an instance of \eqref{eq:cart}. Additionally, any instance of \eqref{eq:cart} can be reduced to an instance of \eqref{eq:otp} with $H=1$. \end{proposition} Since \eqref{eq:cart} is an NP-hard problem~\citep{laurent1976constructing}, Proposition \ref{th:equivalence-cart-otp} shows that solving \eqref{eq:otp} is an NP-hard problem. From our proof of Proposition \ref{th:equivalence-cart-otp}, we also note that with a horizon $H=1$ and for a fixed tree $T_{1}$, computing an optimal policy in $\Pi_{T_{1}}$ is easy and can be done in a greedy fashion. When $\omega_{i,\ell} = 1_{ \{ \ell = y_{i} \}}$ for $\ell \in \mathcal{L}, i \in [m]$, this is analogous to the \textit{majority rule}, where the label assigned to each class is simply the most represented label in each class. However, computing an optimal tree (along with the optimal policy) is NP-hard, even with $H=1$. This shows that when $H=1$, the hardness of \eqref{eq:otp} comes from computing an optimal decision tree: computing an optimal policy afterward is straightforward. Interestingly, \cite{ciocan2018interpretable} consider the problem of computing tree policies for \textit{stopping time problems}, and show that when $H \geq 2$ and a tree $T$ is fixed, computing an optimal policy in $\Pi_{T}$ is also NP-hard. \noindent \textbf{A first approach to computing tree policies.} As highlighted in Proposition \ref{th:equivalence-cart-otp}, it is hard to compute an optimal tree policy, even when $H=1$. Still, a natural heuristic to return tree policies can be as follows. First, compute the optimal \textit{unconstrained} policy $\pi^{*} = \left( \pi^{*}_{1},...,\pi^{*}_{H} \right)$ for the MDP. This can be done efficiently with value iteration. Second, fit a classification tree to each of the optimal unconstrained decision rules $\pi_{1}^{*},...,\pi^{*}_{H}$. Intuitively, this heuristic first solves the (unconstrained) MDP, then ``projects'' the optimal policy onto the set of tree policies. The problem with this approach is that for any $t \in \{1,...,H-1\}$, $\pi^{*}_{t}$ is the optimal choice of decision for period $t$ \textit{only} if the decision maker chooses $\pi_{t+1}^{*}, ..., \pi^{*}_{H}$ subsequently. This follows from the recursion in the Bellman optimality equation \eqref{eq:Bellman-recursion}. In particular, if the decision-maker modifies his/her decisions $\pi_{t+1}^{*}, ..., \pi^{*}_{H}$ to obtain tree policies, then $\pi^{*}_{t}$ may not be optimal at period $t$, and it is irrelevant to fit a tree to $\pi^{*}_{t}$. We characterize the optimal tree policies in the next section. \subsection{Structural Properties of optimal tree policies} In the unconstrained MDP setting presented in Section \ref{sec:model}, an optimal policy may be chosen to be Markovian, deterministic, and independent of the initial distribution $\bm{p}_{1}$~\citep{Puterman}. In the following proposition, we contrast these properties with the properties of optimal tree policies. \begin{proposition}\label{prop:properties-optimal-policy} Consider an MDP instance $\mathcal{M}$, a set of sequence of trees $\mathbb{T}$ feasible for $\mathcal{M}$ and a feasible sequence of trees $T \in \mathbb{T}$. \begin{enumerate} \item All optimal tree policies for $T$ may depend on the initial distribution $\bm{p}_{1}$. \item All optimal tree policies for $T$ may be history-dependent. \item There always exists an optimal tree policy for $T$ that is deterministic (even though it may be history-dependent). \end{enumerate} \end{proposition} We present a detailed proof in Appendix \ref{app:properties-opt-policy}. Intuitively, in an instance of \eqref{eq:otp}, the optimal decision at period $t$ depends on the current distribution over the states $\mathbb{S}_{t}$, which itself depends on the history up to period $t$. We also note that the optimality of deterministic policies is important for deploying policies in practice. \noindent \textbf{The role of rectangularity.} We finish this section by discussing the fundamental role of \textit{rectangularity} in value iteration and contrasting it with the decision tree structure. The rectangularity assumption is a common assumption in the robust optimization and robust MDP literature \citep{Iyengar,BBC08,Kuhn,GGC}. In the unconstrained MDP setting of Section \ref{sec:nominal-MDP}, the rectangularity assumption states that the decisions $\pi_{t,s}$ for $s \in \mathbb{S}_{t}$ can be chosen independently across $s \in \mathbb{S}_{t}$. In particular, the decisions chosen in one state $s$ do not influence the choice of the decision maker at another state $s'$ (at the same period). In this case, the minimization problems defining the recursions \eqref{eq:Bellman-recursion} on the value function $\bm{v}^{*}$ of the optimal policy $\pi^{*}$ can be solved independently across $s \in \mathbb{S}_{t}$ for every period $t \in [H]$. Crucially, this is also implies the component-wise inequality $\bm{v}^{*}_{t} \leq \bm{v}^{\pi}_{t}$ at any period $t$ for any Markovian policy $\pi$, since $\pi^{*}$ is solving the minimization programs \eqref{eq:Bellman-recursion} at each state independently. From the definition of tree policies (Definition \ref{def:tree-policies}), it is clear that the rectangularity assumption is {\it not} satisfied for tree policies, because if $\pi$ is a tree policy compatible with a given tree $T$, then $\pi$ must choose the same action for all the states in a given subregion of the state space (defined by a leaf of $T$). In this case, the recursion \eqref{eq:Bellman-recursion} may not hold for an optimal, interpretable policy. In particular, if there are some constraints across the decisions chosen at different states, a policy attaining the $\arg \min$ in \eqref{eq:Bellman-recursion} may not even be feasible. \subsection{Our algorithm} Since it is impractical to return history-dependent policies, we present an algorithm to compute Markovian tree policies. Our recursive algorithm, Algorithm \ref{alg:VI-OTP}, is based on the dynamic programming recursion \eqref{eq:Bellman-recursion}, but it forces the sequence of decision rules $\pi_{1},...,\pi_{H}$ to be compatible with some trees $T_{1},...,T_{H}$. Our algorithm alternates between computing a decision rule $\pi_{t}$ for period $t$, compatible with a classification tree $T_{t}$, and updating the value function $\bm{v}_{t}$ of values obtained by the decision maker between period $t$ and $H$ when the decision rules are $\pi_{t},...,\pi_{H}$. It then proceeds backward to obtain the next decision rule $\pi_{t-1}$. Therefore, we interweave an algorithm for computing classification trees (e.g., CART) and an algorithm for computing optimal unconstrained policies (value iteration). This is in contrast with the more naive approach described after Proposition \ref{th:equivalence-cart-otp}, that only uses CART \textit{after} an optimal unconstrained policy $\pi^{*}$ has been computed. \begin{algorithm}[H] \caption{Dynamic programming algorithm to compute a deterministic tree policy.}\label{alg:VI-OTP} \begin{algorithmic}[1] \State \textbf{Input} Sets of acceptable decision trees $\mathcal{T}(\mathbb{S}_{1},[K_{1}],\mathbb{A}_{1}), ..., \mathcal{T}(\mathbb{S}_{H},[K_{H}],\mathbb{A}_{H})$ at periods $t=1,...,H.$ \State \textit{Initialize the policy.} Let $t=H$ and $\hat{T}_{H} \in \mathcal{T}(\mathbb{S}_{H},[K_{H}],\mathbb{A}_{H}), \hat{\pi}_{H} \in \Pi_{H},$ solving \begin{equation*} \min_{T \in \mathcal{T}(\mathbb{S}_{H},[K_{H}],\mathbb{A}_{H})} \min_{\pi \in \Pi_{T}} \sum_{c \in [K_{H}]} \sum_{s \in \mathbb{S}_{H}} \sum_{a \in \mathbb{A}_{H}} 1_{ \{ T(s) = c \} } \pi_{sa} c_{H,sa}. \end{equation*} \State \textit{Initialize the value function.} Set $\bm{v}_{H} \in \mathbb{R}^{\mathbb{S}_{H}}$ such that $v_{H,s} = \sum_{a \in \mathbb{A}_{H}} \hat{\pi}_{H,sa} c_{H,sa}, \forall \; s \in \mathbb{S}_{H}.$ \For{$ t=H-1,...,1$} \State \textit{Choose the decision rule at period $t$.} \label{alg:step:policy-computation} Compute $\hat{T}_{t},\hat{\pi}_{t}$ the optimal solutions to the following Optimal Tree Policy problem with horizon $H=1$: \begin{equation}\label{eq:alg:otp-proxi-bellman} \min_{T \in \mathcal{T}(\mathbb{S}_{t},[K_{t}],\mathbb{A}_{t})} \min_{\pi \in \Pi_{T}} \sum_{c \in [K_{t}]} \sum_{s \in \mathbb{S}_{t}} \sum_{a \in \mathbb{A}_{t}} 1_{ \{ T(s) = c \} } \pi_{sa} \left( c_{sa} + \sum_{s' \in \mathbb{S}_{t+1}} P_{sas'} v_{t+1,s'} \right). \end{equation} \State \textit{Update the value function.} \label{alg:step:value-update} Set $\bm{v}_{t} \in \mathbb{R}^{\mathbb{S}_{t}}$ as \begin{equation*} v_{t,s} = \sum_{a \in \mathbb{A}_{t}} \hat{\pi}_{t,sa} \left( c_{sa} + \sum_{s' \in \mathbb{S}_{t+1}} P_{sas'} v_{t+1,s} \right), \forall \; s \in \mathbb{S}_{t}. \end{equation*} \EndFor \end{algorithmic} \end{algorithm} \paragraph{Discussion on Algorithm \ref{alg:VI-OTP}.} Several remarks are in order. First, our algorithm alternates between computing decision rules that are compatible with a tree in Step \ref{alg:step:policy-computation}, and updating the value function accordingly in Step \ref{alg:step:value-update}. Given the value function $\bm{v}_{t+1}$, \eqref{eq:alg:otp-proxi-bellman} is equivalent to an Optimal Tree Policy instance with $H=1$. From the equivalence of \eqref{eq:otp} and \eqref{eq:cart} (Proposition \ref{th:equivalence-cart-otp}), \eqref{eq:alg:otp-proxi-bellman} can be solved with either exact methods~\citep{bertsimas2017optimal} or heuristics~\citep{breiman1984classification}. Second, the optimal tree policy at period $t$ may depend of the distribution of the visited states $\mathbb{S}_{t}$, as follows from Proposition \ref{prop:properties-optimal-policy}. This distribution depends on the previous decisions, i.e., it depends on $\hat{\pi}_{1},...,\hat{\pi}_{t-1}$. When we choose the decision rule $\hat{\pi}_{t}$ of period $t$ in Algorithm \ref{alg:VI-OTP}, we have chosen $\hat{\pi}_{t+1},...,\hat{\pi}_{H}$, but not yet $\hat{\pi}_{1},...,\hat{\pi}_{t-1}$. For this reason, we simply consider a \textit{uniform} distribution over $\mathbb{S}_{t}$. In particular, in Step \ref{alg:step:policy-computation} we sum the continuation values associated with each state in $\mathbb{S}_{t}$. We then update the value function with the Bellman recursion in Step \ref{alg:step:value-update}. Finally, we would like to note that Algorithm \ref{alg:VI-OTP} can be seen as a heuristic to return a good tree policy, by incorporating the changes in future decision rules in our current decision. This is in contrast to the naive approach presented after Proposition \ref{th:equivalence-cart-otp} (simply fitting a tree to the optimal unconstrained policy $\pi^{*}$), which does not take into account that modifying the actions chosen at period $t'$ has an impact on the optimal actions in previous periods $t < t'$. Because the optimal policy may be history-dependent, it appears hard to prove guarantees on the performances of the policies returned by Algorithm \ref{alg:VI-OTP} or the naive approach. We will see in our numerical study that Algorithm \ref{alg:VI-OTP} computes tree policies that can outperform state-of-the-art allocation guidelines, in the case of ventilator triage for COVID-19 patients. \section{Mechanical Ventilator Triage for COVID-19 Patients}\label{sec:Monte-learning-simu-setup} In this section, we apply the methodology developed in Section \ref{sec:interpretable} to develop interpretable triage guidelines for allocating ventilators to COVID-19 patients and compare them to existing triage guidelines\footnote{Preliminary numerical results have appeared in \cite{grand2021estimation} and \cite{chuang2021quantifying}.}. \subsection{Current triage guidelines} New York State (NYS) policy follows the 2015 Ventilator Triage Guidelines which were recommended by the NYS Taskforce on Life and the Law~\citep{zuckerventilator}. These guidelines were designed to ration critical care services and staff following a disaster (e.g., a Nor'easter, a hurricane, or an influenza epidemic). In particular, the guidelines outline clinical criteria for triage of patients using the Sequential Organ Failure Assessment (SOFA) score, a severity score that has been shown to correlate highly with mortality in COVID-19~\citep{zhou2020clinical}. The goal of the NYS guidelines is to maximize the number of life saved. There are three decision epochs: at \textit{triage}, the first time that a patient requires a ventilator; and thereafter, at two \textit{reassessment periods} after 48 and 120 hours of intubation. The NYS triage guidelines defines \textit{priority classes} -- low, medium, and high -- based on the current SOFA score of the patient. At the reassessment periods, the classification also depends on the improvement/deterioration of the SOFA score since the last decision epoch. A patient with \textit{low} priority class will either be excluded from ventilator treatment (at triage) or removed from the ventilator (at reassessment). These patients typically either can be safely extubated, or have low survival chance (e.g., SOFA score $>$ 11). Patients with \textit{medium} priority class are intubated and maintained on a ventilator, unless a patient with \textit{high} priority class also requires intubation, in which case they are extubated and provided with palliative care. The guidelines at triage and reassessments admit simple tree representations (even though they were originally presented with tables). Details about the NYS guidelines are provided in Appendix \ref{app:details-NYS}. We note that the NYS guidelines were defined in 2015 and, hence, are \textit{not} specifically calibrated to the disease dynamics of COVID-19 patients. \subsection{Markov Model for COVID-19 Ventilator Triage}\label{subsec:MDP-triage-model} We now formalize the MDP model for COVID-19 ventilator allocation. \noindent \textbf{Decision epochs, states and epochs.} Recall that the NYS guidelines has only three decision periods: at triage and two reassessments. Therefore, we consider an MDP model where there are $H=4$ periods; the last period corresponds to discharge of the patients after 120h (or more) of intubation. Our MDP model is depicted in Figure \ref{fig:MDP-model}. After 0h/48h/120h of intubation, the patient is in a given health condition captured by the SOFA score (value of SOFA, and increasing/decreasing value of SOFA compared to last decision time), which changes dynamically over time, as well as static information on comorbidities and demographics. At triage (0h of intubation, t=1 in the MDP), the decision maker chooses to {\it allocate} the ventilator to this patient, or \textit{exclude} the patient from ventilator treatment. After 48h or 120h of intubation (t=2 and t=3 in the MDP), the decision is whether or not to {\it maintain} the patient on the ventilator. After the decision is executed, the patient transitions to another health condition or is nominally extubated before the next period which will correspond to a terminal state $D_{t}$ or $A_{t}$, indicating the status at discharge from the hospital ({\bf D}eceased or {\bf A}live) (see Figure \ref{fig:MDP-model-maintain}). If the patient is excluded from ventilator treatment, s/he transitions to state $D_{t}^{ex}$ (if s/he dies at discharge) or $A_{t}^{ex}$ (if s/he recovers at discharge), see Figure \ref{fig:MDP-model-exclude}. \noindent \textbf{Costs parameters.} The MDP costs reflect the relative preference for survival of the patient (compared to death), with a penalty for longer use of ventilators in order to reflect the reluctance for lengthy use of limited, critical care resources. In particular, the costs are associated with terminal states $D_{t},A_{t},D_{t}^{ex},A_{t}^{ex}$, for $t \in \{1,2,3\}$ (modeling 0h/48/120h of intubation). Since we want to minimize the number of deaths, the costs of the \textit{deceased at discharge} terminal states is significantly larger than that of the \textit{alive at discharge} terminal states. Additionally, we want to penalize the lengthy use of resources, i.e., more costs should be given to discharge after 120h (or more) of intubation compared to discharge after 0h to 48h of intubation, in order to capture the disutility of using the limited ventilator capacity. Finally, for a given outcome (deceased or alive), we aim to distinguish among the states where the patient was excluded or not. To capture these considerations, we parametrize our cost function with three parameters. We let $C > 1$ represents the cost for deceased patients, which is measured relative to a base cost of $1$ for patients who survive. Typically, $C$ one or two orders of magnitude higher than $1$; in our simulation we choose $C=100$. To penalize for using the limited resource, the cost for ventilator use increases by a multiplicative factor $\rho > 1$ for each period of ventilator use (corresponding to 48h, 120h, 120+h). This can be seen as an actualization factor, e.g., $\rho = 1.1 $ means that future costs are increasing by $10 \%$ (per period) compared to the same outcome at the current period. This cost reflects the desire to use resources for shorter periods. We choose $\rho=1.1$ in our simulation. Finally, among patients who survive, a multiplicative penalty of $\gamma >1$ is given to patients who have been extubated, while for patients who die, a multiplicative bonus of $1/\gamma <1$ is given to patients who have been extubated. Choosing $\gamma$, one needs to be careful to maintain the costs for deceased patients higher than the costs for patients discharged alive. We choose $\gamma = 1.5$ in our simulation. We recommend values of $C,\rho$ and $\gamma$ to maintain $C/\gamma >> \gamma \rho^{2}$, so that any state associated with deceased patients have higher costs than any state associated with patients alive at discharge. Our final costs functions can be represented as \[ c(A_{t}^{\sf \ell}) = 1 \times \rho ^{t-1} \times \gamma^{\mathbbm{1}_{ \{\ell = \sf ex \}}}, \; c(D_{t}^{\sf \ell}) = C \times \rho^{t-1} \times (1/\gamma)^{\mathbbm{1}_{ \{ \ell = \sf ex \}}}, \forall \; t \in \{1,2,3\}.\] While this cost parametrization is an artifact of our model and is necessary to compute the triage policy, we evaluate the performance of the resulting policy through simulations, which estimate its potential performance in practice. We also conduct a sensitivity analysis, where we vary the values of $C,\rho$ and $\gamma$, and study the variations in the estimated performances of the corresponding optimal policies and tree policies in the MDP. We observe stable performances in the simulation model for the optimal policies and tree policies for a wide range of parameters $C, \rho,\gamma$, as long as $C/\gamma$ is significantly larger than $\gamma \rho^{2}$. We present the sensitivity analysis in Appendix \ref{app:sensitivity-analysis}, \begin{figure}[htb] \center \begin{subfigure}{0.48\textwidth} \centering \includegraphics[width=0.95\linewidth]{figures/MDP-model-triage-action-maintain} \caption{Transition for action = \textit{maintain}.} \label{fig:MDP-model-maintain} \end{subfigure} \begin{subfigure}{0.48\textwidth} \centering \includegraphics[width=0.95\linewidth]{figures/MDP-model-triage-action-exclude} \caption{Transition for action = \textit{exclude}.} \label{fig:MDP-model-exclude} \end{subfigure} \caption{States and transitions in our MDP model with actions \textit{`maintain'} and \textit{`exclude'}.} \label{fig:MDP-model} \end{figure} \subsection{Data set and parameter estimation}\label{subsec:triage-data-set} To calibrate our model, we utilize a retrospective data of 807 COVID-19 hospitalizations at Montefiore. In particular, we include patients with confirmed laboratory test (real-time reverse polymerase chain reaction) for SARS-CoV-2 infection, admitted to three acute care hospitals within a single urban academic medical center from 3/01/2020 and 5/27/2020, with respiratory failure requiring mechanical ventilation. This hospital system is located in the Bronx, NY, which was one of the hardest hit neighborhoods during the initial COVID-19 surge seen in the United States. This study was approved by the Albert Einstein College of Medicine/Montefiore Medical Center and Columbia University IRBs. Each hospitalization corresponds to a unique patient. For each patient, we have patient level admission data. This includes demographics such as age, gender, weight, BMI, as well as comorbid health conditions such as the Charlson score, diabetes, malignancy, renal disease, dementia, and congestive heart failure. Our data provides admission and discharge time and date, as well as status at discharge from the hospital (deceased or alive). Finally, every patient in our data set is assigned a SOFA score, which quantifies the number and severity of failure of different organ systems ~\citep{jones2009sequential}, and which is updated every two hours. The ventilator status of the patients (intubated or not) is also updated on a two-hours basis. The hospital that we study was able to increase ventilator capacity through a series of actions, including procurement of new machines, repurposing ventilators not intended for extended use, and borrowing of machines from other states. The maximum number of ventilators that were used for COVID-19 patients over the study period was 253. The hospital never hit their ventilator capacity, so triage was never required to determine which patients to intubate. The mean SOFA score at admission was 2.0 (IQR: [0.0,3.0]) and the maximum SOFA score over the entire hospital stay was 9.7 (IQR: [8.0,12.0]). The mean age was 64.0 years (SD 13.5). The patients who survived were significantly younger than those who died in the hospital (p$<$0.001). The average SOFA at time of intubation was 3.7 (IQR: [1.0,6.0]), at 48 hours it was 6.3 (IQR: [4.0,9.0]) and at 120 hours it was 5.9 (CI: [3.0,8.0]). Details and summary statistics about the data set and our patient cohort are presented in Table \ref{tab:summary-statistics} in Appendix \ref{app:details-data-set}. \subsection{Model Calibration} To calibrate the MDP model, we utilize {\em static} patient data assigned at the time of admission (e.g., history of comorbodities), and {\em dynamical} patient data updated on a two-hour basis (e.g., SOFA score and intubation status). We calibrate the transition rates across states, as well as the likelihood of deaths and survival at each period, using the observed rates for these events from the data. The transition rates depend on the information included in the states. To reduce the total number of states and to increase the number of observations and transitions per states, we first create $k=10$ clusters using $k$-means when using more information than just the SOFA score. A state then consists of a cluster label, and the current SOFA score, and the direction of change of the SOFA score (decreasing or increasing, compared to last triage/reassessment period). Note that in our data we do not observe any early extubation (i.e., we only observe extubation when it is safe or when the patient is deceased). Therefore, we cannot estimate the transition rates to $D^{ex}_{t}$ (the death state if extubated between period $t$ and the next period). We use a single parameter $p \in [0,1]$ for the transitions to $D^{ex}_{t}$. We choose a uniform $p$ across periods $t \in \{1,2,3\}$ and states. This gives a range of estimates, from optimistic estimates ($p=0$) to more realistic estimates ($p \geq 0.9$), with values $p=0.90$ and $p=0.95$ being closer to the death rates estimated by our clinical collaborators. We note that some patients may be intubated more than once during their hospital visits. This can happen when the health condition of an intubated patient first improves, the patient is safely extubated, and then the health condition starts to deteriorate again. We do not account for this in our MDP model, as this is a relatively rare event. In our data, it occurs in only 5.7\% of the patients. Therefore, we treat second ventilator uses as {\it new trajectories}, starting from period $t=1$. While the dynamical health evolution of the patient who are reintubated may differ from the dynamics of the patients who are intubated for the first time, we emphasize that only the computational part (i.e., computation of tree policies for the MDP in Figure \ref{fig:MDP-model}) is based on this approximation. The evaluation of patient survival with our simulation model does not depend on this approximation. \subsection{Policy Computation} We use Algorithm \ref{alg:VI-OTP} for our MDP model to compute several tree policies using different covariates describing the health conditions of the patients. We first compute a tree policy that only uses the SOFA score (Figure \ref{fig:tree-sofa}), since this is the only covariate used in the NYS guidelines. We then compute a tree policy based on SOFA and age of the patient (Figure \ref{fig:tree-sofa-age}), as there is some debate about making categorical exclusions based on age: for example, the NYS guidelines break ties based on age. We also compute a tree policy based on all the comorbid conditions and demographic information available in our data (Figure \ref{fig:tree-sofa-covariates}). When we include covariates other than SOFA scores, we create 10 clusters to reduce the final number of states and transitions. For instance, for the policies based on SOFA scores and age, the final states in the MDP of Figure \ref{fig:MDP-model} consists of pairs $({\sf sofa},\ell,+/-)$ where ${\sf sofa}$ is the current SOFA score, $\ell$ is a cluster label describing the age of the patient, and $+$ or $-$ captures whether patient condition is improving or worsening. We present the details of the covariates used in the full tree policy along with the corresponding trees for each computed policy in Appendix \ref{app:tree-policies} . We note that one needs to be cognizant of potential ethical considerations when including certain covariates. For instance, diabetes has been shown to be correlated with higher risk of severe COVID~\citep{orioli2020covid}. However, increased prevalence of diabetes (and other risk factors for severe COVID patients) is observed in underserved communities who have suffered from structural health inequities. Excluding patients from ventilator access on the basis of such covariate could further exacerbate these long-standing structural inequities. As such, there are several ethical justifications for the absence of categorical exclusion criteria from the triage decisions~\citep{white2020framework}. During the COVID-19 pandemic, there has been a movement away from including these covariates in triage algorithms, because of the potential to exacerbate inequities~\citep{mello2020respecting}. We believe there is value in estimating the potential benefits (or not) of including as much information as possible in the triage guidelines, to provide quantitative data on the consequences of these choices to inform this discourse. \section{Empirical results}\label{sec:Monte-learning-simu-results} We evaluate the performance of the tree policies computed using Algorithm \ref{alg:VI-OTP}. We compare to two benchmarks: 1) NYS Triage guidelines and 2) First-Come-First-Serve (FCFS). For all policies -- including ours -- ventilators are allocated according to FCFS until the ventilator capacity is reached. When there is insufficient ventilator supply to meet all of the demand, they will be allocated according to the specified priority scheme. \subsection{Simulation model}\label{subsec:triage-simulation-model} We use simulation to estimate the number of deaths associated with implementation of the various triage guidelines at different levels of ventilator capacity. Specifically, we bootstrap patient arrivals and ventilator demand from our data and examine different allocation decisions, based on our MDP model. The time periods considered consist of a discretization of the time interval (03/01/20 - 05/27/20) into intervals of two hours. At each time period, the following events happen: \begin{enumerate} \item We sample (with replacement) the arrivals and ventilator demand from our data set of observed patients trajectories. The number of samples at each period is equal to the number of new intubations observed at this time period in our data. \item We update the status (intubated, reassessment or discharge) of all patients in the simulation. Prior to reaching ventilator capacity, ventilators are allocated on a first-come-first served basis. When the ventilator capacity is reached, new patients are triaged using the triage guideline chosen and assigned a priority (low, medium or high). Low priority patients are excluded from ventilator treatments. A medium priority patient currently intubated may be excluded from ventilator treatment, to intubate a high priority patient. High priority patients are never extubated. In particular, if all patients currently intubated have high priority, any remaining patients who need a ventilator will be excluded from ventilation; i.e., no patients currently intubated will be excluded from ventilator treatment. \item After 48h and 120h of intubation, patients on ventilators are reassessed and reassigned priority classes. Patients in low and medium priority classes are excluded from ventilator treatment if a new patient with higher priority requires one. Patients with low priority class are removed first. \end{enumerate} The First-Come-First-Served (FCFS) triage rule is operationalized as follows. When the capacity constraint is reached, no new patient is assigned a ventilator until one becomes available, regardless of priority classes. Extubation only occurs when the patient is deceased or can be safely extubated (the timing of which is indicated by extubation in the observed data). At discharge, the status of patients who were not impacted by the triage/reassessment guidelines (i.e. their simulated duration of ventilation corresponds to the observed duration in the data) is the same as observed in the data. For the outcomes of patients excluded from ventilation by the triage guideline, we use the same method as for our MDP model. In particular, we use a single parameter $p \in [0,1]$ to model the chance of mortality of patients excluded from ventilator treatment. With probability $p$, the discharge status of a patient excluded from ventilator treatment is deceased. Otherwise, with probability $1-p,$ the discharge status of a patient excluded from ventilator treatment is the same as if this patient had obtained a ventilator (i.e., the same as observed in the data). We acknowledge that the three potential exclusion events (at triage, at reassessments, or when removed in order to intubate another patient) may require different values of $p$. Additionally, $p$ may vary across patients and is difficult to estimate in practice. However, when $p = 0$, we obtain an optimistic estimate of the survival rate, since being excluded from ventilator treatment has no impact on the outcome of the patient. When $p = 1$, we obtain a pessimistic estimate of the survival rate, as in this case any patient excluded from ventilator treatment will die. Therefore, using a single parameter $p$ in $[0,1]$ enables us to interpolate between an optimistic ($p=0$) and a pessimistic ($p=1$) estimation of the survival rates associated with the triage guidelines. In practice, our clinical collaborators estimate that $p=0.90$ or $p=0.95$ are reasonable values. \subsection{Number of deaths} We obtain estimate of the number of deaths, associated with a ventilator capacity and triage guidelines over $100$ bootstrapped data sets. In Figure \ref{fig:number-of-deaths}, we compare the number of deaths associated with various levels of ventilator capacity for different triage guidelines: our tree policies based only on SOFA, based on SOFA and age, and based on SOFA and other covariates. For comparison purposes, we also include the performance of the NYS triage algorithm and FCFS. We also show the performance of the optimal unconstrained policy for our MDP model (which we call \textit{MDP policy} in Figure \ref{fig:number-of-deaths}). For the sake of readability, we only show the MDP policy computed based on SOFA score, as it is outperforming the MDP policies based on SOFA score and age, and SOFA score and other covariates. Recall that $p$ models the likelihood of death of a patient after exclusion from ventilator treatment. For brevity, we only present the pessimistic ($p=0.99$) estimations in the main body of the paper. The estimations for other values of $p$ are coherent with $p=0.99$ and are presented in Appendix \ref{app:simu-other-p}. We recall that the total number of deaths in our data set, i.e., with ample ventilator capacity, was 543 patients among our cohort of 807 patients (see Table \ref{tab:summary-statistics}). We see similar number of deaths between the NYS and FCFS policies. For instance, we consider the number of deaths at a ventilator capacity of 180 ventilators. The average total for the number of deaths is 582.9 (CI: [582.3,583.4]) for the NYS guidelines and 585.3 (CI: [584.5,586.1]) for the FCFS guidelines. While the difference in the number of deaths is statistically significant (at the p$<$0.001 level), this difference is small (two to three lives, less than 0.5\% of the total 543 observed deaths over a time period when triage was never necessary). In Figure \ref{fig:number-of-deaths} we observe this very small difference between the two policies for various levels of ventilator capacity. This also holds for various levels of $p \in [0,1]$ (see Appendix \ref{app:simu-other-p}). It is somewhat surprising to see the NYS and FCFS guidelines performing similarly in this cohort of COVID-19 acute respiratory failure. The NYS guidelines were designed prior to the COVID-19 pandemic, in part because of concerns that arose following the shortages experienced in New Orleans after Hurricane Katrina. Consequently, they were designed primarily for the case of ventilator shortages caused by \textit{disasters}, such as hurricanes, a Nor'easter, or mass casualty event. Therefore, even though the NYS guidelines is based on the SOFA score, it ignores the specifics of respiratory distress caused by COVID-19. For instance, this may indicate that COVID-19 natural history does not follow the 48 and 120 hours reassessment time line, with the average SOFA score at t=48h and at t=120h being somewhat similar in our patient cohort. The timing of reassessment in the NYS guidelines may need to be re-examined, otherwise the NYS triage algorithm is not able to substantially outperform FCFS. \begin{figure}[htb] \center \includegraphics[width=0.7\linewidth]{figures/number_of_deaths_p_99_new} \caption{Number of deaths for various triage guidelines at hypothetical levels of ventilator capacities, for $p=0.99$.} \label{fig:number-of-deaths} \end{figure} Still focusing on a ventilator capacity of 180 ventilators, we note that when only using information on SOFA, our tree policy achieves an average number of deaths of 574.1 (CI: [573.4,574.7]). The difference with the average number of deaths for the NYS guidelines amounts to 1.5 \% of the 543 observed deaths in our data. The optimal MDP policy only based on SOFA performs even better (average: 568.5 deaths, CI: [567.8,569.1]) but is not interpretable. We present our tree policy in Appendix \ref{app:tree-policies}. It is a very simple policy, which only excludes patients with SOFA strictly higher or equal to $11$ at triage and strictly higher or equal to 10 at reassessment. Thus, it is less aggressive than the NYS guidelines which may exclude some patients with SOFA $> 7$ at 48h and 120h of intubation, if their conditions is not improving (see Appendix \ref{app:details-NYS} for more details). This suggests that the NYS guidelines may be too proactive at excluding patients from ventilator treatments. We note that including other covariates (such as demographics and comorbidities, see \textit{Tree policy (SOFA+COV)} in Figure \ref{fig:number-of-deaths}) leads to similar performances compared to policies only based on SOFA score. This is coherent with the fact that the SOFA score itself has been shown to be a strong predictor of COVID-19 mortality~\citep{zhou2020clinical}. When we only include SOFA and age (\textit{Tree policy (SOFA+AGE)} in Figure \ref{fig:number-of-deaths}), we see higher number of deaths for the estimated tree policy, compared to policies only based on SOFA score. We note that including more covariates in the state space leads to a smaller number of transitions out of each state, leading to less accurate parameter estimations (even though we use clusters to lower the number of states in our MDP model). Therefore, this may reflect the fact that age is not a good predictor for COVID-19 mortality, so that including it in the state space only results in lower accuracy for parameter estimations, and does not result in a more informative description of the health state of the patient. Overall, the models that incorporate comorbidities and/or demographics do not significantly outperform the policies only based on SOFA. Categorical exclusion of some patients is considered unethical~\citep{white2020framework}, and we show that it is not necessarily associated with significant gains in terms of patients saved. \subsection{Observed survival rates among excluded patients} For each level of ventilator capacity and each triage guideline (NYS, FCFS, or tree policies), using our simulation model we can compute the list of patients that would have been excluded from ventilator treatments. In an ideal situation, triage guidelines would exclude from ventilator treatment patients who would not benefit from it, i.e., ideal triage guidelines would exclude the patients that would die \textit{even if intubated}. Note that using our data set we are able to know if a patient would have survived in case of intubation (since all patients were intubated in our data set and we can see status at discharge). Therefore, we can compute the survival rates (in case of intubation) among excluded patients. Intuitively, if the guidelines were perfect, the survival rate (in case of intubation) among excluded patients would be close to 0 \%. Note that random exclusion would achieve an average survival rate (in case of intubation) among excluded patients of 32.7 \%, the average survival rate in our cohort of patients. We compare the survival rate (in case of intubation) among excluded patients for various guidelines in Figure \ref{fig:true_survival_exclusion_NYS}-\ref{fig:true_survival_exclusion_sofa_covariates}. In Figure \ref{fig:true_survival_exclusion_NYS_triage}, we note that among the patients excluded by the NYS guidelines at triage, the survival rate in case of intubation would have been above 40 \% (for all levels of ventilator capacity). This is higher than 32.7 \% (p$<$0.001), which means that at triage, the NYS guidelines are mis-identifying patients who would not benefit from ventilator treatment. At reassessment, and compared to triage, the NYS guidelines achieve lower survival rates (in case of intubation) among patients excluded (Figure \ref{fig:true_survival_exclusion_NYS_reassessment}). Compared to NYS guidelines, our novel triage guidelines based on SOFA, SOFA and age, and SOFA, demographics and comorbidities, are identifying for exclusion those patients with lower survival rates (when intubated) (Figures \ref{fig:true_survival_exclusion_sofa_all}, \ref{fig:true_survival_exclusion_sofa_age_all},\ref{fig:true_survival_exclusion_sofa_covariates_all}). We note that the tree policy based on SOFA, demographics and comorbidities does not exclude any patient at triage (Figure \ref{fig:true_survival_exclusion_sofa_covariates_triage}). Additionally, among all policies, the survival rates (in case of intubation) among patients excluded \textit{at triage} is higher than the observed survival rates among patients excluded \textit{at reassessment}. This stark discrepancy between performances at triage and at reassessment suggests that it is significantly harder to foreshadow the future evolution of patients condition and status at discharge, at the moment of intubation. All the guidelines considered better identify patients who would not benefit from ventilator treatment, {\it after the patients have been intubated for at least 48h}. This may suggest that there should be more proactive decisions about withdrawing support from the patients who are not responding to intensive care treatment. Although ethicists generally consider the decision to proactively extubate a patient at reassessment morally equivalent to declining to offer intubation at triage, this action may cause more moral distress to clinicians carrying out the extubation~(see Chapter 5 in \citep{beauchamp2001principles}). Finally, we want to note that it is also important to account for the number of patients excluded by the guidelines. In particular, Figure \ref{fig:true_survival_exclusion_sofa_age_all} (for the tree policy based on SOFA and age) is very similar to Figure \ref{fig:true_survival_exclusion_sofa_all} (for the tree policy only based on SOFA) and Figure \ref{fig:true_survival_exclusion_sofa_covariates_all} (for the tree policy based on SOFA and other covariates). In contrast, we have seen in Figure \ref{fig:number-of-deaths} that the tree policy based on SOFA and age may perform quite poorly. Using our simulation model, we noted that on average it was excluding more patients. For instance, at a ventilator capacity of 180, it is excluding on average 233.5 patients (CI: [221.4,245.6]) compared to 191.7 patients for the tree policy based on SOFA (CI: [176.6, 206.8]) and 189.4 patients for the tree policy based on SOFA and other covariates (CI: [176.3,202.5]). This is mainly the reason behind the poor performance of the tree policy based on SOFA and age: even though it maintains a similar survival rate (in case of intubation) among excluded patients, it exclude more patients than the other tree policies, \textit{some of which would have survived in case of intubation}. The other tree policies are striking a better balance between excluding many patients and identifying patients who would not benefit from ventilator treatment. \begin{figure}[htb] \center \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_NYS_all} \caption{All excluded patients.} \label{fig:true_survival_exclusion_NYS_all} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_NYS_triage} \caption{Patients excluded at triage.} \label{fig:true_survival_exclusion_NYS_triage} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_NYS_reassessment} \caption{Patients excluded at reassessment.} \label{fig:true_survival_exclusion_NYS_reassessment} \end{subfigure} \caption{For NYS guidelines: observed survival rates (in the case of intubation) among all excluded patients (Figure \ref{fig:true_survival_exclusion_NYS_all}), patients excluded at triage (Figure \ref{fig:true_survival_exclusion_NYS_triage}) and patients excluded at reassessment (Figure \ref{fig:true_survival_exclusion_NYS_reassessment}).} \label{fig:true_survival_exclusion_NYS} \end{figure} \begin{figure}[htb] \center \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_sofa_all} \caption{Among all excluded patients.} \label{fig:true_survival_exclusion_sofa_all} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_sofa_triage} \caption{Among patients excluded at triage.} \label{fig:true_survival_exclusion_sofa_triage} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_sofa_reassessment} \caption{Among patients excluded at reassessment.} \label{fig:true_survival_exclusion_sofa_reassessment} \end{subfigure} \caption{For our tree policy only based on SOFA score: observed survival rates (in the case of intubation) among all excluded patients (Figure \ref{fig:true_survival_exclusion_sofa_all}), patients excluded at triage (Figure \ref{fig:true_survival_exclusion_sofa_triage}) and patients excluded at reassessment (Figure \ref{fig:true_survival_exclusion_sofa_reassessment}).} \label{fig:true_survival_exclusion_sofa} \end{figure} \begin{figure}[htb] \center \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_sofa_age_all} \caption{Among all excluded patients.} \label{fig:true_survival_exclusion_sofa_age_all} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_sofa_age_triage} \caption{Among patients excluded at triage.} \label{fig:true_survival_exclusion_sofa_age_triage} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_sofa_age_reassessment} \caption{Among patients excluded at reassessment.} \label{fig:true_survival_exclusion_sofa_age_reassessment} \end{subfigure} \caption{For our tree policy only based on SOFA score and age: observed survival rates (in the case of intubation) among all excluded patients (Figure \ref{fig:true_survival_exclusion_sofa_age_all}), patients excluded at triage (Figure \ref{fig:true_survival_exclusion_sofa_age_triage}) and patients excluded at reassessment (Figure \ref{fig:true_survival_exclusion_sofa_age_reassessment}).} \label{fig:true_survival_exclusion_sofa_age} \end{figure} \begin{figure}[htb] \center \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_sofa_covariates_all} \caption{Among all excluded patients.} \label{fig:true_survival_exclusion_sofa_covariates_all} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_sofa_covariates_triage} \caption{Among patients excluded at triage.} \label{fig:true_survival_exclusion_sofa_covariates_triage} \end{subfigure} \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.9\linewidth]{figures/true_survival_exclusion_sofa_covariates_reassessment} \caption{Among patients excluded at reassessment.} \label{fig:true_survival_exclusion_sofa_covariates_reassessment} \end{subfigure} \caption{For our tree policy based on SOFA score, demographics and comorbidities: observed survival rates (in the case of intubation) among all excluded patients (Figure \ref{fig:true_survival_exclusion_sofa_covariates_all}), patients excluded at triage (Figure \ref{fig:true_survival_exclusion_sofa_covariates_triage}) and patients excluded at reassessment (Figure \ref{fig:true_survival_exclusion_sofa_covariates_reassessment}).} \label{fig:true_survival_exclusion_sofa_covariates} \end{figure} \subsection{Discussion} \noindent \textbf{Advantages and disadvantages of SOFA-based guidelines.} SOFA-based guidelines have multiple advantages. First, the SOFA score has been shown to correlate with COVID mortality~\citep{zhou2020clinical}. They are simple to implement, as they rely on a single score, and can be deployed quickly in a number of different clinical and disaster scenarios before specifics of a new disease are known. This is why of the 26 states who have defined triage guidelines in the United States, 15 use the Sequential Organ Failure Assessment (SOFA) score to triage patients~\citep{babar2006direct}. In terms of performance, we have seen in Figure \ref{fig:number-of-deaths} that SOFA policies may achieve lower number of deaths than the official NYS policies (here, COVID-19). This suggests that NYS guidelines, also solely relying on SOFA scores, need to be adjusted to the current disaster before being successfully implemented. It may be possible to improve the performance of triage policies when even more disease-specific data become available, however, this will not solve the problem of how to manage a novel disaster in the future. Intuitively, incorporating more covariates in the decision model may help better inform triage guidelines. In contrast, our data show that using other clinical information (such as demographics and comorbidities) does not necessarily improve the number of lives saved. Additionally, including comorbid conditions may further disadvantage those who face structural inequities, since comorbidities such as diabetes and obesity are closely linked to social determinants of health~\citep{cockerham2017social}. This detrimental impact may erode trust in medical institutions at large~\citep{auriemma2020eliminating}, which in turn may frustrate other critical public health interventions such as vaccination~\citep{bunch2021tale}. Therefore, it is critical to counterbalance the utilitarian aims of saving more lives with fairness and the duty to patient care. Designing data-driven \textit{and} explainable guidelines is a first step toward fair and efficient allocation of resources. This study provides some data to inform the process of choosing to implement (or not) triage guidelines: official guidelines (such as NYS guidelines) need to be re-adjusted to the specifics of COVID-19 patients before being implemented. Otherwise, they may show little to no improvement compared to FCFS guidelines, and there may not be any ethical justification for unilaterally removing a patient from a ventilator and violating the duty to care for that patient. \noindent \textbf{Limitations.} The strength of our analysis is based on real world data during a massive surge in our facility where ventilator capacity reached fullness. There are several limitations to this study. First, the results cannot be applied to other disease states such as novel viruses that may arise in the future. The model needs to be re-trained with new data for each specific patient population. Second, the observations occurred during the height of the pandemic in New York City when little was known about the specific management of COVID-19. Results may be different with better therapeutic options for the disease. However, this is also a strength of the study given that it matches the scenarios in which triage guidelines are meant to be deployed. Third, the results could be different under different surge conditions, e.g. if the rise in number of cases was sharper or more prolonged. Finally, the simulation cannot mimic real-world work flows that might have required some alterations of the movement of ventilators between patients. From a modeling standpoint, our algorithm may not return an \textit{optimal} tree policy, since it only returns Markovian tree policies. Additionally, we use a \textit{nominal} MDP model, and do not attempt to compute a \textit{robust} MDP policy~\citep{Iyengar,Kuhn,GGC}. This reason behind this is that we have a fairly small population of patients, so that the confidence intervals in the estimation of our transition rates may be quite large, leading to overly conservative policies. To mitigate this, we use our simulation model to estimate the performances of a policy, and not simply the cumulative rewards in the MDP model, which, of course, also depends of our parameter choices. Therefore, even though the triage guidelines computed with Algorithm \ref{alg:VI-OTP} are dependent of the (possibly miss-estimated) transition rates and our choices of costs, the estimation of their performances is not, and is entirely data- and expert-driven, relying solely on our data set of 807 patients hospitalizations and our collaborations with practitioners at Montefiore. \section{Conclusion} In this work we study the problem of computing interpretable resource allocation guidelines, focusing on triage of ventilator for COVID-19 patients. We present an algorithm that computes a \textit{tree policy} for finite-horizon MDPs by interweaving algorithms for computing classification trees and algorithms solving MDPs. Developing bounds on the suboptimality of this tree policy compared to the optimal unconstrained policy is an important future direction. Additionally, we provide valuable insights on the performances of official triage guidelines for policy makers and practitioners. We found that the New York State (NYS) guidelines may fail to lower the number of deaths, and performs similarly as the simpler First-Come-First-Served allocation rule. Our empirical study finds that our interpretable tree policies based only on SOFA may improve upon the NYS guidelines, by being less aggressive in exclusions of the patients. Some medical studies have found that SOFA may not be informative for Sars-CoV-2 triage decisions~\citep{wunsch2020comparison}. We show that SOFA is not necessarily useless, but this depends greatly on how the decision maker uses it. Remarkably, our simulations also show that it may not be beneficial to include more information (e.g., demographics and comorbidities) in the triage and reassessment recommendations. In particular, this may not lead to lower number of deaths, on the top of raising important ethical issues. Overall, our simulations of various triage guidelines for distributing ventilators during the COVID-19 pandemic revealed serious limitations in achieving the utilitarian goals these guidelines are designed to fulfill. Guidelines that were designed \textit{prior} to the pandemic need to be reconsidered and modified accordingly to incorporate the novel data available. Our work can help revise guidelines to better balance competing moral aims (e.g., utilitarian objectives vs. fairness). Interesting directions include studying guidelines with later times of reassessments (e.g., reassessment after $7$ or $10$ days on ventilators) or different objectives (such the total number of \textit{life-years} saved). \small \bibliographystyle{plainnat}
{'timestamp': '2021-10-22T02:39:31', 'yymm': '2110', 'arxiv_id': '2110.10994', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.10994'}
arxiv
\section{Introduction} Tags are words or short sequences associated with a resource or a document. Depending on the context, the role of a tag differs. They could be used to describe feeling, category, source, content, ownership and others \cite{surver_social_tagging}. The tags associated with a document form a bag of words, where the order does not matter. Tags can be weighted or ranked by relevance, helping the machine or user to know which are the most accurate or specific to the document. Tags can be obtained with two different approaches: they can be machine extracted, where an algorithm process the resources and extract some of their characteristics \cite{the_million_song_dataset,Tang:08KDD}; or they can be handcrafted by \textit{experts} or \textit{non-experts}. In the expert case, the vocabulary is controlled, and the results would be comparable to machine extracted tags. In contrast, \textit{folksonomy} corresponds to non-expert tags, leading to a large corpus with redundant or mispelt tags. The corpus is often represented using the vector space model, where a document is represented by a sparse binary vector, where a $1$ encode the presence of a tag within the document. The document's tags cannot be rank by importance because a document is described by a binary vector. Tags can only be ranked within the corpus, and often shows power-law distribution \cite{power_tags}, making their analysis difficult because of the scarcity of frequent keywords and an abundance of unfrequent tags. Additionally, their number per document is relatively smaller than for usual textual documents, as the goal of tags is to provide a synthetic view of the document. This reduces the precision of an analysis when a tag is missing, as there is not enough tag redundancy to compensate for the absence of this tag. A way to improve the tag vector representation is to rely on an external database \cite{clustering_short_sequence_wiki} like WordNet \cite{Wordnet} or Wikipedia \cite{wikipedia} to add additional related tags to enrich the initial tag vector description. Another possibility is to rely on a probabilistic model \cite{DBSCAN_KL}, modeling keywords distribution based on available data. Tags can be use for information retrieval and recommendation. For a machine, it allows proposing related documents using tag co-occurrences. For a human, tags can be used to create \textit{tag clouds} \cite{tag_cloud} to help a user to refine its query by suggesting related keywords. A tag cloud displays the best co-occurring tags, adjusting the size, color, opacity of the tags to the context. Nonetheless, the tag cloud utility is limited due to the amount of irrelevant unorganized information \cite{tag_cloud_signalers}, \cite{begelman2006automated}. Rather than ranking tags against an initial query, another option is to cluster tags \cite{tag_clusters}, grouping them by context. Many algorithms, trying to cluster keywords alone, without clustering documents \cite{topic_detection_KL,keywords_clustering_autoclass,begelman2006automated} exist. These approaches do not take advantage of the duality between samples and features. For our particular setup where documents are succinctly described, it seems more relevant to use an algorithm clustering samples and features at the same time to improve the clustering quality. Co-clustering approaches cluster both on rows and columns together. Many approaches focus on the bipartite graph representation \cite{keywords_advertiser,co_clust_image_keywords,Dhillon01co-clusteringdocuments} of keywords and documents. \cite{Dhillon01co-clusteringdocuments} proposed to use the spectral decomposition to cluster samples and features using their eigenvector representation. The work \cite{Dhillon03InformationCoclustering} proposed using information theory methods, which given an initial partitioning alternates between row clusters refinement and column clusters refinement. There are two main problems in clustering: defining the target number of clusters, and defining the rules for cluster assignment. Concerning the cluster count, we propose a hierarchical agglomerative algorithm that stores the merging operation history. It free us from setting \textit{a priori} a specific number of clusters. Nonetheless, we suggest a stopping criterion to select an optimal partitioning. We follow the probabilistic and information theory approaches to cluster tags with limited information available. We follow a co-clustering approach to take advantage of the synergies between documents and keywords clustering. In this paper, we describe in the first part, a procedure to enhance keywords and documents context without the use of an external database. Next, the algorithm and its cost function are detailed. The details about datasets and metrics used are presented in the experimental setup section, followed by the experimental results. Then, the article ends with a discussion and a conclusion. \section{Enlarging Document Context} \subsection{Documents Keywords Matrix} Be $X=\{x_i\}_{i=1:n}$ the set of $n$ documents and $Y=\{y_j\}_{j=1:m}$ the set of $m$ keywords, which occur in the set of documents. Using the vector space model, a document is represented under the form of a binary vector $\mathbf{x}_i = [x_{i, 1}, ..., x_{i, m}]$ where a $1$ encodes the keyword's presence while a $0$ its absence in document $i$. The same representation applies to keywords, represented as $\mathbf{y}_j = [y_{j, 1}, ..., y_{j, n}]$, where a $1$ encodes the occurrence of keyword $j$ in a document. The collection of document vectors is often represented in a matrix form. The documents-keywords matrix is $M \in \{0, 1\}^{n \times m}$, with $M_{i, j} = x_{i, j} = y_{j, i}$, where rows represent documents and columns the keywords. \subsection{Similarity Matrix} In practice, the documents-keywords matrix is very sparse as a document is assumed to be tagged with only a few relevant keywords. For a keyword, the sparsity leads to very few keyword co-occurrence pairs with very low weight. In our particular case, we assume that keywords are exact and relevant, accurately extracted by the algorithms or experts, and none due to mistakes. This assumption simplifies the task of enhancing the keywords-documents matrix. Rather than searching for incorrect pairs first for data cleaning, all the keywords pairs are taken into account to improve the keywords-document matrix. To improve the matrix, we take advantage of the co-occurrence matrices, one measuring the document's similarity, the other measuring the keyword's similarity. A cosine-like similarity is used to compute the similarity between pairs of documents and keywords, $S^{(X)}$ and $S^{(Y)}$ respectively, taking values in $[0, 1]$. Instead of running the cosine similarity on binary vector, the values are adjusted by the relative frequency. For document $i$, each keyword is weighted by its frequency $c_k^{-1}$ where $c_k = \sum_{i} M_{i, k}$, to ensure that frequent keywords count less than infrequent ones. The same normalization is performed on keyword vectors, normalized by the number of keywords within each document $r_k = \sum_{j=1}^m M_{k,j}$. The document normalization has almost no effect, as the number of tags per documents is relatively homogeneous, but affect a lot keyword normalization, as they follow a power-law distribution. The document similarity is defined as: \begin{equation} S^{(X)}_{i, j} = \frac{\sum_{k=1}^{m} \frac{M_{i, k} M_{j, k}}{c_k} }{\sqrt{\left(\sum_k^m \frac{M_{i, k}}{c_k}\right) \left( \sum_k^m \frac{M_{j, k}}{c_k}\right)}} \label{eq:cosine} \end{equation} The equation \ref{eq:cosine} is adapted to compute $S^{(Y)}$ by making the sum over the rows rather than the columns (i.e., $\sum_{k=1}^n \frac{M_{k, i}}{r_k}$), and normalized by the number of keywords describing the document $r_k$. The normalization is equivalent to the inverse document frequency used in TF-IDF to score keywords by relevance, enabling to focus on singular keywords rather than frequent one. \subsection{Transition Matrix} The similarity matrix represents on a scale from $0$ to $1$ how well two elements are related. The closeness is characterized by a value close to $1$ while unrelatedness by $0$. Similar keywords can be either synonymous or occurring in the same context. In some way, the similarity matrix represents the co-occurrence laws. To exploit these relationships, we suggest transforming the similarity matrices into the form of Markov transition probability matrices, where $T_{i, j} = Pr(j \rightarrow i)$ is the probability to move to state $j$ starting from $i$. Using the product between $T$ and $M$, we would obtain a vector with weights representing the probability of obtaining a given keyword given the initial tags. A simple normalization of $S$ is not enough to obtain $T$. The normalization of $S$ ensures that the mass-distributed by an item to its neighbors is preserved after transformation, ie $|T \mathbf{u}^{\dagger}| = |u|$. However, it does not ensure that the mass is fairly attributed. Highly frequent keywords are more receptive than infrequent ones, as $\sum_{j} Pr(j \rightarrow i)$ is larger for frequent items. To rebalance the mass attribution, the matrix $T$ is obtained by bi-stochastization, leading to $T = T^{\dagger}$, ie $Pr(i \rightarrow j) = Pr(j \rightarrow i)$. We use the Sinkhorn-Knopp algorithm \cite{SK_sto_binorm}, which alternates between searching the best column normalization vector $\mathbf{c}$ and the best row normalization vector $\mathbf{r}$, repeating until convergence $\mathbf{c} = (S \mathbf{r})^{-1}$ and $\mathbf{r} = (S^{\dagger} \mathbf{c})^{-1}$. The transition matrix is obtained by: \begin{equation} T = \mathcal{D}(\mathbf{r}) S \mathcal{D}(\mathbf{c}) \label{eq:transition_matrix} \end{equation} where $\mathcal{D}(\mathbf{z})$ is the diagonal matrix with element $D_{i, i} = z_i$. \subsection{Matrix Smoothing with Mass Preservation} The two transition matrices are used to smooth the initial documents-keywords matrix using: \begin{equation} M^* = T^{(X)} M T^{(Y)} \label{eq:matrix_smoothing} \end{equation} The detail of a term of $M^*$ obtained following \ref{eq:matrix_smoothing} is: \begin{equation} M^*_{i, j} = \sum_{k=1}^n \sum_{\ell=1}^m Pr(x_i | x_k) Pr(y_j | y_{\ell}) M_{k, \ell} \label{eq:detail_matrix_smoothing} \end{equation} The term $M^*_{i, j}$ of \ref{eq:detail_matrix_smoothing} corresponds to all possible transitions to a document $i$ and keywords $j$ from all possible document-keyword pairs $M_{k \ell}$. The application of $T^{(Y)}$ preserves the mass on the rows while $T^{(X)}$ preserves it on columns. After application of both, only the global mass is preserved $\sum_{i,j} M^*_{i, j} = \sum_{i, j} M_{i, j}$. This transformation redistributes the weights for documents and keywords without changing the global mass of the system. The matrix $M^*$ will be used for the co-clustering instead of the binary matrix $M$. \section{Clustering Maximizing Information} \subsection{Agglomerative Clustering} An agglomerative clustering algorithm iteratively aggregates items from $X$ into groups, leading to a hard partitioning. The algorithm starts with an initial partitioning where each item of $X$ is alone in its own cluster, i.e. $\mathcal{C}^{(X)} = \{c_i = \{x_i\}\}_{x_i \in X}$. The clusters to merge are selected according to a cost function $D: C \times C \rightarrow \mathbb{R}^+$ which scores cluster pairs. The pair $(c_i, c_j)$ with the lowest cost are merged together to form a new cluster $c_k = c_i \cup c_j$. The agglomeration process take $n-1$ steps for the rows, where $n = |X|$. The cost function affects the algorithm outcome \cite{clustering_agglo_fx, clustering_doc_retrieval}. The selection of a specific cost function depends on the assumption over the cluster shape. For instance, \textit{single linkage} focusses on merging clusters with the smallest gap $C(c_i, c_j) = \sum \min_{x_k \in c_i, x_{\ell} \in c_j} d(x_k, x_{\ell})$, without taking into account the cluster mass, while \textit{complete linkage} focusses on merging clusters with the lowest maximal distance $C(c_i, c_j) = \sum \max_{x_k \in c_i, x_{\ell} \in c_j} d(x_k, x_{\ell})$. It results in two different behaviors: \textit{single linkage} is sensitive to noise, as it would create artificial bridges between clusters, while \textit{complete linkage} is sensitive to outliers, preventing the merge of clusters containing some of them. On the vector space model, the use of distance measures is not satisfactory \cite{feature_red_short_text}, as the information per documents is too short to get an accurate representation. Instead of distance, the dissimilarity between clusters is measured using the divergence between their probability distribution. A partitioning with one large cluster and many singleton clusters made of outliers is similar to a filtering algorithm. A clustering with such an outcome is not desirable as no \textit{true} group exists. A partition must be composed of clusters with equivalent size, without high disparity. Some algorithms naturally take into account the cluster size. For example, in the case of \textit{complete linkage}, where the larger a cluster becomes, the harder it is to merge as the maximal distance to other clusters tends to grow. When using a cluster probability distribution, all items within the clusters are represented by a single prototype independent of the cluster size. To remediate to the fact that cluster prototypes do not include the knowledge of their size, we define our agglomerative algorithm cost as the product between the cluster prototype divergence and the cost relative to their size: \begin{equation} \label{eq:decision_cost} D^*(c_i, c_j) = D(c_i, c_j) \times {\rm Merge}(c_i, c_j; \mathcal{C}) \end{equation} where $D(.)$ is the divergence part, while ${\rm Merge}(.)$ corresponds to the size part; this ensures that quality and quantity are similar across clusters. These two parts will be defined in the following. For simplicity, the \textit{features} are relatively defined to the \textit{samples} considered. When looking at rows, the features represented by columns, while when looking at columns, the relative features correspond to the rows. \subsection{Partitioning Entropy} \subsubsection{Shannon Entropy} The Shannon entropy is a way to measure the number of bits required on average to code an information. The more bits are needed, the more information would transit. For a random variable with discrete values $X=\{x_i\}$ and associated probabilities $Pr(X=x_i) = p_i$, the Shannon entropy is defined as: \begin{equation} \label{marginal_entropy} H(X) = - \sum_{x_i \in X} p_i \log p_i \end{equation} with the $\log$ corresponding to the base $2$ logarithm $\log_2$. \subsubsection{Informative Clustering} We state that a partitioning $\mathcal{C}$ is informative if items are distributed into clusters of equivalent size, maximizing the entropy $H(\mathcal{C})$. Here, the probabilities associated to each cluster is not related to the item frequency, ie $Pr(C=c_i) \neq \sum_{x \in c_i} Pr(X=x)$. Otherwise, the goal would be to isolate highly frequent keywords into individual clusters and gather infrequent keywords on a large cluster, which is by no means more interesting than clustering infrequent keywords alone. Therefore, the cluster contribution is proportional to the number of items $|c_i|$, $Pr(C=c_i) = p_i = \frac{|c_i|}{\sum_{c_j \in \mathcal{C}} |c_j|}$. To make the distinction with entropy using item distribution, we refer to the entropy using item count as the \textit{partition entropy}. For a partitioning into $k$ clusters, $H(\mathcal{C})$ is maximal for $Pr(C=c_i) = \frac{1}{k} \forall i$ with a maximal value of $\log k$. The partitioning with the largest entropy is the one with a single item in each cluster. To compare fairly two partitions at different stages of the agglomerative process regardless the number of clusters, the partition entropy is normalized by its theoretical maximum: \begin{equation} \label{eq:relative_entropy} H_{rel}(\mathcal{C}) = \frac{H(\mathcal{C})}{\log|\mathcal{C}|} \end{equation} which is defined for any partitioning with at least $2$ clusters. The relative entropy takes values in $[0, 1]$, which allows convenient state comparison regardless the number of partitions. \subsubsection{Partitioning Entropy Variation} At the start, each item forms its own cluster, leading to a $H_{rel}(\mathcal{C}) = 1$. The agglomerative process leads to clusters of various sizes which affects the entropy's quality. To keep this value maximal, we study the entropy variation following a merge. For two clusters $c_i$ and $c_j$ merged together, with probability $p_i$ and $p_j$, the new entropy can be expressed using the previous term: \begin{equation} \label{eq:relative_entropy_new} \begin{array}{ll} H_{rel}(\mathcal{C}^{k-1}) &= H_{rel}(\mathcal{C}^k) \frac{\log k}{\log (k-1)} \\ & + \frac{p_i\log p_i + p_j\log p_j}{\log k} - \frac{(p_i + p_j)\log (p_i + p_j)}{\log (k-1)} \\ & = H_{rel}(\mathcal{C}^k) \frac{\log k}{\log (k-1)} + \Delta(p_i, p_j; k) \end{array} \end{equation} where $\mathcal{C}^{k-1}$ corresponds to the new partition with $k-1$ clusters and $\mathcal{C}^{k}$ the previous partition with $c_i$ and $c_j$ unmerged. The total entropy is improved by a factor $\frac{\log k}{\log (k-1)}$ regardless of which clusters are merged. Concerning the merged clusters contribution $\Delta(p_i, p_j; k)$, the behavior can be estimated for large $k$, as the approximation $\log k \approx \log (k-1)$ holds. The merge impact is equivalent to $\Delta(p_i, p_j; k) \approx \frac{1}{\log k}\left(f(p_i) + f(p_j) - f(p_i+p_j)\right)$ where $f(x) = x \log x$. $f$ is negative, concave and monotonically decreasing over the interval $[0, e^{-1}]$, with $e^{-1}=\exp(-1)$ corresponding to the limit of what could be considered as \textit{small} clusters, which is respected for many partitions as $3 e^{-1} > 1$. As a consequence, $f(p_i) + f(p_j) < f(p_i + p_j)$ which leads to an entropy decrease, compensated to some extend by $H_{rel}(\mathcal{C}^k) \frac{\log k}{\log (k-1)}$. \subsubsection{Cluster Size Influence} For large $k$, $\Delta(p_i, p_j) < 0$. To study the size influence, two merges are compared: the merge of $c_i$ and $c_j$ with respective probabilities $p_i$ and $_j$, and the merge of $c_i'$ with $c_j'$ with respective probabilities $\alpha p_i$ and $\alpha p_j$, where $\alpha \in \mathbb{R}^+$. It can be shown that $\Delta(p_i', p_j') = \alpha \Delta(p_i, p_j)$. The cost increases with the size of clusters merged. To maximize the relative partitioning entropy cost over the agglomerative process, small clusters must be preferentially merged to limit the loss, which can be compensated by the former term $H_{rel}(\mathcal{C}^k) \frac{\log k}{\log (k-1)}$ in eq. \ref{eq:relative_entropy_new}. \subsubsection{Minimization Criterion} For any pair of clusters $(c_i, c_j)$, the term $H^{rel}(\mathcal{C}) \frac{\log k}{\log (k-1)}$ in \ref{eq:relative_entropy_new} is the same regardless of which clusters are merged. Two different merges are distinguished by the value of $\Delta(p_i, p_j; k)$. As this term is negative, the goal is to minimize: \begin{equation} \label{eq:end_merge_cost} {\rm Merge}(c_i, c_j; \mathcal{C}) = -\Delta(p_i, p_j; k) \end{equation} \subsection{Content Similarity} We discussed about cluster size in the previous paragraphs. The following describes the evaluation of clusters' content similarity. \subsubsection{Cluster Conditional Probability} Given a cluster $c^{(X)} \in \mathcal{C}^{(X)}$ and a partitioning $\mathcal{C}^{(Y)}$, the distribution of cluster $c^{(X)}$ over $\mathcal{C}^{(Y)}$ is: \begin{equation} \label{eq:cluster_proba_distribution_X} Pr(c^{(Y)} | \mathcal{C}^{(X)}=c^{(X)}) = \frac{\sum_{x_i \in c^{(X)}} \sum_{y_j \in c^{(Y)}} M^*_{i, j}}{\sum_{x_i \in c^{(X)}} \sum_{y_j \in Y} M^*_{i, j}} \end{equation} and for the distribution of cluster $c^{(Y)}$ over $\mathcal{C}^{(X)}$: \begin{equation} \label{eq:cluster_proba_distribution_Y} Pr(c^{(X)} | \mathcal{C}^{(Y)}=c^{(Y)}) = \frac{\sum_{x_i \in c^{(X)}} \sum_{y_j \in c^{(Y)}} M^*_{i, j}}{\sum_{x_i \in X} \sum_{y_j \in c^{(Y)}} M^*_{i, j}} \end{equation} \subsubsection{Cluster Dissimilarity} For two clusters $c_a, c_b \in \mathcal{C}^{(X)}$, the probability distribution over $\mathcal{C}^{(Y)}$ is noted $A$ and $B$ respectively to limit notation symbols, such as $a_i = Pr(c^{(Y)}_i | c^{(X)}_a)$ and $b_i = Pr(c^{(Y)}_i | c^{(X)}_b)$. The Kullback-Leibler ($KL$) divergence is a way to measure the distance between probability distributions $A$ and $B$: \begin{equation} \label{KL} KL(A \| B) = \sum_i a_i \log\frac{a_i}{b_i} \end{equation} The same equation is obtained for $c_a, c_b \in \mathcal{C}^{(Y)}$, with $a_i = Pr(c^{(X)}_i | c^{(Y)}_a)$ in this case. The intuition of the $KL$ divergence is that mass of distribution $B$ must be present where $A$ is. If not, the penalty grows. The $KL$ divergence can be rewritten as $KL(A \| B) = H^*(A, B) - H(A)$ where $H^*(A, B)$ is the cross-entropy, and $H(A)$ the regular entropy. While the entropy $H(A)$ corresponds to the average number of bits exchanged to communicate symbols of $A$ using the most optimal code, the cross-entropy $H^*(A, B)$ corresponds to the average number of bits exchanged to transmit $A$ given the optimal code to transmit $B$. If the two clusters share the same distribution, the code is likely to be similar, and the associated cost low. \subsubsection{Symmetry} There is no order when merging two clusters, as $c_i \cup c_j = c_j \cup c_i$. However, the Kullback-Leibler divergence is not symmetric. Instead, we use the $J$-symmetrized $KL$ divergence, which is defined as: \begin{equation} \label{J_KL} KL^J_{\alpha}(A \| B) = (1 - \alpha)KL(A \| B) + \alpha KL(B \| A) \end{equation} with the balance factor $\alpha = \frac{1}{2}$. The symmetrization ensures that both $A$ and $B$ share the same support probability, which leads to a more discriminative function as both $a_i$ and $b_i$ needs to be non-zero for the same feature $i$. \subsubsection{Minimization Criterion} The cost term takes into account the clusters similarity in eq. \ref{eq:decision_cost} is $D(c_a, c_b) = KL^J(A \| B)$. It measures the divergence between prototypes' distribution according to the clustered features. The $KL^J$ takes values in $\mathbb{R}^+$, where a low value represents a high content similarity between considered clusters. \subsection{Agglomeration Procedure} Given the initial smoothed documents-keywords matrix $M^*$, the algorithm starts by computing $KL^J$ for all possible pairs of clusters in $\mathcal{C}^{(X)}$ and pairs in $\mathcal{C}^{(Y)}$. This lead to two initial divergence matrices $KL^J(\mathcal{C}^{(X)})$ and $KL^J(\mathcal{C}^{(Y)})$. This operation is computationally expensive, as it requires $\mathcal{O}(nm (m + n))$ operations. The merge cost is recomputed at each round, and the total cost is computed for each pair. The pair of clusters from $\mathcal{C}^{(X)}$ or $\mathcal{C}^{(Y)}$ with the lowest cost is selected and merged. The two divergence matrices are updated after the merge operation. If two clusters $c_i, c_j \in \mathcal{C}^{(X)}$ are merged together, all the pairs involving $c_i$ and $c_j$ in $KL^J(\mathcal{C}^{(X)})$ must be recomputed with the new cluster characteristics $c_i \cup c_j$, leading to a matrix with one dimension less. This first update requires $\mathcal{O}(n(t)m(t))$ operations, where $n(t)=|\mathcal{C}^{(X)}|$ and $m(t)=|\mathcal{C}^{(Y)}|$ is the number of row and column clusters left after $t$ merge operations. Concerning $KL^J(\mathcal{C}^{(Y)})$, all the items are affected. Nonetheless, the matrix can easily be updated, by looking at the difference between merged and unmerged state. For two column clusters $c_a$ and $c_b \in \mathcal{C}^{(Y)}$ with distribution over rows $A$ and $B$ respectively, the cost variation is: \begin{equation}\label{eq:delta_reciprocal} \begin{array}{llc} \Delta^{(i, j)}KL(A \| B) & = (a_i + a_j) \log \frac{a_i + a_j}{b_i + b_j} \\ & - \left( a_i \log \frac{a_i}{b_i} + a_j \log \frac{a_j}{b_j} \right) \\ \end{array} \end{equation} where $\Delta^{(i,j)}KL(A\|B)$ corresponds to the non-symmetric $KL$ cost. The new cost for merging $c_a$ with $c_b$ is replaced by $KL^J(c_a, c_b) + \Delta^{(i, j)}KL(A \| B) + \Delta^{(i, j)}KL(A \| B)^{\dagger}$. This updating step requires $m(t)^2$ operations to update all the feature pairs. In total, a step requires $\mathcal{O}(n(t)^2 + m(t)^2)$ operations to select the best pair, and $\mathcal{O}(n(t)m(t) + m(t)^2)$ operations to update the cost pairs $KL^J$ when merging two row clusters. The same reasoning applies when merging two-column clusters by exchanging $n(t)$ with $m(t)$ in the formula. \section{Experimental Setup} \subsection{Datasets} \subsubsection{Scientific Paper Tags} The main motivation for tag co-clustering arose from scientific papers literature. The DBLP dataset \cite{Tang:08KDD} is a citation graph gathering computer science papers, with meta-data such as title, publication year, references, authors, conference/journal, \textit{field of study}, available for a large number of papers. We used the most recent version (v12) for our experiments. The \textit{field of study} is a list of descriptive keywords about the field (e.g. \textit{Cryptography}, \textit{Biology}), the method (\textit{Matrix factorization}), or other related concepts (\textit{Bullwhip effect}) discussed in a paper. Each paper has, on average $10$ descriptive tags. Hopefully, tags are already well pre-processed, and no steaming nor stop-words removal need to be done. The algorithm complexity is more than quadratic, which prevents the scaling to a large database. Documents are sampled to make the clustering possible on a regular machine. A particular tag is selected, and all papers with the tag included are gathered. Then, $5000$ documents are selected at random from this pre-selection. All keywords with less than $5$ occurrences are discarded, which leads to around $1000$ keywords left and a filling rate of $2 \%$ of the binary documents-keywords matrix. \subsubsection{Synthetic checkerboard} The real-world dataset does not contain any label, which prevents the evaluation with objective metrics. We propose to generate a sparse synthetic dataset with clustering structures to test the performance of our model. A synthetic sparse matrix $M$ of size $n_X \times n_Y$ partitioned over $X$ and $Y$ dimensions is constructed the following way. Rows are split into $k_X$ clusters of equal size $\lfloor \frac{n_X}{k_X} \rfloor + \{0, 1\}$. The same regular partitioning is performed on $Y$ with $k_Y$ clusters. The matrix $M$ is filled with $0$ and $1$ according to the partitioning. The \textit{tile} $T(a, b) = \{M^*_{i, j}\}_{ x_i \in c_a^{(X)}, y_j \in c_b^{(Y)}}$ is the intersection between the row and column clusters $c_a^{(X)}$ and $c_b^{(Y)}$. Some of the tiles selected with probability $\alpha \in [0, 1]$ are filled, leaving $(1 - \alpha)$ of the tiles empty, where $\alpha$ is the \textit{global} filling rate. For a tile $T(a, b)$ to fill, the filling rate $\beta_{a, b}$ is selected at random in $[0, \beta]$ with $\beta \in [0, 1]$ the \textit{local} filling rate. For each item $(i, j)$ in tile $(a, b)$ to be filled, its value is $1$ with probability $\beta_{a, b}$ else $0$. The result is a matrix filled with rate $\frac{\alpha \beta}{2}$. In our case, the global and local filling rate are set to $\alpha = \beta = 0.2$ leading to a total filling rate similar to our real-world dataset of $2 \%$ . For all experiments, $n_X = n_Y = 1000$ and $k_X = k_Y$ would be adjusted over the experiments. The resulting matrix looks like a regular grid and would be called, for this reason, the \textit{checkerboard} dataset (see Fig. \ref{fig:smoothing}). The experiments are done for the same $n_X$ and $n_Y$, and identical $k_X$ and $k_Y$. This choice is made to aggregate results over $X$ and $Y$ together, but the performances are not affected by asymmetric choices. \subsection{Monitoring metrics} To evaluate our algorithm, we selected some supervised and unsupervised metrics to evaluate the quality of the partition recovery and estimate cluster quality in the absence of labels. \subsubsection{V-measure} The $V$-measure is a supervised metric comparing the real clusters to the estimated ones using entropy measures. It is analogous to \textit{accuracy} on classification problems. Two sub-measures are first computed: the \textit{homogeneity}, which corresponds to the fact that a good cluster contains a single class, and the \textit{completeness}, which measures how well elements from a given class are grouped. The homogeneity is defined as: \begin{equation}\label{homogeneity} h = 1 - \frac{H(L | K)}{H(L)} \end{equation} with $L$ the real cluster labels and $K$ the hypothetic labels obtained using a clustering. The completeness is defined similarly as: \begin{equation}\label{completeness} c = 1 - \frac{H(K | L)}{H(K)} \end{equation} The $V$-measure is then defined as: \begin{equation}\label{v_measure} V = \frac{(1 + \beta)\times h c}{\beta h + c} \end{equation} where the parameter $\beta \in \mathbb{R}^+$ balances the contribution of each term. For $\beta=0$, it corresponds to the $h$, while $\lim_{\beta \rightarrow \infty} = c$. The values obtained lie within $[0, 1]$, where $1$ is attributed to the best clustering, while $0$ to the worse case. The $V$-measure can also be used to compare two partitioning obtained with different parameters or algorithms, measuring the similarity degree. \paragraph{Random Guess} Suppose $\mathcal{C}$ is a partitioning of items into $k$ clusters of equal size, with $Pr(c) = \frac{1}{k}$. The associated partitioning entropy is $H(\mathcal{C})= \log k$. Be $\mathcal{C}'$ a randomly guessed partitioning with $k$ clusters of equal size too, but filled with items selected at random. The overlap probability between $c \in \mathcal{C}$ and $c' \in \mathcal{C}'$ is $\frac{1}{k^2}$ for all clusters' pairs. Consequently, the joint entropy is $H(\mathcal{C}, \mathcal{C}') = \log k^2 = 2 \log k$, leading to $H(\mathcal{C} | \mathcal{C}') = H(\mathcal{C}' | \mathcal{C}) = \log k$. Completeness and homogeneity are both equal to 0, leading to an undefined $V$-measure. However, when looking at the limit, the value converges to zero. Compared to accuracy measure, where a random guess's accuracy is $\frac{1}{k}$, the $V$-measure is more discriminative. \subsubsection{Limited Partitioning Entropy} At the start, the partitioning entropy defined in eq. \ref{eq:relative_entropy} is maximal. However, the clustering is non-informative as only singleton clusters exist. Instead, knowing that final clusters would have a critical size with more than $r$ elements, smaller clusters' contribution can be discarded, considering them as \textit{outliers}. The restricted relative partitioning entropy is then defined as: \begin{equation} \label{eq:relative_entropy_restricted} H^*_{rel}(\mathcal{C}; r) = \frac{- \sum_{c \in \mathcal{C} \wedge |c| > r} p(c)\log p(c)}{\log |\mathcal{C}|} \end{equation} At initialization, the value is $0$ as no cluster of sufficient size exists for $r > 1$. This value is still bounded between $[0, 1]$ and enables to track clusters creation. This measure allows to evaluate the partitioning distribution without considering cluster content. \subsubsection{Mutual Information} When monitoring the cluster's content, the information variations are monitored. In this case, the entropy is computed using the sample probabilities, defined in equations \ref{eq:cluster_proba_distribution_X} and \ref{eq:cluster_proba_distribution_Y}. The \textit{mutual information} corresponds to the information shared between $X$ and $Y$. This measure is defined as: \begin{equation} \label{mutual_info} I(X, Y) = H(X) + H(Y) - H(X, Y) \end{equation} It corresponds to the gain of coding $X$ with $Y$, i.e. the amount of redundancy between the two variables. This value is bounded by $0$ (independent variables) and $\min(H(X), H(Y))$ (correlated variables). We would monitor the mutual information between partitioning $I(\mathcal{C}^{(X)},\mathcal{C}^{(Y)})$. As the number of clusters decrease over time, this value would decrease due to information loss during the compression. \subsection{Comparative Algorithms} We proposed to compare our algorithm to the co-clustering algorithm presented in \cite{Dhillon01co-clusteringdocuments}, which relies on spectral decomposition. First, two diagonal matrices $D_{1}$ and $D_2$ are obtained from $M$, where $D_{1: i,i} = \sum_{j=1}^m M_{i, j}$ and $D_{2: j,j} = \sum_{i=1}^n M_{i, j}$. Then, the normalized matrix $M_n = D_1^{-1/2} M D_2^{-1/2}$ is decomposed using singular value decomposition such as $M_n = U S V^T$. The vectors $D_1^{-1/2}U$ and $D_2^{-1/2} V$ are concatenated to form the matrix $Z$. The algorithm finishes by performing a $k$-means clustering on the $\ell = \lceil \log_2 k\rceil$ main dimensions, omitting the first main dimension. \pagebreak \section{Experimental Results} \subsection{Smoothing Effect} \begin{figure} \centering \includegraphics[width=\columnwidth]{./img/check_board_transfo_02_n_1000_k_15.png} \caption{Matrix smoothing for $n_X=n_Y=1000$ and $k_X=k_Y=15$, ie around $67$ points per cluster. The global filling ratio is $\alpha=0.2$ and the local filling ratio is $\beta=0.2$. Left: binary matrix, right: smoothed matrix.} \label{fig:smoothing} \end{figure} The smoothing proposed enables to switch from binary values to real values by redistributing the weights. A visual example is presented in Fig \ref{fig:smoothing}. The filled tiles are identifiable on the binary matrix. For the tiles with low $\beta_{a, b}$, the boundaries are hard to identify. On the smoothed matrix, the weights are completely redistributed leading to the visual identification of tiles, even the ones that were not filled at all. All items belonging to the same clusters tend to have a more similar feature vector. The information is of lower intensity locally but is better distributed across the different features, even on tiles that were not filled. \subsection{Size Dependent Cost} This experiment compares the composite cost defined in eq. \ref{eq:decision_cost} to the version where only content similarity obtained using $KL^J$ cost is taken into account. For this purpose, we compared for several numbers of cluster $k$ the maximal $V$-measure averaged over $5$ independent trials for each $k$. We gathered the number of clusters left $\hat{k}$ for the maximal value of $V$. We did the same by extracting the maximal restricted relative entropy, removing clusters of size smaller or equal to $1$, and extracting the corresponding $\hat{k}$. \begin{figure} \centering \includegraphics[width=\columnwidth]{./img/vmax_kerror_04_02_n1000_abs.png} \caption{Best $v$-measure and average absolute error for corresponding $k$. Blue rounds correspond to the normal setup with co-clustering and weighting according to $KL^J$ cost and cluster distribution entropy $H(\mathcal{C})$. Orange triangles correspond to the co-clustering setup without taking into account cluster distribution. Red squares correspond to the double weighting approach but rows and columns are clustered independently. Each point corresponds to the average for $5$ independent trials. } \label{fig:v_measure_setup_1} \end{figure} The results are presented in Fig. \ref{fig:v_measure_setup_1}, with the composite cost denoted $KL \times H(\mathcal{C})$ and the simple cost $KL$. As a general remark, for all setups, it is easier to cluster many clusters with sufficient size. For very few clusters, the accuracy quickly decreases. As the global filling rate is $\alpha=0.2$, on average $2$ tiles are filled over $10$. Due to randomness, a single one or none could be filled, leading to less information for clustering. For a large number of partition, a cluster is well defined in the sense that enough tile are filled. The problem of insufficient information occurs at the sample level. For a row sample of size $n$ and $k$ feature partitioning, there are $\frac{n}{k}$ slot for a given feature cluster. As the local filling rate is $\beta_{a, b} \leq 0.2$, the probability that none of the slot are filled grows with $k$. This effect is nonetheless less disturbing than the former as redundancy exists. The $V$-measure of the composite cost is always higher than for the simple cost setup. The accuracy of $KL$ quickly drops for large $k$ with smaller cluster sizes. The absolute $k$ deviation $\mathbb{E}(|k - \hat{k}|)$ of the composite cost is relatively close from the optimal, with a consistent error unless for very small cluster size, while the error for the simple cost is too large to fit in the figure. \begin{figure} \centering \includegraphics[width=\columnwidth]{./img/emax_kerror_04_02_n1000_abs_15.png} \caption{Left: Best $H(\mathcal{C})$ with cluster of size lower or equal to $1$ removed. Right: average absolute error of the corresponding $\hat{k}$. Same color code and setup as \ref{fig:v_measure_setup_1}. Blue rounds and red circles overlap on the left sub-figure. } \label{fig:entropy_setup_1} \end{figure} Looking at the maximal relative partitioning entropy in Fig. \ref{fig:entropy_setup_1}, the composite cost leads to very good cluster distributions for any $k$, while the simple cost is $0.2$ points lower for small number of clusters and very low for larger values. On the right side of Fig. \ref{fig:entropy_setup_1}, the $\hat{k}$ obtained with the composite cost is close to the exact value even for large $k$. This means that the number of clusters obtained when stopping the agglomeration procedure with the partitioning entropy criterion is close from the true initial cluster numbers for all cluster sizes. When using the simple cost, clusters number is far from the true number of cluster. In both case, the entropy stopping criterion leads to a smaller error over the number of estimated clusters. \subsection{Co-Clustering vs Independent Clustering} One of the initial hypothesis concerns the synergy between joint reduction. We compare the co-clustering setup to the independent setup, where the partitioning $\mathcal{C}^{(X)}$ is obtained using the uncompressed features $Y$, as well as the partitioning $\mathcal{C}^{(Y)}$ is obtained using the unaggregated rows $X$. This setup is denoted \textit{Indep} in Fig. \ref{fig:v_measure_setup_1} and \ref{fig:entropy_setup_1}. The results obtained with the independent clustering are similar to the co-clustering but with a lower $v$-measure for a large number of clusters $k$. The obtained $\hat{k}$ from the $v$-measure are close to the co-clustering ones. As far as shape is concerned, independent clustering performs as well as the co-clustering, and the $\hat{k}$ obtained are relatively similar. The co-clustering advantage is limited for large clusters / small $k$ and becomes more interesting when uncertainty grows with smaller size clusters for large $k$. \subsection{Comparison to Alternative Algorithms} We compare our algorithm to spectral co-clustering presented in \cite{Dhillon01co-clusteringdocuments}. The algorithm needs as input the target number of clusters to search for. When comparing the agglomerative algorithm with the spectral algorithm, the spectral algorithm is run with the exact $k$ provided, compared to the partitioning obtained with the agglomerative algorithm with $k$ remaining clusters. The $V$-measure and the relative cluster partitioning entropy $H_{rel}^*(\mathcal{C}; 1)$ are extracted from these two partitioning. The results are presented in Fig. \ref{fig:spectral_vs_hierarchical}. \begin{figure} \centering \includegraphics[width=\columnwidth]{./img/spectral_vs_KL_04_02_n1000_15_fair.png} \caption{Comparative results between Spectral co-clustering and Agglomerative clustering. On the right, maximal $V$-measure obtained for } \label{fig:spectral_vs_hierarchical} \end{figure} The spectral algorithm results are lower than the one obtained for the agglomerative approach. However, the shape of the clusters obtained are equivalent. The spectral approach is quite robust in general, but the sparsity level affects the results. With a higher filling rate ($\alpha=0.4$), the spectral results get closer to the agglomerative one. We also tested with DBSCAN, which has been used in some papers. As it is impossible to select the wished number of clusters, and because the results were lower than spectral decomposition, the results are not presented. Nonetheless, the smoothed matrix's use improved the partitioning, allowing the algorithm to discover more clusters than with the regular binary matrix. \subsection{Textual Results} The initial goal was to cluster tags associated with scientific papers to identify topics. In the dataset used, there is no high-level classification or paper grouping to evaluate our clustering. Despite the lack of objectivity, we present the results on two subsets of papers, obtained for the \textit{Payment} field of study, and the second for \textit{Biometry}. We take advantage of the hierarchical form to present the results using a dendrogram. Around $15$ clusters are left unmerged, and the three most frequent keywords are displayed for analysis. For the two, the relative partitioning entropy was around $H(\mathcal{C})=0.95$ for keywords. \paragraph{Payment} \begin{figure} \centering \includegraphics[width=\columnwidth]{./img/dengrogam_test_payment_03.png} \caption{Dendrogram for \textit{Payment} field of study.} \label{fig:dendrogram_payment} \end{figure} Fig. \ref{fig:dendrogram_payment} corresponds to the clustering of keywords co-occurring with the \textit{Payment} tag. Three high level clusters are identified. The one on the left corresponds to things related to \textit{economics}. The right one corresponds to what could be considered as the \textit{core} of the payment field, oriented toward users, with the new payment methods (\textit{Cryptocurrency}, \textit{Mobile payment}) and intricated topics (\textit{Computer security}, \textit{Marketing} and \textit{Advertising}). The bottom cluster corresponds to the medium or technology used in the payment but is not specific. For instance, \textit{Artificial intelligence} is used in payment systems for fraud detection or biometric authentication, but it is not specific to payment. Surprisingly, the keyword \textit{Payment} is located on the bottom cluster, near \textit{Cash} and \textit{Crowdsourcing}, which seems conceptually incorrect. This is due partially to our sampling method, where all documents with keywords \textit{Payment} were selected. As it co-occurs with all keywords, there is no way to identify true relationships. \textit{Payment} is located on a cluster were the other keywords are related to \textit{Crowds}, with additional keywords such as \textit{Reputation}, \textit{Social network}, \textit{Audit} and \textit{Crowdsensing}. This artefact is not limited to the selected keywords but to the most frequent keywords. A second example is \textit{Computer science} on the right, in a cluster related to the \textit{Internet}, with additional keywords like the \textit{World Wide Web}, \textit{Mobile device}, \textit{Service provider} and \textit{Mobile computing}. \paragraph{Biometry} \begin{figure} \centering \includegraphics[width=\columnwidth]{./img/dengrogam_test_biometry_02.png} \caption{Dendrogram for \textit{Biometrics} field of study. } \label{fig:dendrogram_biometry} \end{figure} The second partitioning uses the \textit{Biometrics} tag as a reference. The resulting dendrogram is presented in Fig. \ref{fig:dendrogram_biometry}. Two large clusters are identified. The main on the left gathered keywords about biometric methods and algorithms to extract a digital identity. It is subdivided into two subgroups. The top one gathered keywords related to computer-vision, with \textit{Image processing}, gait and face analysis. The bottom one corresponds to the other methods, with fingerprint, \textit{Speaker recognition}/\textit{verification}. The cluster with \textit{Biometrics}, \textit{Computer science} and \textit{Speech recognition} corresponds to an artefact gathering highly frequent keywords together. The right cluster corresponds to the security part, with \textit{Cryptography}, \textit{Password}, \textit{Authentication} and others. \section{Discussions} \subsection{Ending Criterion} The checkerboard experiments were evaluated, knowing the number of clusters. In an unsupervised setup, this knowledge is often unavailable. To select the cluster number, one has to look at a specific criterion indicating if the partitioning is satisfying. For instance, the algorithm $X$-means \cite{Pelleg00x-means} is a divisive algorithm based on $k$-means which successively splits the existing clusters. The splitting decision is based on the split's likelihood, assuming the data corresponds to a Gaussian mixture. For more general clustering algorithm, the silhouette coefficient, measuring the distance to the nearest cluster versus the radius of the cluster. On our type of data, the silhouette is not suitable as cluster are not well separated. The \textit{goodness} criterion of the algorithm must be in accordance to the goal achieved by the algorithm. Reminding our cost definition in \ref{eq:decision_cost}, it is the product between \textit{cluster size} and \textit{content} related costs. The first part of the answer to this problem is to look at the restricted relative partitioning entropy defined in \ref{eq:relative_entropy_restricted}, with small clusters of size $1$ or less removed. In Fig. \ref{fig:entropy_setup_1}, $H_{rel}(\mathcal{C}; 2)$ is already a good indicator of when clusters are sufficiently aggregated. However, this is a particular case where all clusters have the same size, leading to a particular configuration where $H_{rel}$ is maximal. In a more general configuration, there is no particular reason for clusters of exactly the same size. The second cost part takes into account content. On the information theory-based work of \cite{Dhillon03InformationCoclustering}, a good clustering is defined as minimizing the quantity $I(X, Y) - I(\mathcal{C}^{(X)}, \mathcal{C}^{(Y)})$ for a given number of row and column clusters. The agglomeration of clusters is a form of compression which mechanically reduces the information available. The restricted relative entropy is maximal towards the end of the agglomeration process, while the information is maximal at the beginning and minimal at the end. A good compromise between the two is to look for the value for which the product of $I(\mathcal{C}^{(X)}, \mathcal{C}^{(Y)})$ and $H(\mathcal{C}^{(X)})$ or $H(\mathcal{C}^{(Y)})$ is maximal: \begin{equation} \label{eq:ending_criterion} k^*_X = \arg_{k_X = |\mathcal{C}|} \max H_{rel}(\mathcal{C}^{(X)}; r) \times I(\mathcal{C}^{X}, \mathcal{C}^{Y}) \end{equation} $X$'s best partitioning is not necessarily simultaneous with that of $Y$ because the actual number of clusters may be different. The co-clustering only exploit synergies to find clusters more accurately. In general, the partitioning with the lowest number of dimensions would be merged more frequently until reaching a size comparable to its feature size. As a rough guide, for $k$ features, the maximum entropy is $\log k$. The cost of $KL^J$ is not limited by an upper bound, but the higher the number of features, the higher the cost will be because the probability of $a_i=0 \neq b_i$ is higher in such a configuration. With a higher cost, the clustering will preferably select the cluster pairs with the smallest number of features. This criterion was tested on the checkerboard dataset. The estimated $\hat{k}$ were very close to the expected one, with an average absolute deviation close to $1$. This criterion was used to build the dendrogram, where the estimated cluster number was between $15 \sim 20$ clusters depending on the main selected keyword. \subsection{Model Limitations} The checkerboard model differs from a documents-keywords matrix obtained from tag on two majors points. The first difference concerns distribution. Tags follow a Zipf's law, which is not modeled here, as all columns have on average the same strength. Nonetheless, the unbalanced distribution is corrected by the matrix smoothing protocol, which decreases the weight of these frequent keywords to less frequent one. The second difference is the hierarchical division of keywords. The associated tags range from very broad domains (\textit{Chemistry}, \textit{Mathematics}), to fields (\textit{Inorganic chemistry}, \textit{Databases}), to specialities and other lower levels. The checkerboard model is made of independent clusters which are not hierarchicaly organized. Nonetheless, due to the scaling limitation of the proposed algorithm, the restriction to around $5000$ documents and $1000$ keywords limit the visibility of such organizations. \section{Conclusion} In this paper, we addressed the problem of tag clustering, where the tag amount per document is limited. To this purpose, using the correlation between tags and keywords, a method to enhance context without the use of an external database or model was proposed. With the assumption that a clustering is informative if the partition entropy is large, we proposed an agglomerative co-clustering algorithm taking into account the content as well as the cluster size. The algorithm showed good recovery performance on synthetic datasets with the same sparsity level. It showed conceptually correct clustering results on scientific paper tags, up to highly frequent keywords where no discriminative relationship could be found. The algorithm's complexity is polynomial but more than quadratic, which restricts its usage on a small dataset. Some improvement can be made by splitting the dataset into independent parts or finding cost approximations. Nonetheless, the idea of building groups of equivalent size could be mixed with other agglomerative measures to include distant items to their closest cluster. \bibliographystyle{unsrtnat}
{'timestamp': '2021-10-22T02:43:12', 'yymm': '2110', 'arxiv_id': '2110.11079', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.11079'}
arxiv
\section{Introduction} \subsection{Motivation} Nowadays, we are witnessing revolutionary changes in UAV technology resulting in redesigning the business models and creating a new operating environment in a variety of industries, from entertainment and meditation \cite{la2019drones} to assistance in territory monitoring \cite{yatskin2017principles}. At an early date, customers from a wide range of industries will witness the first impact of UAVs in various areas, from delivery services to power line inspection. UAV-based solutions are most relevant for industries that require both mobility and high-quality information. The integration of such systems into the daily workflow can provide significant advantages when implementing large capital construction projects, infrastructure management, agriculture, and 3D surface deformation \cite{braley2018griddrones}. Conducting a stocktaking of industrial warehouses in a fully autonomous mode is a highly promising and, at the same time, challenging task. As a rule, such a warehouse is equipped with a large number of racks with a height of 10-12 m. Such a height makes it impossible to use a robotic arm for this task. Each pallet and its place number is marked with a unique identifier, for example, a barcode, quick response (QR) code, or a Radio Frequency IDentification (RFID), while the barcode is the most common type of identification. At the moment, most of the stocktaking of such warehouses is carried out manually \cite{wawrla2019applications}. The pallets are removed from the shelves, scanned, and then put back during the inventory process. This manual operation takes a tremendous amount of time and leads to warehouse downtime of up to 4 days for an average warehouse of 10,000 m$^2$ \cite{fernandez2019towards}. An autonomous UAV with an indoor localization system could be an ideal solution to this problem. However, the main problem is the precise positioning of the UAV within the narrow aisles between the racks. To overcome this problem, we developed a heterogeneous robotic system consisting of UAV and UGV. The proposed approach makes it possible to install all the necessary localization and navigation equipment on two robots, as opposed to motion capture systems, which require additional active infrastructure, which is impossible for warehouses. In addition, the UAV flight time is limited to 25 minutes, during which, on average, it is possible to carry out an inventory of no more than 200 m$^2$ of the warehouse. Therefore, we decided to use our mobile platform for recharging the UAV through contact pads. \begin{figure}[!t] \centering \includegraphics[width=0.98\linewidth]{figures/unity.jpg} \caption{WaveVR interface.} \label{fig:main} \vspace{-1em} \end{figure} We have developed a heterogeneous robotic system that can localize and navigate in the indoor warehouse environment autonomously \cite{kalinov2019high, kalinov2020warevision, kalinov2021impedance}. The system copes with its task and makes an inventory with photos, uploading all the information into a database and building a product location map. In some cases, the data from the autonomous inventory (recognition result, coordinates, photo) is insufficient, and a more detailed inspection of a particular pallet is needed. This type of inspection is not available offline, but sometimes it is required promptly and remotely. Therefore, it is essential to have an intuitive human-computer interface to interact with the autonomous system with clear feedback, so that even warehouse workers inexperienced in robot control can easily handle it. Such an interface should include two operation modes for the system: automatic and manual. The use of virtual reality can provide a comfortable perception of the environment around the robot and increase the level of involvement and realism during teleoperation compared to the regular screen interface. The proposed WareVR interface allows regular warehouse workers without experience in robotics to control the heterogeneous robotic system in the VR application, which provides visualization of the heterogeneous robotic system in the digital twin of the warehouse. Besides, our interface allows stream video from the UAV camera into the virtual environment for additional visual feedback from the real environment. The user can operate the robotic system with velocity control using the hand-held VR controller. \subsection{Related works} In the evolution of the Human-Computer Interaction (HCI) discipline, recently, special attention is paid to human-drone interaction (HDI). Drones are becoming more and more diffused, being used with different purposes in various control modes, e.g., automatic, manual, shared-autonomy, when the user can execute some operations while the autonomous system works. Silvia Mirri et al. \cite{mirri2019human} presented a thorough overview of the latest papers in HDI. One of the main problems with almost all control interfaces is the necessary experience in drone control for their use in challenging tasks, e.g., indoor operation \cite{erat2018drone}, risky operation \cite{aleotti2017detection}, inspection \cite{irizarry2012usability}, etc. One of the most common approaches to remote control of drones is the use of computer vision methods. In several works \cite{naseer2013followme, mohaimenianpour2018hands}, the operator implemented UAV control using an on-board camera (RGB camera, Kinect sensor) that recognizes face and hand gestures. However, this approach cannot be applied if the operator is out of the UAV camera field of view. Nowadays, one of the most prospective approaches for remote robot control is teleoperation via physical sensor-based (e.g., motion capture or electromyography) interface \cite{miehlbradt2018data}, \cite{wu2019teleoperation}. Thus, Rognon et al. \cite{rognon2018flyjacket} developed FlyJacket, a soft exoskeleton for UAV control by body motion. The exoskeleton contains a motion-tracking device to detect body movements and a VR headset to provide visual feedback. However, such interfaces can be bulky and complicated for deploying and using quickly and require preliminary operator training. Besides, the exoskeleton as a concept for robot control significantly limits the motion of the operator. Virtual reality user interfaces provide the operator with more immersive interaction with robots. Thomason et al. \cite{thomason2019comparison} developed a virtual reality interface for safe drone navigation in a complex environment. The teleoperation system provides the user with environment-adaptive viewpoints in real-time to maximize visibility. In \cite{vempati2019virtual}, it was proposed a VR interface to control an autonomous UAV for spray painting on complex surfaces. Using a virtual spray gun, it allows the user to move around the target surface in a virtual environment and paint at desired locations. Patterson et al. \cite{paterson2019improving} presented an open-source platform for 3D aerial path planning in VR. The introduced VR interface has advantages in both usability and safety over manual interfaces and can significantly reduce path planning time compared to a 2D touchscreen interface. Yashin et al. \cite{aerovr2019} proposed a VR-based teleoperation system for an aerial manipulator. The developed system consists of a VR application with a digital twin of a drone and a wearable control interface represented by VR trackers worn on the operator's arm and a tracking glove with vibrotactile feedback to control the position of the robotic arm mounted on the UAV. Most of the VR teleoperation systems propose direct robot control via VR controllers or wearable interfaces. However, in our case, it is needed a semi-autonomous interface that allows choosing the operation mode of the autonomous robotic system and, if necessary, providing manual operation mode. These needs can be met with an intuitive graphical user interface (GUI) in VR. \begin{figure*}[!h \centering \includegraphics[width=0.95\textwidth]{figures/pictures_2.png} \vspace{-1em} \caption{The overall architecture of the developed system. The key equipment of the heterogeneous robot, server information flow using ROS, and operator layers are presented in the form of block diagrams. }~\label{fig:scheme} \vspace{-1em} \end{figure*} \section{System Overview} Fig. \ref{fig:scheme} shows the overall architecture of the developed system, which includes the key equipment of the heterogeneous robot, Robot Operating System (ROS) framework, Unity, and the operator workplace. We used the HTC VIVE headset to represent a virtual environment from the Unity application and the HTC VIVE controller to track user hand position to control the system. The desktop computer with installed ROS and Unity is located in the operator's workspace, the mobile platform is controlled by an on-board computer based on the Intel NUC with Core i7 processor, the on-board computer of the UAV is Nvidia Jetson Nano, which directly interacts with the Pixhawk flight controller. All three computers operate in multi-master mode in ROS to ensure reliable information transfer within the one local Wi-Fi network in the warehouse. The connection between ROS and Unity application is based on the ROS-Unity Communication Package (ROS$\#$). \subsection{Operation principles of heterogeneous robotic system} The main objective of the UGV is to determine its coordinates relative to the surrounding objects in the warehouse and accurately calculate the position of each pallet. To do this, we use modern approaches for robot localization and navigation. The robot uses a simultaneous localization and mapping (SLAM) algorithm based on graph-based approaches \cite{Hess2016} to determine its location in space. For map building of the surveyed area, the UGV employs a Light Detection and Ranging device (LIDAR). To detect and recognize UAV position relative to the UGV, we installed the camera on the ground robot and two concentric patterns of active infrared (IR) markers on the UAV. In our setup, we employ a global shutter ImagingSource camera with a resolution of 2448x2048 and a lens with 137.9$^\circ$ field of view (FoV). Besides, we use an IR-passing 950 nm filter to obscure all the light (e.g., ceiling backlight) except for IR markers. All the key hardware components and communication between them are represented in Fig. \ref{fig:scheme}. The detailed explanation of the system setup is described in our previous work \cite{kalinov2019high}. \subsection{Barcode mapping} \label{mapping} For acquiring augmented UAV localization, we obtain the exact coordinates of the barcode relatively to the UAV and verify them by a laser scanner, which makes it possible to use it as an additional source of information. At the first stage, we get data from the convolutional neural network (CNN) U-Net on the possible position of barcodes in the image frame \cite{kalinov2020warevision}. Based on the position of barcodes, we make a preliminary barcode map and generate our preliminary global flight path. Then the UAV starts scanning along this path. The area where the barcode was detected and verified by the laser scanner is assigned a ``verified barcode'' status and gets into the barcode database, after which the drone flies to the next waypoint. If the laser scanner cannot read the barcode, in this case, our algorithm removes this waypoint from the path and assigns the next waypoint to the drone \cite{kalinov2020warevision}. In addition, during the flight, we obtain the linear dimensions of the boxes with an accuracy of 3 cm using the distance to the boxes and detecting their contours by the standard OpenCV functions. This accuracy allows to classify boxes by typical sizes and use them for a digital twin recreation \autoref{twin}. The recognized barcodes are linked to the boxes according to their position. The result of this work is an accurate map of recognized barcodes and goods in a warehouse (Fig. \ref{fig:marginfig}). \begin{figure}[h] \centering \includegraphics[width=0.9\linewidth]{figures/barcodemap.png} \caption{The accurate map of barcodes in RVIZ environment. The green boxes represent verified barcodes. The red box represents false-positive detected barcode with CNN.}~\label{fig:marginfig} \end{figure} \subsection{VR system} We have developed a VR interface based on the Unity game engine, which allows monitoring and managing the robot inventory process directly in real time. The VR setup includes HTC Vive Pro base stations, head-mounted display (HMD), and HTC VIVE controller for tracking the position of the user’s hand in VR. The 3D graphical user interface (GUI) developed by us includes a panel for control of a full inventory process, as well as a manual operation of the UAV, one screen for providing visual feedback from the drone camera, and another for representing a digital twin of the warehouse (Fig. \ref{fig:main}). The control board consists of three panels: a panel for choosing the operational mode, a panel for the input of pallet place number, and a panel for the manual UAV control. \section{VR Interactive Interface} \subsection{A digital twin of the warehouse} \label{twin} The left screen on the GUI is used to visualize the target warehouse in the VR environment (Fig. \ref{fig:main}). Initially, the digital twin of the warehouse is generated based on the given input parameters. This list includes a 2D map of the warehouse walls, the ceiling height, the number of racks and their initial positions, the distance between racks, the number of tiers and sections in each rack, the size of the rack cells (pallet places), and a list of typical boxes with dimensions. Then we place the heterogeneous robot in our model of the digital twin. Filling the shelves with pallets and boxes occurs based on the created map of detected and verified barcodes during the stocktaking (\autoref{mapping}). When the UAV detects a barcode on the real goods, a virtual pallet is filled with a box in the digital warehouse only after barcode verification. In addition, at the time of verification, the UAV takes a photo of the pallet and links it in the database with the scanned barcode. Thus, we reconstruct a simplified model of the inspected warehouse (Fig. \ref{fig:wareVR}). \subsection{Safe operating modes} Although one of the advantages of the proposed system is the possibility of remote use, which eliminates the risk of the drone operation near the operator, nevertheless, other employees may work in the warehouse during this time. Therefore, from the point of view of human-robot interaction, it is essential to describe the modes of safe operation. We utilize all the data used to create the digital twin (2D map of the warehouse walls, the ceiling height, the initial positions of the racks, etc.) in the robot control system. Thus, we generate a 3D map of the space with the zones where the drone can fly. This is done to significantly reduce the risk of the drone collision with the racks. It is also important to note that the drone is always located in the cylindrical area above the mobile robot. In case of any connection loss or an abnormal situation, the drone will provide a soft landing on the mobile robot \cite{kalinov2021impedance}. \begin{figure}[h] \centering \includegraphics[width=0.95\linewidth]{figures/vr_scene.png} \caption{Visualization of the UAV flight above the UGV near one rack in the warehouse digital twin. In our user study, we used pallet highlighting for scanning as follows: the green box indicates a scanned pallet, the red box indicates a pallet that requires scanning. }~\label{fig:wareVR} \end{figure} \subsection{Operational modes} The control panel includes four operational modes of stocktaking for the operator: \begin{itemize \item \textbf{Full stocktaking}. During this mode, the system works fully automated and conducts stocktaking of the whole warehouse. In this mode, the operator supervises the system and visually checks the conditions of the pallets (damaged, opened, etc.) using a video stream from the UAV camera. At any time, the operator could pause the stocktaking to zoom in the image from the UAV and check the pallet condition and then give a command to continue stocktaking in automatic mode or abort stocktaking. \item \textbf{Partial stocktaking}. During this mode, the system works fully automated and conducts stocktaking of a selected part of the warehouse. The operator supervises the system and could check the pallet as in ``Full stocktaking mode''. \item \textbf{Tag search}. The system works fully automated during this mode and searches a defined tag using the information from the previous stocktaking as the initial parameters. If the pallet was not found in its past location, the system automatically gradually increases the search area within the same alley. If no pallet is found in this alley upon completion of the search, the system offers to select another alley for searching or switch to ``Visual inspection mode''. \item \textbf{Visual inspection}. During this mode, the system is controlled manually by the operator. The first step for the operator is to enter the target location for the inspection. The robotic system autonomously arrives at the desired row, and the drone takes off at the desired height. Then the operator can guide the drone manually closer to the rack at different angles and adjust the view. \end{itemize} \subsection{UAV teleoperation} \label{teleop} A drone control panel allows the user to operate the UAV in manual mode. It comprises four buttons for the translational positioning of a drone along $X$ (left, right) and $Z$ (up, down) axes. Besides, there is an opportunity to zoom in and out the distance between the UAV and the rack with a slider (movement along the $Y$-axis). All buttons are selected with the HTC VIVE controller. For velocity control of the UAV without panel buttons, we track the position of the HTC VIVE controller by HTC VIVE base stations. To control the 4 DoF of the UAV, we use four inputs obtained from the HTC VIVE controller ($x_c$, $y_c$, $z_c$, yaw) to calculate the velocities of the UAV along the three axes as well as the target UAV yaw angle. The controlled UAV responds to changes in the position of the controller in the following way. If the HTC VIVE controller is moved horizontally (forward, backward, left, or right), the drone is commanded to change its velocity in the horizontal plane proportionally to the controller displacement. Controlling the movement along the $Z$-axis works the same way. Besides, We used the trackpad button for drone rotation in the yaw direction. \subsection{Visual Feedback} The right screen on the GUI in the VR application is used for providing visual feedback during the work of the robotic system from the inspection place. A video from the UAV camera is streaming in real-time to the predefined IP address in the local network during the inventory process. Unity application displays this video stream from the URL source to the interface screen. \begin{comment} \begin{figure*}[!ht] \begin{center} \subfigure[\label{RNN}Regular NN architecture.]{ \includegraphics[width=0.3\linewidth]{figures/lab.png}} \subfigure[\label{CNN}CNN architecture.]{ \includegraphics[width=0.29\linewidth]{figures/barcodemap.png}} \subfigure[\label{CNN}CNN architecture.]{ \includegraphics[width=0.3\linewidth]{figures/unity_env.png}} \caption{Deep learning architectures.} \end{center} \label{ARCH} \end{figure*} \end{comment} \section{User Study} We conducted an experiment with UAV control in a simulated environment using VR and desktop applications to evaluate the convenience of control modes and identify possible emergencies with the real system. The purpose of the user study was to evaluate the effectiveness of the proposed approach of the manual UAV control through the developed VR interface in comparison with one of the most popular methods of UAV control using First Person View (FPV) glasses and a remote controller (RC) \cite{grijalva2019landmark}. Since usually only the image frame from the drone camera is transmitted in FPV glasses, in this mode, it is impossible to use the advantages of the VR interface, e.g., 360$^\circ$ view of the environment through the head rotation. Therefore, we simulated this control mode by streaming the image from the drone camera from the digital twin to the desktop monitor. Thereby, we would like to compare desktop and VR-based applications to prove the effectiveness of using the VR mode in our work. \subsection{Experimental Description} For the user study, the following scenario was developed. The system was launched in the ``visual inspection'' mode. The participant had to find 5 pallets and fly up to them, thereby making an inventory. All pallets that the user had to scan during the experiment, we highlighted in a red box. After scanning, the highlight color changed to green (Fig. \ref{fig:wareVR}). To simulate a flight in FPV mode, we broadcast the video stream from the drone camera from the digital environment to the desktop display (Fig. \ref{fig:participants} (a)). Flight control was carried out using two thumbsticks on the Logitech Gamepad F710 (the left thumbstick for the torque control and yaw rotation, the right one for movement in the horizontal direction: forward, backward, left, or right). This setup was chosen to simulate the most common drone control using an RC. No other camera views were available in this mode, the only video from the drone camera, as in normal control through FPV glasses. In the VR scenario with the developed interface, the UAV was controlled using the HTC VIVE controller (\autoref{teleop}). The trigger button was used to move the UAV to the holding position mode allowing the user to rotate the UAV in the yaw direction only. The subjects controlled the quadcopter from the third-person view and could rotate the head to look around the space (Fig. \ref{fig:participants} (b)). Besides, an additional window with the drone camera view was available for the user. Before the experiment, each subject had short training to get acquainted with the control procedure. After completing the tasks using both modes, we asked participants to respond to a 9-question survey using a seven-point Likert scale. The survey results are presented in Fig. \ref{fig:Likert}. \begin{figure}[h] \begin{center} \subfigure[Desktop mode.]{ \includegraphics[width=0.9\linewidth]{figures/user1.jpg}} \subfigure[VR mode.]{ \includegraphics[width=0.9\linewidth]{figures/user2.jpg}} \caption{Overview of the experiment process.}\label{fig:participants} \end{center} \vspace{-2em} \end{figure} \begin{comment} \begin{figure}[h] \centering \includegraphics[width=0.93\linewidth]{figures/participants.jpg} \caption{Overview of the experiment process: a) Desktop mode, b) VR mode. } \label{fig:participants} \end{figure} \end{comment} \begin{figure*}[!h] \centering \includegraphics[width=0.99\textwidth]{figures/likert_bp.png} \caption{Evaluation of the participant’s experience for both control methods in the form of a 7-point Likert scale (1 = completely disagree, 7 = completely agree). Means and standard deviations (SD) are presented. Crosses mark mean values.} \label{fig:Likert} \end{figure*} \subsection{Participants} In total, 15 subjects took part in the experiment (3 women and 12 men). Participants were students with a background in mechanical engineering, computer science, and robotics. The average participant age was 24.4 ($SD = 2.4$), with a range of 21–31. Our sample of participants included both novice users and experienced users at drone piloting. In total, 3 participants had never interacted with drones before, 7 participants piloted drones several times, and 5 reported regular experience with aerial robots. As for VR experience, 11 participants used VR only a few times, and 4 people answered that they used VR devices regularly. \subsection{Results and discussion} Overall, the subjects assessed the ease of the UAV control process (Q1, Q2, Q3). The participants noted that the control mechanism was more natural (Q1) and easier (Q2) in the case of using a VR mode (Q1: $\mu=5.6,\ SD=1.7$ for VR and $\mu=4.8,\ SD=1.72$ for the RC control mode; Q2: $\mu=6.2,\ SD=0.65$ and $\mu=5.3,\ SD=1.53$ for VR and RC control, respectively). Using the one-way ANOVA, with a chosen significance level of $p<0.05$, we found a statistically significant difference in the ease of control between the two interfaces $(F(1,28)=4.43,\ p=0.04<0.05)$. According to ANOVA results, the type of control interface affects the involvement in the task (Q7) ($F(1,28)=8.02,\ p=8.5\cdot10^{-3}<0.05$) and the ability to concentrate (Q3) on the task ($F(1,28)=11.66,\ p=2\cdot10^{-3}<0.05$). In addition, for the VR mode, the subjects noted the convenience of the third-person view during the robot control (Q8: $\mu = 6.1$, $SD=1.25$). \begin{figure}[!h] \centering \includegraphics[width=1\linewidth]{figures/ExpResults.png} \caption{Experimental results averaged across all participants. Top: completion time; crosses mark mean values. Bottom: radar chart. } \label{fig:US} \vspace{-1em} \end{figure} Fig. \ref{fig:US} shows the results for task completion time and evaluation of control modes in the form of a radar chart across all participants. The difference in completion times is insignificant ($F(1,28) = 0.17,\ p = 0.68$) according to one-way ANOVA. Thus, the task execution time was comparable for both control modes (the average completion time is 130.8 $s$ with $SD=36.98$ for the desktop mode and 125.1 $s$ with $SD=37.1$ for the VR mode). The radar chart shows the user evaluation of two control modes in terms of Performance (Q3, Q4), Ease of control (Q1, Q2), Stress (Q6), Fatigue (Q5), and Involvement (Q7). According to the results of the user study, VR-based interface increases involvement and performance, whereas the stress level during task completion and fatigue of participants were almost the same for both control modes. At the same time, participants noted that it is easier to control the system through the VR application. \section{Conclusions and Future Work} We have proposed a novel interactive interface based on VR application for natural and intuitive human interaction with the autonomous robotic system for stocktaking. It allows the operator to conduct different levels of stocktaking, remotely monitor the inventory process, and teleoperate the drone for a more detailed inspection. According to the user study results, the VR control interface showed a better performance than the FPV mode in terms of ease of drone control and involvement in the task. It could be concluded that WareVR suggests a new way of communication between the robotic system and operator and can potentially improve and facilitate the inventory process.\par In future work, we are going to: \begin{itemize \item Incorporate a tracking glove with tactile feedback for the operator instead of using the HTC VIVE controller. It will facilitate the UAV control by introducing an understanding of the surrounding environment, working area, and obstacles. \item Add the functionality of the gesture control system to control not only a single drone but a whole swarm of drones (see Fig. \ref{fig:swarm}). Conducting experiments on gesture recognition with machine learning (ML). \item Currently, only individual tests of real flights in the warehouse have been conducted, and tests for remote control with the developed interface in the laboratory. The next stage will be testing the whole integrated system in the warehouse and conducting experiments with warehouse employees. \begin{comment} \item Improve the process of reconstruction of the digital twin of the warehouse, namely, the automatic recording of all information during the inventory and updating of the digital twin. Besides, we consider adding the opportunity to teleport the operator into the virtual warehouse to allow visiting its digital twin without leaving the workplace. \end{comment} \end{itemize} \begin{figure}[h] \centering \includegraphics[width=0.95\linewidth]{figures/swarm.jpg} \caption{The heterogeneous robotic system with swarm of drones in the digital twin environment.}~\label{fig:swarm} \vspace{-1em} \end{figure} \section*{Acknowledgements} The reported study was funded by RFBR, project number 20-38-90294. \bibliographystyle{IEEEtran}
{'timestamp': '2021-10-22T02:42:18', 'yymm': '2110', 'arxiv_id': '2110.11052', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.11052'}
arxiv
\section{Introduction} \label{INTRODUCTION} In the passing decade, deep neural networks (DNNs) have emerged as one of the most exciting developments in computer science, allowing computers to outperform humans in various classification tasks. However, a major issue with DNNs is the existence of \emph{adversarial inputs}~\cite{GoShSz14}: inputs that are very close (according to some metrics) to correctly-classified inputs, but which are misclassified themselves. It has been observed that many state-of-the-art DNNs are highly vulnerable to adversarial inputs~\cite{CaWa17}. As the impact of the AI revolution is becoming evident, regulatory agencies are starting to address the challenge of integrating DNNs into various automotive and aerospace systems --- by forming workgroups to create the needed guidelines. Notable examples in the European Union include SAE G-34 and EUROCAE WG-114~\cite{PeTh20,ViGaObOb21}; and the European Union Safety Agency (EASA), which is responsible for civil aviation safety, and which has published a road map for certifying AI-based systems~\cite{EuUnAvSaAg20}. These efforts, however, must overcome a significant gap: on one hand, the superior performance of DNNs makes it highly desirable to incorporate them into various systems, but on the other hand, the DNN's intrinsic susceptibility to adversarial inputs could render them unsafe. This dilemma is particularly felt in safety-critical systems, such as automotive, aerospace and medical devices, where regulators and public opinion set a high bar for reliability In this work, we seek to begin bridging this gap, by devising a framework that could allow engineers to \emph{bound and mitigate} the risk introduced by a trained DNN, effectively containing the phenomenon of adversarial inputs. Our approach is inspired by common practices of regulatory agencies, which often need to certify various systems with components that might fail due to an unexpected hazard. A widely used example is the certification of jet engines, which are known to occasionally fail. In order to mitigate this risk, manufacturers compute the engines' \emph{mean time between failures} (\emph{MTBF}), and then use this value in performing a safety analysis that can eventually justify the safety of the jet engine system as a whole~\cite{LaNi11}. For example, federal agencies guide that the probability of an extremely improbable failure conditions event per operational hour should not exceed $10^{-9}$~\cite{LaNi11}. To perform a similar process for DNN-based systems, we first need a technique for accurately bounding the likelihood of a failure to occur --- e.g., for measuring the probability of encountering an adversarial input. In this paper, we address the aforesaid crucial gap, by introducing a straightforward and scalable method for measuring the probability that a DNN classifier misclassifies inputs. The method, which we term \emph{Robustness Measurement and Assessment} (\emph{RoMA}), is inspired by modern certification concepts, and operates under the assumption that a DNN's misclassification is due to some internal malfunction, caused by random input perturbations (as opposed to misclassifications triggered by an external cause, such as a malicious adversary). A random input perturbation can occur naturally as part of the system's operation, e.g., due to scratches on a camera lens or communication disruptions. Under this assumption, RoMA can be used to measure the model's robustness to randomly-produced adversarial inputs. RoMA is a method for estimating rare events in a large population --- in our case, adversarial inputs within a space of inputs that are generally classified correctly. When these rare events (adversarial inputs) are distributed normally within the input space, RoMA performs the following steps: it \begin{inparaenum}[(i)] \item samples a few hundred random input points; \item measures the ``level of adversariality'' of each such point; and \item uses the normal distribution function to evaluate the probability of encountering an adversarial input within the input space. \end{inparaenum} Unfortunately, adversarial inputs are often \emph{not} distributed normally. To overcome this difficulty, when RoMA detects this case it first applies a statistical \emph{power transformation}, called Box-Cox~\cite{BoCo82}, after which the distribution often becomes normal and can be analyzed. The Box-Cox transformation is a widespread method that does not pose any restrictions on the DNN in question (e.g., Lipschitz continuity, certain kinds of activation functions, or specific network topology). Further, the method does not require access to the network's design or weights, and is thus applicable to large, black-box DNNs. We implemented our method as a proof-of-concept tool, and evaluated it on a VGG16 network trained on the CIFAR10 data set. Using RoMA, we were able to show that, as expected, a higher number of epochs (a higher level of training) leads to a higher robustness score. Additionally, we used RoMA to measure how the model's robustness score changes as the magnitude of allowed input perturbation is increased. Finally, using RoMA we found that the \emph{categorial robustness} score of a DNN, which is the robustness score of inputs labeled as a particular category, \emph{varies significantly} among the different categories. To summarize, our main contributions are: \begin{inparaenum}[(i)] \item introducing RoMA, which is a new and scalable method for measuring the robustness of a DNN model, and which can be applied to black-box DNNs; \item using RoMA to measure the effect of additional training on the robustness of a DNN model; \item using RoMA to measure how a model's robustness changes as the magnitude of input perturbation increases; and \item formally computing categorial robustness scores, and demonstrating that they can differ significantly between labels. \end{inparaenum} \mysubsection{Related work.} The topic of statistically evaluating a model's adversarial robustness has been studied extensively. State-of-the-art approaches~\cite{HuHuHuPe21,CoRoZi19} assume that the confidence scores assigned to perturbed images are normally distributed, and apply \emph{random sampling} to measure robustness. However, as we later demonstrate, this assumption often does not hold. Other approaches~\cite{WeRaTePa18,TiFuRo2021,MaNoOr19} use a sampling method called \emph{importance sampling}, where a few bad samples with large weights can drastically throw off the estimator. Further, these approaches typically assume that the network's output is Lipschitz-continuous. Although RoMA is similar in spirit to these approaches, it requires no Lipschitz-continuity, does not assume a-priori that the adversarial input confidence scores are distributed normally, and provides rigorous robustness guarantees. Other noticeable methods for measuring robustness include formal-verification based approaches~\cite{KaBaDiJuKo17, KaBaDiJuKo21}, which are exact but which afford very limited scalability; and approaches for computing an estimate bound on the probability that a classifier's margin function exceeds a given value~\cite{WeChNgSqBoOsDa19,AnSo20,DvGaFaKo18}, which focus on worst-case behavior, and may consequently be inadequate for regulatory certification. In contrast, RoMA is a scalable method, which focuses on the more realistic, average case. \section{Background} \label{Background} \mysubsection{Neural Networks.} A neural network $N$ is a function $N: \mathbb{R}^n \rightarrow \mathbb{R}^m$, which maps a real-valued input vector $ \vec{x} \in \mathbb{R}^n$ to a real-value output vector $\vec{y} \in \mathbb{R}^m$. For classification networks, which is our subject matter, $\vec{x}$ is classified as label $l$ if $y$'s $l$'th entry has the highest score; i.e., if $\argmmax(N(\vec{x}))=l$. \mysubsection{Local Adversarial Robustness.} The local adversarial robustness of a DNN is a measure of how resilient that network is against adversarial perturbations to specific inputs. More formally~\cite{BaIoLaVyNoCr16}: \begin{definition} \label{definition1} A DNN $N$ is $\epsilon$-locally-robust at input point $\vec{x_0}$ iff \[ \forall \vec{x}. \displaystyle || \vec{x} -\vec{x_0} ||_{\infty} \le \epsilon \Rightarrow \argmmax(N(\vec{x})) = \argmmax(N(\vec{x_0})) \] \end{definition} Intuitively, Definition~\ref{definition1} states that for input vector $\vec{x}$, which is at a distance at most $\epsilon$ from a fixed input $\vec{x_0}$, the network function assigns to $\vec{x}$ the same label that it assigns to $\vec{x_0}$ (for simplicity, we use here the $L_\infty$ norm, but other metrics could also be used). When a network is \emph{not} $\epsilon$-local-robust at point $\vec{x_0}$, there exists a point $\vec{x}$ that is at a distance of at most $\epsilon$ from $\vec{x_0}$, which is misclassified; this $\vec{x}$ is called an \emph{adversarial input}. In this context, \emph{local} refers to the fact that $\vec{x_0}$ is fixed. \mysubsection{Distinct Adversarial Robustness.} Recall that the label assigned by a classification network is selected according to its greatest output value. The final layer in such networks is usually a softmax layer, and its outputs are commonly interpreted as confidence scores assigned to each of the possible labels.\footnote{The term \emph{confidence} is sometimes used to represent the reliability of the DNN as a whole; this is not our intention here.} We use $c(\vec{x})$ to denote the highest confidence score, i.e. $c(\vec{x})=max(N(\vec{x}))$. We are interested in an adversarial input $\vec{x}$ only if it is \emph{distinctly} misclassified~\cite{LaNi11}; i.e., if $\vec{x}$'s assigned label receives a significantly higher score than that of the label assigned to $\vec{x_0}$. For example, if $\argmmax(N(\vec{x_0}))\neq \argmmax(N(\vec{x}))$, but $c(\vec{x})=20\%$, then $\vec{x}$ is not distinctly an adversarial input: while it is misclassified, the network assigns it an extremely low confidence score. Indeed, in a safety-critical setting, the system is expected to issue a warning to the operator when it has such low confidence in its classification~\cite{MiKwGa2018}. In contrast, a case where $c(\vec{x})=80\%$ is much more distinct: here, the network gives an incorrect answer with high confidence, and no warning to the operator is expected. We refer to inputs that are misclassified with confidence greater than some threshold $\delta$ as \emph{distinctly adversarial inputs}, and refine Definition~\ref{definition1} to only consider them, as follows: \begin{definition} \label{definition2} A DNN $N$ is ($\epsilon,\delta$)-distinctly-locally-robust at input point $\vec{x_0}$, iff \begin{align*} &\forall \vec{x}.\ \displaystyle || \vec{x} -\vec{x_0} ||_{\infty} \le \epsilon \Rightarrow \big( \argmmax(N(\vec{x})) = \argmmax(N(\vec{x_0})) \big) \vee (c(\vec{x})<\delta ) \end{align*} \end{definition} Intuitively, if the definition does not hold then there exists a (distinctly) adversarial input $\vec{x}$ that is at most $\epsilon$ away from $\vec{x_0}$, and which is assigned a label different than that of $\vec{x_0}$ with a confidence score that is at least $\delta$. \section{The Proposed Method} \label{Method} \subsection{Probabilistic Robustness} Definitions~\ref{definition1} and~\ref{definition2} are geared for an external, malicious adversary: they are concerned with the existence of an adversarial input. Here, we take a different path, and follow common certification methodologies that deal with internal malfunctions of the system~\cite{FAA93}. Specifically, we focus on ``non-malicious adversaries'' --- i.e., we assume that perturbations occur naturally, and are not necessarily malicious. This is represented by assuming those perturbations are randomly drawn from some distribution. We argue that the non-malicious adversary setting is more realistic for widely-deployed systems in, e.g., aerospace, which are expected to operate at a large scale and over a prolonged period of time, and are more likely to encounter randomly-perturbed inputs than those crafted by a malicious adversary. Targeting randomly generated adversarial inputs requires extending Definitions~\ref{definition1} and~\ref{definition2} into a probabilistic definition, as follows: \begin{definition} \label{definition3} The $(\delta,\epsilon)$-probabilistic-local-robustness score of a DNN $N$ at input point $\vec{x_0}$, abbreviated $\text{plr}\xspace{}{}_{\delta,\epsilon}(N,\vec{x_0})$, is defined as: \begin{align*} \text{plr}\xspace{}{}_{\delta,\epsilon}&(N,\vec{x_0}) \triangleq P_{x: \lVert \vec{x} -\vec{x_0} \rVert_\infty \le \epsilon} [(\argmmax(N(\vec{x})) = \argmmax(N(\vec{x_0})) \lor c(\vec{x}) < \delta)] \end{align*} \end{definition} Intuitively, the definition measures the probability that an input $\vec{x}$, drawn at random from the $\epsilon$-ball around $\vec{x_0}$, will either have the same label as $\vec{x_0}$ or, if it does not, will receive a confidence score lower than $\delta$ for its (incorrect) label. A key point is that probabilistic robustness, as defined in Definition~\ref{definition3}, is a scalar value: the closer this value is to 1, the less likely it is a random perturbation to $\vec{x_0}$ would produce a distinctly adversarial input. This is in contrast to Definitions~\ref{definition1} and~\ref{definition2}, which are Boolean in nature. We also note that the probability value in Definition~\ref{definition3} can be computed with respect to values of $\vec{x}$ drawn according to any input distribution of interest. For simplicity, unless otherwise stated, we assume that $\vec{x}$ is drawn uniformly at random. In practice, we propose to compute $\text{plr}\xspace{}{}_{\delta,\epsilon}(N,\vec{x})$ by first computing the probability that a randomly drawn $\vec{x}$ \emph{is} a distinctly adversarial input, and then taking that probability's complement. Unfortunately, directly bounding the probability of randomly encountering an adversarial input, e.g., with the Monte Carlo or Bernoulli methods~\cite{Ha13}, is not feasible due to the typical extreme sparsity of adversarial inputs, and the large number of samples required to achieve reasonable accuracy~\cite{WeRaTePa18}. Thus, we require a different statistical approach to obtain this measure, using only a reasonable number of samples. We next propose such an approach. \subsection{Sampling Method and the Normal Distribution} \label{NormalDistribution} Our approach is to measure the probability of randomly encountering an adversarial input, by examining a finite set of perturbed samples around $\vec{x_0}$. Each perturbation is selected through \emph{simple random sampling}~\cite{Ta16} (although other sampling methods can be used), while ensuring that the overall perturbation size does not exceed the given $\epsilon$. Next, each perturbed input $\vec{x}$ is passed through the DNN to obtain a vector of confidence scores for the possible output labels. From this vector, we extract the \emph{highest incorrect confidence} (\emph{$\text{hic}\xspace{}{}$}) score: \[ \text{hic}\xspace{}(\vec{x}) = \max_{i\neq \argmmax(N(\vec{x_0}))} \{N(\vec{x})[i]\} \] which is the highest confidence score assigned to an \emph{incorrect} label, i.e., a label different from the one assigned to $\vec{x_0}$. Observe that input $\vec{x}$ is distinctly adversarial if and only if its $\text{hic}\xspace{}{}$ score exceeds the $\delta$ threshold. The main remaining question is how to extrapolate from the collected $\text{hic}\xspace{}{}$ values a conclusion regarding the $\text{hic}\xspace{}{}$ values in the general population. The normal distribution is a useful notion in this context: if the $\text{hic}\xspace{}{}$ values are distributed normally (as determined by a statistical test), it is straightforward to obtain such a conclusion, even if adversarial inputs are scarce. To illustrate this process, we trained a VGG16 DNN model (information about the trained model and the dataset appears in Section~\ref{Evaluation}), and examined an arbitrary point $\vec{x_0}$, from its test set. We randomly generated 10,000 perturbed images around $\vec{x_0}$ with $\epsilon = 0.04$, and ran them through the DNN. For each output vector obtained this way we collected the $\text{hic}\xspace{}{}$ value, and then plotted these values as the blue histogram in Figure~\ref{DistributeNarmally}. The green curve represents the normal distribution. As the figure shows, the data is normally distributed; this claim is supported by running a ``goodness-of-fit'' test (explained later). \begin{figure}[htp] \centering \includegraphics[trim = 2cm 21cm 10cm 3.1cm,clip,width=.75\textwidth]{Figure5.pdf} \caption{A histogram depicting the highest incorrect confidence ($\text{hic}\xspace{}{}$) scores assigned to each of 10,000 perturbed inputs. These scores are normally distributed.} \label{DistributeNarmally} \end{figure} Our goal is to compute the probability of a fresh, randomly-perturbed input to be distinctly misclassified, i.e. to be assigned a $\text{hic}\xspace{}{}$ score that exceeds a given $\delta$, say $60\%$. For data distributed normally, as in this case, we begin by calculating the \emph{statistical standard score} (\emph{Z-Score}), which is the number of standard deviations by which the value of a raw score exceeds the mean value. Using the Z-score, we can compute the probability of the event using the Gaussian function. In our case, we get $ \text{hic}\xspace{}(\vec{x}) \sim \mathcal{N} ( \mu=0.499 , \Sigma=0.059^2)$, where $\mu$ is the average score and $\Sigma$ is the variance. The Z-score is $\frac{\delta-\mu}{\sigma} = \frac{0.6-0.499}{0.059}=1.741$, where $\sigma$ is the standard deviation. Recall that our goal is to compute the $\text{plr}\xspace{}{}$ score, which is the probability of the $\text{hic}\xspace{}{}$ value not exceeding $\delta$; and so we obtain that: \begin{align*} \text{plr}\xspace{}{}_{0.6,0.04}(N,\vec{x_0}) &= \text{NormalDistribution}\xspace{}(\text{Z-score}) \\ &= \text{NormalDistribution}\xspace{}(1.741) \\ &= \frac{1}{\sqrt{2\pi}}\int_{-\infty}^{t=1.741}e^\frac{-t^2}{2} dt = 0.9591 \end{align*} We thus arrive at a probabilistic local robustness score of $95.91\%$. Because our data is obtained empirically, before we can apply the aforementioned approach we need a reliable way to determine whether the data is distributed normally. A \emph{goodness-of-fit} test is a procedure for determining whether a set of $n$ samples can be considered as drawn from a specified distribution. A common goodness-of-fit test for the normal distribution is the Anderson-Darling test~\cite{An11}, which focuses on samples in the tails of the distribution~\cite{BeKoSc21}. In our evaluation, a distribution was considered normal only if the Anderson-Darling test returned a score value greater than $\alpha=0.15$, which is considered a high level of significance --- guaranteeing that no major deviation from normality was found. \subsection {The Box-Cox Transformation} \label{Box-Cox} Unfortunately, most often the $\text{hic}\xspace{}{}$ values are not normally distributed. For example, in our experiments we observed that only 1,282 out of the 10,000 images in the CIFAR10's test set (fewer than 13\%) demonstrated normally-distributed $\text{hic}\xspace{}$ values. Figure~\ref{DistributionBefore} illustrates the abnormal distribution of $\text{hic}\xspace{}$ values of perturbed inputs around one of the input points. In such cases, we cannot use the normal distribution function to estimate the probability of adversarial inputs in the population. \begin{figure}[h!] \centering \subfigure[] {\label{DistributionBefore} \includegraphics[trim = 2cm 21cm 10cm 3.1cm,clip,width=.7\textwidth]{Figure1.pdf}} \subfigure[] {\label{DistributionAfter} \includegraphics[trim = 2cm 21cm 10cm 3.1cm,clip,width=.7\textwidth]{Figure2.pdf}} \caption{On the top: a histogram depicting the highest incorrect confidence ($\text{hic}\xspace{}{}$) scores of each of 10,000 perturbed inputs around one of the test points. These scores are \emph{not} normally distributed. Beneath: the same scores after applying the Box-Cox power transformation, now normally distributed.} \end{figure} The strategy that we propose for handling abnormal distributions of data, like the one depicted in Figure \ref{DistributionBefore}, is to apply \emph{statistical transformations}. Such transformations preserve key properties of the data, while producing a normally distributed measurement scale~\cite{GrAmHu13} --- effectively converting the given distribution into a normal one. There are two main transformations used to normalize probability distributions: Box-Cox~\cite{BoCo82} and Yeo-Johnson~\cite{YeJo00}. Here, we focus on the Box-Cox power transformation, which is preferred for distributions of positive data values (as in our case). Box-Cox is a continuous, piecewise-linear power transform function, parameterized by a real-valued $\lambda$, defined as follows: \begin{definition} \label{definition4} The Box-Cox$_\lambda$ power transformation of input $x$ is: \[ \ BoxCox_\lambda (x)= \begin{cases} \frac{x^{\lambda}-1}{\lambda} & if \lambda \ne 0\\ \ln (x) & if \lambda=0 \end{cases} \] \end{definition} The selection of the $\lambda$ value is crucial for the successful normalization of the data. There are multiple automated methods for $\lambda$ selection, which go beyond our scope here~\cite{Ro18}. For our implementation of the technique, we used the common \emph{SciPy} Python package~\cite{scipy}, which implements one of these automated methods. Figure~\ref{DistributionAfter} depicts the distribution of the data from Figure~\ref{DistributionBefore}, after applying the Box-Cox transformation, with an automatically calculated $\lambda = 0.534$ value. As the figure shows, the data is now normally distributed: $\text{hic}\xspace{}(\vec{x}) \sim \mathcal{N} ( \mu=-0.79 , \Sigma=0.092^2)$. The normal distribution was confirmed with the Anderson-Darling test. Following the Box-Cox transformation, we can now calculate the Z-Score, which gives $3.71$, and the corresponding $\text{plr}\xspace{}{}$ score, which turns out to be 99.98\%. \subsection{The RoMA Certification Algorithm} \label{section:algorithm} Based on the previous sections, our method for computing $\text{plr}\xspace{}{}$ scores is given as Algorithm~\ref{algorithm1}. The inputs to the algorithm are: \begin{inparaenum}[(i)] \item $\delta$, the confidence threshold for a distinctly adversarial input; \item $\epsilon$, the maximum amplitude of perturbation that can be added to $\vec{x_0}$; \item $\vec{x_0}$, the input point whose $\text{plr}\xspace{}{}$ score is being computed; \item $n$, the number of perturbed samples to generate around $\vec{x_0}$; \item $N$, the neural network; and \item $\mathcal{D}$, the distribution from which perturbations are drawn. \end{inparaenum} The algorithm starts by generating $n$ perturbed inputs around the provided $\vec{x_0}$, each drawn according to the provided distribution $\mathcal{D}$ and with a perturbation that does not exceed $\epsilon$ (lines 1--2); and then storing the $\text{hic}\xspace{}{}$ score of each of these inputs in the \emph{hic} array (line 3). Next, lines 5--10 confirm that the samples' $\text{hic}\xspace{}{}$ values distribute normally, applying the Box-Cox transformation if needed. Finally, on lines 11--13, the algorithm calculates the probability of randomly perturbing the input into a distinctly adversarial input using the properties of the normal distribution, and returns the computed $\text{plr}\xspace{}{}_{\delta,\epsilon}(N,\vec{x_0})$ score on line 14. \begin{figure}[htp] \begin{algorithm}[H] \caption{Compute Probabilistic Local Robustness($\delta, \epsilon, \vec{x_0}, n, N, \mathcal{D}$)} \label{algorithm1} \begin{algorithmic}[1] \FOR {$i:=1$ to $n$} \label{lineRef1} \STATE $\vec{x^i}$ = CreatePerturbedPoint({$\vec{x_0},\epsilon,\mathcal{D}$}) \STATE $\text{hic}\xspace{}{}$[i] $\gets$ Predict({$N,\vec{x^i}$}) \ENDFOR \label{lineRef2} \IF {Anderson-Darling({hic} $\ne$ NORMAL)} \label{lineRef3} \STATE hic $\gets$ Box-Cox(hic) \IF {Anderson-Darling(hic $\ne$ NORMAL)} \STATE Return ``Fail'' \ENDIF \ENDIF\label{lineRef4} \STATE avg $\gets$ Average(hic)\label{lineRef5} \STATE std $\gets$ StdDev(hic) \STATE z-score $\gets$ Z-Score(avg,std,$BoxCox(\delta$))\label{lineRef6} \STATE Return NormalDistribution(z-score)\label{lineRef7} \end{algorithmic} \end{algorithm} \end{figure} \mysubsection{Soundness and Completeness.} Algorithm~\ref{algorithm1} depends on the distribution of $\text{hic}\xspace{}(\vec{x})$ being normal. If this is initially not so, the algorithm attempts to normalize it using the Box-Cox transformation. The Anderson-Darling goodness-of-fit test ensures that the algorithm does not treat an abnormal distribution as a normal one, and thus guarantees the soundness of the computed $\text{plr}\xspace{}{}$ scores. The algorithm's completeness depends on its ability to always obtain a normal distribution. As our evaluation demonstrates, the Box-Cox transformation can indeed lead to a normal distribution very often. However, the transformation might fail in producing a normal distribution; this failure will be identified by the Anderson-Darling test, and our algorithm will stop with a failure notice in such cases. In that sense, Algorithm~\ref{algorithm1} is incomplete. In practice, failure notices by the algorithm can sometimes be circumvented --- by increasing the sample size, or by evaluating the robustness of other input points. In our evaluation, we observed that the success of Box-Cox often depends on the value of $\epsilon$. Small or large $\epsilon$ values more often led to failures, whereas mid-range values more often led to success. We speculate that small values of $\epsilon$, which allow only tiny perturbation to the input, cause the model to assign similar $\text{hic}\xspace{}{}$ values to all points in the $\epsilon$-ball, resulting in a small variety of $\text{hic}\xspace{}{}$ values for all sampled points; and consequently, the distribution of $\text{hic}\xspace{}{}$ values is nearly uniform, and so cannot be normalized. We further speculate that for large values of $\epsilon$, where the corresponding $\epsilon$-ball contains a significant chunk of the input space, the sampling produces a close-to-uniform distribution of all possible labels, and consequently a close-to-uniform distribution of $\text{hic}\xspace{}{}$ values, which again cannot be normalized. We thus argue that the mid-range values of $\epsilon$ are the more relevant ones. Adding better support for cases where Box-Cox fails, for example by using additional statistical transformations and providing informative output to the user, remains a work in progress. \section{Evaluation} \label{Evaluation} For evaluation purposes, we implemented Algorithm~\ref{algorithm1} as a proof-of-concept tool written in Python 3.7.10, which uses the TensorFlow 2.5 and Keras 2.4 frameworks. For our DNN, we used a VGG16 network trained for 200 epochs over the CIFAR10 data set. All experiments mentioned below were run using the \emph{Google Colab Pro} environment, with an NVIDIA-SMI 470.74 GPU and a single-core Intel(R) Xeon(R) CPU @ 2.20GHz. The code for the tool, the experiments, and the model's training is available online~\cite{ourCode}. \mysubsection{Experiment 1: Measuring robustness sensitivity to perturbation size.} By our notion of robustness given in Definition~\ref{definition3}, it is likely that the $\text{plr}\xspace{}{}_{\delta,\epsilon}(N,\vec{x_0})$ score decreases as $\epsilon$ increases. For our first experiment, we set out to measure the rate of this decrease. We repeatedly invoked Algorithm~\ref{algorithm1} (with $\delta=60\%, n=1,000$) to compute $\text{plr}\xspace{}{}$ scores for increasing values of $\epsilon$. Instead of selecting a single $\vec{x_0}$, which may not be indicative, we ran the algorithm on all 10,000 images in the CIFAR test set, and computed the average $\text{plr}\xspace{}{}$ score for each value of $\epsilon$; the results are depicted in Figure~\ref{Figure3}, and indicate a strong correlation between $\epsilon$ and the robustness score. This result is supported by earlier findings~\cite{WeRaTePa18}. \begin{figure}[htp] \centering \includegraphics[trim = 1cm 2.8cm 1cm 2.7cm, clip,width=80mm]{Figure3.pdf} \caption{Average $\text{plr}\xspace{}{}$ score of all 10,000 images from the CIFAR10 dataset, computed on our VGG16 model as a function of $\epsilon$.} \label{Figure3} \end{figure} Running the experiment took less than 400 minutes, and the algorithm completed successfully (i.e., did not fail) on 82\% of the queries. We note here that Algorithm~\ref{algorithm1} naturally lends itself to parallelization, as each perturbed input can be evaluated independently of the others; we leave adding these capabilities to our proof-of-concept implementation for future work. \mysubsection{Experiment 2: Measuring robustness sensitivity to training epochs.} In this experiment, we wanted to measure the sensitivity of the model's robustness to the number of epochs in the training process. We ran Algorithm~\ref{algorithm1} (with $\delta=60\%,\epsilon=0.04, n=1,000$) on a VGG16 model trained with a different number of epochs --- computing the average $\text{plr}\xspace{}{}$ scores on all 10,000 images from CIFAR10 test set. The computed $\text{plr}\xspace{}{}$ values are plotted as a function of the number of epochs in Figure~\ref{Figure5}. The results indicate that additional training leads to improved probabilistic local robustness. These results are also in line with previous work~\cite{WeRaTePa18}. \begin{figure}[htp] \centering \includegraphics[trim = 1cm 9cm 1cm 10.2cm, clip,width=80mm]{Figure6.pdf} \caption{Average \text{plr}\xspace{}{} score of all 10,000 images from CIFAR10 test set, computed on VGG16 model as a function of training epochs.} \label{Figure5} \end{figure} \mysubsection{Experiment 3: Categorial robustness.} For our final experiment, we focused on \emph{categorial robustness}, and specifically on comparing the robustness scores across categories. We ran Algorithm~\ref{algorithm1} ($\delta$ = 60\%, $\epsilon = 0.04$, and $n=1,000$) on our VGG16 model, for all 10,000 CIFAR10 test set images. The results, divided by category, appear in Table~\ref{CategorialRobustnes}. For each category we list the average $plr$ score, the standard deviation of the data (which indicates the scattering for each category), and the probability of an adversarial input (the ``Adv'' column, calculated as $1-plr$). Performing this experiment took 37 minutes. Algorithm~\ref{algorithm1} completed successfully on 90.48\% of the queries. The results expose an interesting insight, namely the high variability in robustness between the different categories. For example, the probability of encountering an adversarial input for inputs classified as Cats is four times greater than the probability of encountering an adversarial input for inputs classified as Trucks. We observe that the standard deviation for these two categories is very small, which indicates that they are ``far apart'' --- the difference between Cats and Trucks, as determined by the network, is generally greater than the difference between two Cats or between two Trucks. To corroborate this, we applied a \emph{T-test} and a \emph{binomial test}; and these tests produced a similarity score of less than 0.1\%, indicating that the two categories are indeed distinctly different. The important conclusion that we can draw is that the per-category robustness of models can be far from uniform. \newcommand{\fixedmin}[1]{\rule{#1}{0pt}&\rule{#1}{0pt}&\rule{#1}{0pt}&\rule{#1}{0pt}\\[-\arraystretch\normalbaselineskip]} \begin{figure}[htp] \caption{An analysis of average, per-category robustness, computed over all 10,000 images from the CIFAR10 dataset.} \label{CategorialRobustnes} \begin{center} \begin{tabular}{llll}\fixedmin{2.5cm} {\bf Category} &{\bf $\text{plr}\xspace{}{}$} &{\bf Std-Dev.} &{\bf Adv} \\ \hline \\ Airplane & $99.143\%$ & $5.18\%$ & $0.857\%$ \\ Automotive & $99.372\%$ & $3.86\%$ & $0.628\%$ \\ Bird & $97.226\%$ & $8.87\%$ & $2.774\%$ \\ Cat & $97.112\%$ & $8.77\%$ & $2.888\%$ \\ Deer & $98.586\%$ & $6.25\%$ & $1.414\%$ \\ Dog & $97.233\%$ & $8.58\%$ & $2.767\%$ \\ Frog & $98.524\%$ & $6.39\%$ & $1.476\%$ \\ Horse & $98.606\%$ & $6.09\%$ & $1.394\%$ \\ Ship & $98.389\%$ & $6.63\%$ & $1.611\%$ \\ Truck & $99.390\%$ & $4.26\%$ & $0.610\%$ \\ \end{tabular} \end{center} \end{figure} It is common in certification methodology to assign each sub-system a different robustness objective score, depending on the sub-system's criticality~\cite{FAA93}. Yet, to the best of our knowledge, this is the first time such differences in neural networks' categorial robustness have been measured and reported. We believe categorial robustness could affect DNN certification efforts, by allowing engineers to require separate robustness thresholds for different categories. For example, for a traffic sign recognition DNN, a user might require a high robustness score for the ``stop sign'' category, and be willing to settle for a lower robustness score for the ``parking sign'' category. \section{Summary and Discussion} \label{Discussion} In this paper, we introduced RoMA --- a novel statistical and scalable method for measuring the probabilistic local robustness of a black-box, high-scale DNN model. We demonstrated RoMA's applicability in several aspects. The key advantages of RoMA over existing methods are: \begin{inparaenum}[(i)] \item it uses a straightforward and intuitive statistical method for measuring DNN robustness; \item scalability; and \item it works on black-box DNN models, without assumptions such as Lipschitz continuity constraints. \end{inparaenum} Our approach's limitations stem from the dependence on the normal distribution of the perturbed inputs, and its failure to produce a result when the Box-Cox transformation does not normalize the data. The $\text{plr}\xspace{}{}$ scores computed by RoMA indicate the risk of using a DNN model, and can allow regulatory agencies to conduct \emph{risk mitigation} procedures: a common practice for integrating sub-systems into safety-critical systems. The ability to perform risk and robustness assessment is an important step towards using DNN models in the world of safety-critical applications, such as medical devices, UAVs, automotive, and others. We believe that our work also showcases the potential key role of \emph{categorial robustness} in this endeavor. Moving forward, we intend to: \begin{inparaenum}[(i)] \item evaluate our tool on additional norms, beyond $L_\infty$; \item better characterize the cases where the Box-Cox transformation fails, and search for other statistical tools can succeed in those cases; and \item improve the scalability of our tool by adding parallelization capabilities. \end{inparaenum} \mysubsection{Acknowledgments.} We thank Dr. Pavel Grabov From Tel-Aviv University for his valuable comments and support. \bibliographystyle{splncs04}
{'timestamp': '2022-10-04T02:05:54', 'yymm': '2110', 'arxiv_id': '2110.11088', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.11088'}
arxiv
\section*{Media Summary} In the era of big data, observational studies are a treasure for both association analysis and causal inference, with the potential to improve decision-making. Depending on the set of assumptions one is willing to make, one might achieve either point, sign, or partial identification of causal effects. In particular, under partial identification, it might be inevitable to make suboptimal decisions. Policymakers caring about decision-making would face the following important question: What are optimal strategies corresponding to different risk preferences?\\ \indent In this article, the author offers a unified framework that generalizes several decision-making strategies in the literature. Building on this unified framework, the author also provides a novel minimax solution (i.e., a rule that minimizes the maximum regret for so-called opportunists) for individualized decision-making and policy assignment. \newpage \section{The power of storytelling: different views might lead to different decisions} \label{sec1} Suppose one is playing a two-armed slot machine. The rewards $R_{-1}$ and $R_{1}$ are the payoffs for hitting the jackpot of each arm, respectively. For simplicity, let us assume that both arms always give positive rewards ($R_{-1},R_{1}>0$), that is, one is guaranteed not to lose and therefore would not refrain from playing this game. However, due to some uncertainty, one does not have prior knowledge of the exact values of $R_{-1}$ and $R_1$. Fortunately, suppose there is a magic instrument, which can help one to identify the range of rewards. By only providing one with the left panel of Figure~\ref{fig:0}, that is, the range of $R_1-R_{-1}$, most people might opt to pull arm $-1$. But wait a minute... where am I, and why am I looking at the left panel without knowing the real payoffs? After looking at the right panel, the decision might be changed depending on a person's risk preference. \tikzstyle{txt} = [rectangle, thick, draw=white,fill=white,minimum size=10mm, minimum height=7mm] \begin{figure}[H] \centering \begin{tikzpicture} \begin{scope} \draw [thick](2,0.2)--(2,1.6); \draw [thick](4,0.6)--(4,1); \draw [thick](1.75,0.2)--node[right=2mm]{$0.1$}(2.25,0.2); \draw [thick](1.75,1.6)--node[right=2mm]{$0.8$}(2.25,1.6); \draw [thick](3.75,0.6)--node[right=2mm]{$0.3$}(4.25,0.6); \draw [thick](3.75,1)--node[right=2mm]{$0.5$}(4.25,1); \draw [dashed](0.5,0)--node[xshift=2.5cm,yshift=-3mm]{$0$}(5.5,0); \node[rectangle, thick, draw=black!10,fill=black!10,minimum size=10mm, minimum height=7mm, xshift=2cm, yshift=-0.5cm]{$R_{-1}$}; \node[rectangle, thick, draw=black!10,fill=black!10,minimum size=10mm, minimum height=7mm, xshift=4cm, yshift=-0.5cm]{$R_1$}; \end{scope} \begin{scope}[xshift=-3cm,yshift=1cm] \draw [thick,blue](0,-1)--(0,0.8); \draw [thick,blue](-0.25,-1)--node[right=2mm,blue]{$-0.5$}(0.25,-1); \draw [thick,blue](-0.25,0.8)--node[right=2mm,blue]{$0.4$}(0.25,0.8); \draw [dashed](-2.5,0)--node[xshift=2.5cm,yshift=-3mm]{$0$}(2.5,0); \node[rectangle, thick, draw=black!10,fill=black!10,minimum size=10mm, minimum height=7mm, xshift=0cm, yshift=-1.5cm]{$R_1-R_{-1}$}; \end{scope} \begin{pgfonlayer}{background} \filldraw [line width=4mm,black!10,xshift=-3cm,yshift=2cm] (-2,-3) rectangle (2,1); \filldraw [line width=4mm,black!10] (1,-1) rectangle (5,3); \end{pgfonlayer} \end{tikzpicture} \caption{A toy example on slot machines. The left panel: the possible range of $R_1-R_{-1}$; the right panel: the possible ranges of $R_{-1}$ and $R_1$, respectively. \label{fig:0}} \end{figure} Is there such an instrument in real life? The answer is in the affirmative. One such instrument is a so-called instrumental variable (IV). In statistics and related disciplines, an IV method is used to estimate causal relationships when randomized experiments are not feasible or when there is noncompliance in a randomized experiment. Intuitively, a valid IV induces changes in the explanatory variable but otherwise has no direct effect on the dependent variable, allowing one to uncover the causal effect of the explanatory variable on the dependent variable. Under certain IV models, one can obtain bounds for counterfactual means. So how would one pursue decision-making when faced with partial identification? The rest of the article offers a comprehensive view of individualized decision-making under partial identification as well as several novel solutions to various decision- and policy-making strategies. \subsection{Introduction} An optimal decision rule provides a personalized action/treatment strategy for each participant in the population based on one's individual characteristics. A prevailing strand of work has been devoted to estimating optimal decision rules \citep[and many others]{murphy2001marginal,murphy2003optimal,robins2004optimal,qian2011performance,zhao2012estimating,zhang2012estimating,wager2021policy}; we refer to \citet{chakraborty2013statistical,kosorok2019review,tsiatis2019dynamic} for an up-to-date literature review on this topic. Recently, there has been a fast-growing literature on estimating individualized decision rules based on observational studies subject to potential unmeasured confounding \citep{kallus2018confounding,yadlowsky2018bounds,kallusinterval,cui2020,qiu2020,pz,zp,han2018identification,han2020,han2019optimal,cuirejoinder,qiu2021,cui2020necessary}. In particular, \citet{cui2020} pointed out that one could identify treatment regimes that maximize lower bounds of the value function when one has only partial identification through an IV. \citet{pz} further proposed an IV-optimality criterion to learn an optimal treatment regime, which essentially recommends the treatment for patients for whom the estimated conditional average treatment effect bound covers zero based on the length of the bounds, that is, based on the left panel of Figure~\ref{fig:0}. See more details in \citet{cui2020,zp,cuirejoinder}. In this article, we provide a comprehensive view of individualized decision-making under partial identification through maximizing the lower bounds of the value function. This new perspective unifies various classical decision-making strategies in classical decision theory. Building on this unified framework, we also provide a novel minimax solution (for so-called opportunists who are unwilling to lose) for individualized decision-making and policy assignment. In addition, we point out that there is a mismatch between different optimality results, that is, an `optimal' rule that attains one criterion does not necessarily attain the other. Such mismatch is a distinctive feature of individualized decision-making under partial identification, and therefore makes the concept of universal optimality for decision-making under uncertainty ill-defined. Lastly, we provide a paradox to illustrate that a non-individualized decision can conceivably lead to an outcome superior to an individualized decision under partial identification. The provided paradox also sheds light on using IV bounds as sanity check or policy improvement. To conclude this section, we briefly introduce notation used throughout the article. Let $Y$ denote the outcome of interest and $A \in \{-1,1\}$ be a binary action/treatment indicator. Throughout it is assumed that larger values of $Y$ are more desirable. Suppose that $U$ is an unmeasured confounder of the effect of $A$ on $Y$. Suppose also that one has observed a pretreatment binary IV $Z \in \{-1,1\}$. Let $X$ denote a set of fully observed pre-IV covariates. Throughout, we assume the complete data are independent and identically distributed realizations of $(Y, X, A, Z, U)$; thus the observed data are $(Y,X,A,Z)$. \section{A brief review of optimal decision rules with no unmeasured confounding} An individualized decision rule is a mapping from the covariate space to the action space $\{-1, 1\}$. Suppose $Y_a$ is a person's potential outcome under an intervention that sets $A$ to value $a$, $Y_{{\mathcal{D}}(X)}$ is the potential outcome under a hypothetical intervention that assigns $A$ according to the rule ${\mathcal{D}}$, that is, $Y_{{\mathcal{D}}(X)} \equiv Y_{1}I\{{\mathcal{D}}(X)=1\}+Y_{-1}I\{{\mathcal{D}}(X)=-1\}$, $E[Y_{{\mathcal{D}}(X)}]$ is the value function \citep{qian2011performance}, and $I\{\cdot\}$ is the indicator function. Throughout the article, we make the following standard consistency and positivity assumptions: (1) For a given regime ${\mathcal{D}}$, $Y = Y_{{\mathcal{D}}(X)}$ when $A = {\mathcal{D}}(X)$ almost surely. That is, a person’s observed outcome matches his/her potential outcome under a given decision rule when the realized action matches his/her potential assignment under the rule; (2) We assume that $\Pr(A = a|X) > 0$ for $a = \pm 1$ almost surely. That is, for any observed covariates~$X$, a person has an opportunity to take either action. We wish to identify an optimal decision rule ${\mathcal{D}}^*$ that admits the following representation, that is, \begin{align} {\mathcal{D}}^*(X) = \text{sign}\{ E(Y_1-Y_{-1}|X)>0 \} ~\text{or}~ {\mathcal{D}}^* = \arg\max_{{\mathcal{D}}} E[Y_{{\mathcal{D}}(X)}]. \label{eq:opt2} \end{align} A significant amount of work has been devoted to estimating optimal decision rules relying on the following unconfoundedness assumption: \begin{assumption}\emph{(Unconfoundedness)} $Y_a \perp \!\!\! \perp A| X$ for $a=\pm 1$. \label{asm:unconfoundedness} \end{assumption} The assumption essentially rules out the existence of an unmeasured factor $U$ that confounds the effect of $A$ on $Y$ upon conditioning on $X$. It is straightforward to verify that under Assumption~\ref{asm:unconfoundedness}, one can identify the value function $E[Y_{{\mathcal{D}}(X)}]$ for a given decision rule ${\mathcal{D}}$. Furthermore, the optimal decision rule in Equation~\eqref{eq:opt2} is identified from the observed data \begin{align*} {\mathcal{D}}^*(X) = \text{sign}\{ {\mathcal{C}}(X)>0 \}, \end{align*} where ${\mathcal{C}}(X)=E(Y|X,A=1) - E(Y|X,A=-1)=E(Y_1-Y_{-1}|X)$ denotes the conditional average treatment effect (CATE). As established by \citet{qian2011performance}, learning optimal decision rules under Assumption~\ref{asm:unconfoundedness} can be formulated as \begin{align*} {\mathcal{D}}^*=\arg\max_{{\mathcal{D}}} E\left[\frac{I\{{\mathcal{D}}(X)=A\}Y}{\Pr(A|X)}\right], \end{align*} where $\Pr(A|X)$ is the probability of taking $A$ given $X$. \citet{zhang2012robust} proposed to directly maximize the value function over a parametrized set of functions. Rather than maximizing the above value function, \citet{zhao2012estimating,zhang2012estimating,rubin2012statistical} transformed the above problem into a weighted classification problem, \begin{align*} \arg\min_{\mathcal{D}} E \{|{\mathcal{C}}(X)| I[\text{sign}\{{\mathcal{C}}(X)>0\} \neq {\mathcal{D}}(X)]\}. \end{align*} The ensuing classification approach was shown to have appealing robustness properties, particularly in a randomized study where no model assumption on $Y$ is needed. \section{Instrumental variable with partial identification} In this section, instead of relying on Assumption~\ref{asm:unconfoundedness}, we allow for unmeasured confounding, which might cause biased estimates of optimal decision rules. Let $Y_{z,a}$ denote the potential outcome had, possibly contrary to fact, a person's IV and treatment value been set to $z$ and $a$, respectively. Suppose that the following assumption holds: \begin{assumption}\emph{(Latent unconfoundedness)} $Y_{z,a} \perp \!\!\! \perp (Z, A)|X, U$ for $z,a = \pm 1$. \label{asm:unconfoundedness2} \end{assumption} This assumption essentially states that together $U$ and $X$ would in principle suffice to account for any confounding bias. Because $U$ is not observed, we propose to account for it when a valid IV $Z$ is available that satisfies the following standard IV assumptions \citep{cui2020}: \begin{assumption}\emph{(IV relevance)} $Z \centernot{\perp \!\!\! \perp} A|X$. \label{IV Relevance} \end{assumption} \begin{assumption}\emph{(Exclusion restriction)} $Y_{z,a}=Y_a$ for $z,a=\pm 1$ almost surely. \label{Exclusion Restriction} \end{assumption} \begin{assumption}\emph{(IV independence)} $Z \perp \!\!\! \perp U |X$. \label{IV Independence} \end{assumption} \begin{assumption}\emph{(IV positivity)} $0<\Pr\left( Z=1|X\right)<1$ almost surely. \label{asm:IV positivity} \end{assumption} Assumptions~\ref{IV Relevance}-\ref{IV Independence} are well-known IV conditions, while Assumption~\ref{asm:IV positivity} is needed for nonparametric identification \citep{imbens1994,angrist1996,greenland2000,hernan2006epi}. Assumption~\ref{IV Relevance} requires that the IV is associated with the treatment conditional on $X$. Note that Assumption~\ref{IV Relevance} does not rule out confounding of the $Z$-$A$ association by an unmeasured factor, however, if present, such factor must be independent of $U$. Assumption~\ref{Exclusion Restriction} states that there can be no direct causal effect of $Z$ on $Y$ not mediated by $A$. Assumption~\ref{IV Independence} states that the direct causal effect of $Z$ on $Y$ would be identified conditional on $X$ if one were to intervene on $A=a$. Figure~\ref{fig:1} provides a graphical representation of Assumptions \ref{Exclusion Restriction} and \ref{IV Independence}. \tikzstyle{var} = [circle, very thick,draw=black,fill=white,minimum size=10mm] \begin{figure}[H] \centering \begin{tikzpicture}[>=latex] \node (A) [var, xshift=0cm,yshift=0cm]{$\boldsymbol{A}$}; \node (U) [var, xshift=1.5cm,yshift=-1.5cm]{$\boldsymbol{U}$}; \node (Y) [var, xshift=3cm,yshift=0cm]{$\boldsymbol{Y}$}; \node (X) [var, xshift=1.5cm,yshift=1.5cm]{$\boldsymbol{X}$}; \node (Z) [var, xshift=-3cm,yshift=0cm]{$\boldsymbol{Z}$} edge[<->, bend right=45, very thick](A) ; \draw[->, very thick] (X) -- (Z); \draw[->, very thick] (X) -- (A); \draw[->, very thick] (X) -- (Y); \draw[->, very thick] (Z) -- (A); \draw[->, very thick] (A) -- (Y); \draw[->, very thick] (U) -- (A); \draw[->, very thick] (U) -- (Y); \end{tikzpicture} \caption{A causal graph with unmeasured confounding. The bi-directed arrow between $Z$ and $A$ indicates the possibility that there may be unmeasured common causes confounding their association. \label{fig:1}} \end{figure} While Assumptions~\ref{IV Relevance}-\ref{asm:IV positivity} together do not suffice for point identification of the counterfactual mean and average treatment effect, a valid IV, even under minimal four assumptions, can partially identify the counterfactual mean and average treatment effect, that is, lower and upper bounds might be formed. Let $\mathcal{L}_{-1}\left( X\right) $, $\mathcal{U}_{-1}\left( X\right) $, $\mathcal{L}_{1}\left( X\right) $, $\mathcal{U}_{1}\left( X\right) $ denote lower and upper bounds for $E\left( Y_{-1}|X\right) $ and $E\left( Y_{1}|X\right) $; hereafter, we consider lower and upper bounds for $E\left( Y_{1}-Y_{-1}|X\right)$ of form $\mathcal{L}\left( X\right)={\mathcal{L}}_1(X)-{\mathcal{U}}_{-1}(X)$ and $\mathcal{U}\left( X\right)={\mathcal{U}}_1(X)-{\mathcal{L}}_{-1}(X)$, respectively; sharp bounds for $E\left( Y_{1}-Y_{-1}|X\right)$ in certain prominent IV models have been shown to take such a form, see for instance Robins-Manski bound \citep{robins1989, manski1990nonparametric}, Balke-Pearl bound \citep{Balke1997}, Manski-Pepper bound under a monotone IV assumption \citep{manski2000monotone} and many others. Here, we consider the following conditional Balke-Pearl bounds \citep{cui2020} for a binary outcome as our running example. Let $p_{y,a,z,x}$ denote $\Pr(Y = y, A = a|Z = z, X = x)$, and \begin{eqnarray*} \mathcal{L}_{-1}\left( x\right) =& \max \left \{ \begin{tabular}{c} $p_{1,-1,1,x}$ \\ $p_{1,-1,-1,x}$ \\ $p_{1,-1,-1,x} + p_{1,1,-1,x} - p_{-1,-1,1,x} - p_{1,1,1,x} $ \\ $p_{-1,1,-1,x} + p_{1,-1,-1,x} - p_{-1,-1,1,x} - p_{-1,1,1,x} $ \\ \end{tabular} \right \}, \\ \mathcal{U}_{-1}\left( x \right) =& \min \left \{ \begin{tabular}{c} $1 - p_{-1,-1,1,x}$ \\ $1- p_{-1,-1,-1,x}$ \\ $p_{-1,1,-1,x} + p_{1,-1,-1,x} + p_{1,-1,1,x} + p_{1,1,1,x} $ \\ $p_{1,-1,-1,x} + p_{1,1,-1,x} + p_{-1,1,1,x} + p_{1,-1,1,x} $ \\ \end{tabular} \right \}, \\ \mathcal{L}_{1}\left( x \right) =& \max \left \{ \begin{tabular}{c} $p_{1,1,-1,x}$ \\ $p_{1,1,1,x}$ \\ $-p_{-1,-1,-1,x} - p_{-1,1,-1,x} + p_{-1,-1,1,x} + p_{1,1,1,x} $ \\ $-p_{-1,1,-1,x} - p_{1,-1,-1,x} + p_{1,-1,1,x} + p_{1,1,1,x} $ \\ \end{tabular} \right \}, \\ \mathcal{U}_{1}\left( x \right) =& \min \left \{ \begin{tabular}{c} $1 - p_{-1,1,1,x}$ \\ $1- p_{-1,1,-1,x}$ \\ $p_{-1,-1,-1,x} + p_{1,1,-1,x} + p_{1,-1,1,x} + p_{1,1,1,x} $ \\ $p_{1,-1,-1,x} + p_{1,1,-1,x} + p_{-1,-1,1,x} + p_{1,1,1,x} $ \\ \end{tabular} \right \}. \end{eqnarray*} Additionally, one could proceed with other partial identification assumptions and corresponding bounds. We refer to references cited in \citet{Balke1997} and a review paper by \citet{swanson2018partial} for alternative bounds. We conclude this section by providing multiple settings in real life where an IV is available but Assumption~\ref{asm:unconfoundedness} is not likely to hold: 1) In a double-blind placebo-randomized trial in which participants are subject to noncompliance, the treatment assignment is a valid IV; 2) Another classical example is that in sequential, multiple assignment, randomized trials (SMARTs) in which patients are subject to noncompliance, the adaptive intervention is a valid IV. We note that the later proposed randomized minimax solution in Section~\ref{sec:minimax_game} offers a promising strategy for this setting; 3) In social studies, a classical example is estimating the causal effect of education on earnings. Residential proximity to a college is a valid IV. We will further elaborate the third example in the next section. \section{A real-world example} \label{sec:real} In this section, we first consider a real-world application on the effect of education on earnings using data from the National Longitudinal Study of Young Men \citep{card1993using, tan2006regression,okui2012doubly,wang2017,wang2018}, which consist of 5,525 participants aged between 14 and 24 in 1966. Among them, 3,010 provided valid education and wage responses in the 1976 follow-up. Following \citet{tan2006regression,wang2018}, we consider education beyond high school as a binary action/treatment (i.e., $A$). A practically relevant question is the following: Which students would be better off starting college to maximize their earnings? In this study, there might be unmeasured confounders even after adjusting for observed covariates, for example, unobserved preferences for education levels might be an unmeasured confounder that is likely to be associated with both education and wage. We follow \citet{card1993using,wang2017,wang2018} and use presence of a nearby four-year college as an instrument (i.e., $Z$). In this data set, 2,053 (68.2\%) lived close to a four-year college, and 1,521 (50.5\%) had education beyond high school. To illustrate the IV bounds with binary outcomes, we follow \citet{wang2017,wang2018} to dichotomize the outcome wage (i.e., $Y$) at its median, that is 5.375 dollars per hour. While we only use this as an illustrating example, we note that dichotomizing earnings might affect decision-making, and therefore in practice one might conduct a sensitivity analysis around the choice of cut-off. Following \citet{wang2018}, we adjust for age, race, father and mother’s education levels, indicators for residence in the south and a metropolitan area and IQ scores (i.e., $X$), all measured in 1966. Among them, race, parents’ education levels, and residence are included as they may affect both the IV and outcome; age is included as it is likely to modify the effect of education on earnings; and IQ scores, as a measure of underlying ability, are included as they may modify both the effect of proximity to college on education, and the effect of education on earnings. We use random forests to estimate the probability of $p_{y,a,z,x}$ \citep[with default tuning parameters in][]{RF} and then construct estimates of Balke-Pearl bounds $\mathcal{L}_{-1}\left( X\right) $, $\mathcal{U}_{-1}\left( X\right) $, $\mathcal{L}_{1}\left( X\right) $, $\mathcal{U}_{1}\left( X\right) $, $\mathcal{L}\left( X\right) $, $\mathcal{U}\left( X\right) $. To streamline our presentation, we consider the subset of individuals of age 15, parents' education level 11 years, non-Black, and residence in a non-south and metropolitan area. Their IV CATE and counterfactual mean bounds ${\mathcal{L}}(X)$, ${\mathcal{U}}(X)$, ${\mathcal{L}}_{-1}(X)$, ${\mathcal{U}}_{-1}(X)$, ${\mathcal{L}}_{1}(X)$, ${\mathcal{U}}_{1}(X)$ are presented in Figure~\ref{fig:2}. \begin{figure}[ht] \centering \includegraphics[width=5.2cm, height=5.2cm]{1.png} \hspace{0.7cm} \includegraphics[width=5.2cm, height=5.2cm]{3.png} \\ \caption{IV CATE and counterfactual mean bounds for two subjects with IQ scores 84.00 and 102.45, where $A=1$ and $-1$ refer to education beyond high school or not, respectively.} \label{fig:2} \end{figure} The shape of IV bounds looks similar to the slot machine example of Figure~\ref{fig:0} given at the beginning of the article. When faced with uncertainty, what are different decision-making strategies? In the next section, we provide a new perspective of viewing optimal decision-making under partial identification beyond just looking at contrast or value function. Except for the real-world example, for pedagogical purposes, we focus on the population level of IV bounds instead of their empirical analogs throughout. \section{The lower bound perspective: A unified criterion} \label{sec:5} In Section~\ref{sec:5.1}, we link the lower bound framework to well established decision theory from an investigator's perspective. In Section~\ref{sec:5.2}, we extend our framework to take into account individual preferences of participants. In Section~\ref{sec:minimax_game}, we provide a formal solution to achieve a minimax regret goal by leveraging a randomization scheme. In Section~\ref{sec:no_optimality}, we reveal a mismatch between deterministic/randomized minimax regret and maximin utility, and conclude that there is no universal concept of optimality for decision-making under partial identification. \subsection{A generalization of classical decision theory} \label{sec:5.1} In this section, we establish a formal link between individualized decision-making under partial identification and classical decision theory. The set of rules ${\mathcal{D}}(w(x),x)$ which maximize the following lower bounds of $E[Y_{{\mathcal{D}}(X)}]$, \begin{align*} &\Big\{E_X \{ [1-w(X)] [\mathcal{L}\left( X\right) I\left\{ \mathcal{D}(X)=1\right\} +\mathcal{L}_{-1}\left( X\right)] + w(X) [ -\mathcal{U}\left( X\right) I\left\{ \mathcal{D}(x)=-1\right\} +\mathcal{L}_{1}\left( X\right)]\}:\\& ~~~~ \text{where}~w(x)~\text{can depend on ${\mathcal{D}}(x)$},~0\leq w(x) \leq 1,~\text{for any}~ x\Big\}, \end{align*} is denoted by ${\mathcal{D}}^{opt}$. The derivation of lower bounds of $E[Y_{{\mathcal{D}}(X)}]$ is provided in the Appendix. Hereinafter, we refer to reasoning decision-making strategy from ${\mathcal{D}}^{opt}$ as the lower bound criterion, where, as can be seen later, $w(x)$ reflects the investigator's preferences. In Table~\ref{table:1}, we provide examples of decision-making criteria that have previously appeared in classical decision theory and we connect each such criterion to a corresponding $w(x)$. Hereafter, for a rule ${\mathcal{D}}$, we formally define utility as value function $E[Y_{{\mathcal{D}}(X)}]$ and regret as $E[Y_{{\mathcal{D}}^*(X)}] - E[Y_{{\mathcal{D}}(X)}]$. We give the formal definition of each rule in Table~ \ref{table:1} except that the mixed strategy is deferred to Section~\ref{sec:minimax_game}. In the following definitions, $\min$ or $\max$ without an argument is taken with respective to $E[Y_{{\mathcal{D}}(X)}]$ (recall that $E[Y_{{\mathcal{D}}(X)}]= E[E[Y_{1}|X]I\{{\mathcal{D}}(X)=1\}+E[Y_{-1}|X]I\{{\mathcal{D}}(X)=-1\}]$, and $E\left( Y_{-1}|X\right)$, $E\left( Y_{1}|X\right)$ satisfy ${\mathcal{L}}_{-1}(X)\leq E\left( Y_{-1}|X\right) \leq {\mathcal{U}}_{-1}(X)$, ${\mathcal{L}}_{1}(X)\leq E\left( Y_{1}|X\right) \leq {\mathcal{U}}_{1}(X)$, respectively), and ${\mathcal{D}}$ belongs to the set of all deterministic rules. \begin{itemize} \item Maximax utility (optimist): $\max_{{\mathcal{D}}} \max E[Y_{{\mathcal{D}}(X)}]$; \item (Wald) Maximin utility (pessimist): $\max_{{\mathcal{D}}} \min E[Y_{{\mathcal{D}}(X)}]$; \item (Savage) Minimax regret (opportunist): $\min_{{\mathcal{D}}} \max ( E[Y_{{\mathcal{D}}^*(X)}] - E[Y_{{\mathcal{D}}(X)}] )$; \item Hurwicz criterion: $\max_{{\mathcal{D}}} (\alpha \max E[Y_{{\mathcal{D}}(X)}]+ (1-\alpha) \min E[Y_{{\mathcal{D}}(X)}])$; \item Healthcare decision-making: $\max_{{\mathcal{D}}} E[E(Y_{-1}|X)+{\mathcal{L}}(X)I\{{\mathcal{D}}(X)=1\}]$. \end{itemize} For example, for the left panel of Figure~\ref{fig:2}, maximax utility criterion recommends $A=1$; maximin utility criterion recommends $A=-1$; minimax regret criterion recommends $A=-1$. Notably, all criteria in Table~\ref{table:1} reduce to ${\mathcal{D}}^*$ under point identification. For a more complete treatment of decision-making strategies and formal axioms of rational choice, we refer to \citet{arrow1972}. Interestingly, we note that a (deterministic) minimax regret criterion coincides with Hurwicz criterion with $\alpha=1/2$ as $\mathcal{L}\left( X\right)={\mathcal{L}}_1(X)-{\mathcal{U}}_{-1}(X)$ and $\mathcal{U}\left( X\right)={\mathcal{U}}_1(X)-{\mathcal{L}}_{-1}(X)$. \begin{table}[H] \centering \caption{Different representations of $w(x)$ for various decision-making strategies. \label{table:1}} \resizebox{1\columnwidth}{!}{ \begin{tabular}{| c| c| c|} \hline Decision theory criterion & $w(x)$ & The corresponding rule \\\hline Maximax utility (optimist) & $I(P>Q)$ & \parbox{3cm}{\begin{align*} {\mathcal{D}} (w(x),x)&= \begin{cases} 1 & {\mathcal{U}}_1(x)>{\mathcal{U}}_{-1}(x), \\ -1 & {\mathcal{U}}_1(x)< {\mathcal{U}}_{-1}(x). \\ \end{cases} \end{align*}} \\\hline Maximin utility (pessimist) & $I(P<Q)$ & \parbox{3cm}{\begin{align*} {\mathcal{D}} (w(x),x) &= \begin{cases} 1 & {\mathcal{L}}_1(x)>{\mathcal{L}}_{-1}(x), \\ -1 & {\mathcal{L}}_1(x)< {\mathcal{L}}_{-1}(x). \\ \end{cases} \end{align*}} \\\hline Minimax regret (opportunist) & $1/2$ & \parbox{3cm}{\begin{align*} {\mathcal{D}} (w(x),x)& = \begin{cases} 1 & {\mathcal{L}}(x)>0~\text{or}~{\mathcal{L}}(x)<0< {\mathcal{U}}(x),|{\mathcal{U}}(x)|>|{\mathcal{L}}(x)|, \\ -1 & {\mathcal{U}}(x)<0~\text{or}~{\mathcal{L}}(x)<0< {\mathcal{U}}(x), |{\mathcal{U}}(x)|<|{\mathcal{L}}(x)|. \end{cases} \end{align*}} \\\hline \pbox{20cm}{ \hspace{0.7cm} Hurwicz criterion\\ ($0\leq \alpha \leq 1$: Hurwicz index)} & $\alpha I(P>Q) + (1-\alpha) I(P<Q)$ & \parbox{3cm}{\begin{align*} {\mathcal{D}} (w(x),x) &= \begin{cases} 1 & (1-\alpha){\mathcal{L}}_1(x)+\alpha {\mathcal{U}}_1(x)>(1-\alpha){\mathcal{L}}_{-1}(x)+\alpha{\mathcal{U}}_{-1}(x), \\ -1 & (1-\alpha){\mathcal{L}}_1(x)+\alpha {\mathcal{U}}_1(x)<(1-\alpha){\mathcal{L}}_{-1}(x)+\alpha{\mathcal{U}}_{-1}(x). \\ \end{cases} \end{align*}} \\\hline \pbox{20cm}{Healthcare decision-making\\ ($A=-1$: standard of care)} & 0 & \parbox{3cm}{\begin{align*} {\mathcal{D}} (w(x),x) &= \begin{cases} 1 & {\mathcal{L}}(x)>0, \\ -1 & {\mathcal{L}}(x)<0. \\ \end{cases} \end{align*}} \\\hline ... & ... &... \\ \hline Mixed strategy & a Bernoulli $w(x)$ & a stochastic ${\mathcal{D}}(w(x),x)$ \\ \hline \end{tabular} } {\scriptsize Define $P\equiv \mathcal{L}\left( x\right) I\left\{ \mathcal{D}(x)=1\right\} +\mathcal{L}_{-1}\left( x\right)$ and $Q \equiv -\mathcal{U}\left( x\right) I\left\{ \mathcal{D}(x)=-1\right\} +\mathcal{L}_{1}\left( x\right)$. The arguments of $x$ and ${\mathcal{D}}$ in $P$ and $Q$ are omitted for simplicity. To streamline the presentation, we omit the case of tiebreaking.} \end{table} \begin{remark} While both lower bound criterion and Hurwicz criterion have an index, they are conceptually and technically different. The index $w(x)$ being a number between 0 and 1 refers to the preference of actions; with $w(x)$ being a weighted average of $I(P<Q)$ and $I(P>Q)$, the lower bound criterion balances pessimism and optimism; however, it may not be straightforward for Hurwicz criterion to balance preferences on treatments/actions. \end{remark} \subsection{Incorporating individualized preferences: numeric/symbolic/stochastic inputs} \label{sec:5.2} We note that the lower bound criterion also sheds light on the process of data collection for individualized decision-making. As individuals in the population of interest may ultimately exhibit different preferences for selecting optimal decisions, it may be unreasonable to assume that all participants share a common preference for evaluating optimality of an individualized decision rule under partial identification. An investigator might collect participants' risk preferences over the space of rational choices to construct an individualized decision rule. Therefore, we use the subscript $r$ (a participant's observed preference) to remind ourselves that $w_r(x)$ depends not only on $x$ but also on an individual's risk preference, that is, $r\in \mathcal{R}$ determines a specific form of $w_r(x)$ (see Table~\ref{table:1}), where $\mathcal{R}$ is a collection of different risk preferences. Such $w_r(x)$ results in a decision rule ${\mathcal{D}}(w_r(x),x)$ depending on both $x$ (standard individualization, e.g., in the sense of subgroup identification) and $r$ (individualized risk preferences when faced uncertainty), where $r$ can be collected from each individual. \begin{remark} We note that part of the elegance of this lower bound framework is that the risk preference does not come into play if there is no uncertainty about optimal decision, that is, if $0 \notin({\mathcal{L}}(x),{\mathcal{U}}(x))$, regardless what $w_r(x)$ being chosen, ${\mathcal{D}}(w_r(x),x)={\mathcal{D}}^*(x)$. \end{remark} Remarkably, the recorded index $w_r(x)$ for each $x$ could be numeric/symbolic/stochastic, that is, fall into any of the following three categories, while the participants only need to specify a category and input a number between 0 and 1 if the first two categories are chosen: \begin{itemize} \item Treatment/action preferences: Input a number $\beta$ between 0 and 1 which indicates preference on treatments/actions with larger $\beta$ in favor of $A=1$. Here, $w_r(x)=\beta$. In observational studies, most applied researchers upon observing $0\in ({\mathcal{L}}(x),{\mathcal{U}}(x))$ would rely on standard of care ($A=-1$) and opt to wait for more conclusive studies, which corresponds to $\beta=0$. In a placebo-controlled study with $A=-1$ denoting placebo, $\beta = 0$ represents concerns about safeness/aversion of treatment. \item Utility/risk preferences: Input a number $\beta$ between 0 and 1 and let symbolic input $w_r(x)=\beta I(P>Q) + [1-\beta] I(P<Q)$, where $\beta$ refers to the coefficient of optimism. For instance, $\beta=0$ puts the emphasis on the worst possible outcome, and refers to risk aversion; and likewise $\beta=1/2$, $1$ refer to risk neutral and risk taker, respectively. \item An option for opportunists who are unwilling to lose: Render $w_r(x)$ random as a Bernoulli random variable, see Section~\ref{sec:minimax_game} for details. \end{itemize} We highlight that the proposed index $w_r(x)$ unifies various concepts in artificial intelligence, economics, and statistics, which holds promise for providing a satisfactory regime for each individual through machine intelligence. \subsection{A randomized minimax regret solution for opportunists}\label{sec:minimax_game} In this section, we consider whether an investigator/participant who happens to be an opportunist can do better in terms of protecting the worst case regret than the minimax regret approach in Table~\ref{table:1}. An opportunist might not put all of his or her eggs in one basket. This mixed strategy is also known as mixed portfolio in portfolio optimization. Let $p(x)$ denote the probability of taking $A=1$ given $X=x$, by the definition of the minimax regret criterion, one essentially needs to solve the following for $p(x)$, $$\min_{p(x)} \max([1-p(x)] \max\{{\mathcal{U}}(x),0\} ,p(x) \max\{-{\mathcal{L}}(x),0\}),$$ which leads to the following solution \begin{align*} p^*(x)= \begin{cases} 1& {\mathcal{L}}(x)>0, \\ 0 & {\mathcal{U}}(x)<0, \\ \frac{{\mathcal{U}}(x)}{{\mathcal{U}}(x)-{\mathcal{L}}(x)} & {\mathcal{L}}(x)<0<{\mathcal{U}}(x). \\ \end{cases} \end{align*} Such a choice of $p^*(x)$ guarantees the worst case regret no more than \begin{align*} \begin{cases} 0 & {\mathcal{U}}(x)<0~\text{or}~{\mathcal{L}}(x)>0, \\ -\frac{{\mathcal{L}}(x){\mathcal{U}}(x)}{{\mathcal{U}}(x)-{\mathcal{L}}(x)} & {\mathcal{L}}(x)<0<{\mathcal{U}}(x).\\ \end{cases} \end{align*} We formalize the above result in the following theorem. \begin{theorem} Define the stochastic policy $\widetilde {\mathcal{D}}$ as $\widetilde {\mathcal{D}}(x)=1$ with probability $p^*(x)$, the corresponding regret is bounded by \begin{align*} E[Y_{{\mathcal{D}}^*(X)}] - E[Y_{\widetilde {\mathcal{D}}(X)}] \leq E\left[ -\frac{{\mathcal{L}}(X){\mathcal{U}}(X)}{{\mathcal{U}}(X)-{\mathcal{L}}(X)} I\{{\mathcal{L}}(X)<0<{\mathcal{U}}(X)\} \right], \end{align*} where $E[Y_{\widetilde {\mathcal{D}}(X)}] = E_X[ E_{\widetilde {\mathcal{D}}} [E_{Y_{\widetilde {\mathcal{D}}}}[Y_{\widetilde {\mathcal{D}}(X)}|\widetilde {\mathcal{D}},X] |X] ]$. \end{theorem} In contrast, by only considering deterministic rules, a minimax regret approach guarantees the worst case regret for $X=x$ which is no more than $$\min ( \max\{{\mathcal{U}}(x),0\} ,\max\{-{\mathcal{L}}(x),0\}).$$ It is clear that \begin{align*} -\frac{{\mathcal{L}}(x){\mathcal{U}}(x)}{{\mathcal{U}}(x)-{\mathcal{L}}(x)} < \min\{-{\mathcal{L}}(x),{\mathcal{U}}(x)\} ~~~~\text{if}~~~~ {\mathcal{L}}(x)<0<{\mathcal{U}}(x). \end{align*} Therefore, the proposed mixed strategy gives a sharper minimax regret bound than \citet{zp} and \citet{pz}, and therefore is sharper than any deterministic rules. \begin{remark} The result in this section does not necessarily rely on ${\mathcal{L}}(x)$ being defined as ${\mathcal{L}}_1(x) - {\mathcal{U}}_{-1}(x)$ and ${\mathcal{U}}(x)$ being defined as ${\mathcal{U}}_1(x) - {\mathcal{L}}_{-1}(x)$. \end{remark} \begin{remark} The proposed mixed strategy leads to $w(x)$ or $w_r(x)$ a Bernoulli random variable with probability $p^*(x)$, and therefore a stochastic rule ${\mathcal{D}}(w(x),x)$ or ${\mathcal{D}}(w_r(x),x)$ assigning 1 with probability $p^*(x)$. Note that $w_r(x)$ being a Bernoulli random variable with parameter $p(x)$, and $w_r(x)$ being a scalar $p(x)$ are fundamentally different: The former one provides a stochastic decision rule. In other words, participants with the same $x$ can receive different recommendations; while the latter one leads to a deterministic rule. That is, all participants with the same $x$ receive the same recommendation. \end{remark} \subsection{No universal optimality for decision-making under partial identification} \label{sec:no_optimality} As can be easily seen from Table~\ref{table:1} as well as Section~\ref{sec:minimax_game}, there is a mismatch between deterministic/randomized minimax regret and maximin utility. In fact, each of the three rules corresponds to a different decision strategy. Such mismatch is a distinctive feature of partial identification. On the one hand, it is notable that $\{{\mathcal{L}}(x),{\mathcal{U}}(x)\}$ provides complementary information to the analyst as it might inform the analyst as to when he/she might refrain from making a decision; mainly, if such an interval includes zero so that there is no evidence in the data as to whether the action/treatment is on average beneficial or harmful for individuals with that value of $x$. One might need to conduct randomized experiments in order to draw a causal conclusion if $0\in ({\mathcal{L}}(x),{\mathcal{U}}(x))$. On the other hand, the decision-making must in general be considered a game of four numbers $\{{\mathcal{L}}_1(x),{\mathcal{L}}_{-1}(x),{\mathcal{L}}(x), {\mathcal{U}}(x) \}$ rather than two, for example, $\{{\mathcal{L}}_1(x),{\mathcal{L}}_{-1}(x)\}$ or $\{{\mathcal{L}}(x),{\mathcal{U}}(x)\}$. From the above point of view, the concept of optimality of a decision rule under partial identification cannot be absolute, rather, it is relative to a particular choice of decision-making criterion, whether it is minimax, maximax, maximin, and so on. Furthermore, an individualized decision rule might incorporate participants' risk preferences as it might be unreasonable to assume everyone shares a common preference. In the Appendix, we provide expressions for the minimum utility, maximum regret, and maximum misclassification rate of certain `optimal' rules in Table~\ref{table:1} (including maximin utility and deterministic/randomized minimax regret rules) for practical uses. \section{A paradox: 1+1<2}\label{sec:6} In this section, we provide an interesting paradox regarding the use of partial identification to conduct individualized decision-making. To streamline our presentation, we use (deterministic) minimax regret rule as a running example, however, any rule ${\mathcal{D}}\in {\mathcal{D}}^{\text{opt}}$ can suffer the same paradox. To simplify exposition, we consider the case with no $U$, that unbeknownst to the analyst, unmeasured confounding is absent. We consider the following model with covariate $X$ (e.g., female/male) distributed on $\{0, 1\}$ with equal probabilities, \begin{align*} \Pr(Y=1|X,A) &= X/16 + 1/5A + 1/15,\\ \Pr(A=1|X,Z) &= X/16 + 2/5Z + 1/2,\\ Z & \sim \text{Bernoulli}(1/2). \end{align*} With a slight abuse of notation, we use $0,1$ coding for $Z,A$ here. It is easy to see that the optimal rule is ${\mathcal{D}}^*=1$ for the entire population. After a simple calculation, the Balke-Pearl conditional average treatment effect bounds for $X=0,1$ both contain zero with $|{\mathcal{L}}(0)|<|{\mathcal{U}}(0)|$ and $|{\mathcal{L}}(1)|>|{\mathcal{U}}(1)|$. The Balke-Pearl average treatment effect bounds marginalizing over $X$ also contain zero and $|{\mathcal{L}}|<|{\mathcal{U}}|$. As it is unbeknownst to the analyst whether unmeasured confounding is present or whether $X$ is an effect modifier, there are several possible strategies for analyzing the data. \begin{enumerate} \item If one is concerned about individualized decision-making but does not worry about unmeasured confounding, one runs a standard regression type analysis and gets the right answer. \item If one is concerned about unmeasured confounding but is only interested in decision-making based on the population level (i.e., based on average treatment effect analysis), one can obtain IV bounds on the average treatment effect and also get the right answer. \item If one is concerned about individualized decision-making and also worries about unmeasured confounding, one gets the wrong answer for a subgroup. \end{enumerate} We summarize results of the above strategies of analyses in Table~\ref{table:2}. \begin{table}[H] \begin{tabular}{lll} & $X=0$ & $X=1$ \\ (1) & $\surd$ & $\surd$ \\ (2) & $\surd$ & $\surd$ \\ (3) & $\surd$ & $\times$ \end{tabular} \caption{Correct/incorrect decisions using three types of data analyses. \label{table:2}} \end{table} As can be seen from the table, mixing up two very difficult domains (individualized recommendation + unmeasured confounding) might make life harder (1 + 1 < 2). There are several lessons one can learn from this paradox: a) A comparison between (1) and (3): It would be a good idea to first conduct a standard analysis (e.g., assume Assumption~\ref{asm:unconfoundedness}) or other point identification approaches \citep[e.g., assume Assumption~7 of][]{cui2020} and then use IV bounds as a sanity check or say policy improvement; b) A comparison between (2) and (3): The paradox sheds light on the clear need for carefully distinguish variables used to make individualized decisions from variables used to address confounding concerns; similar to but different from Simpson's paradox, the aggregated and disaggregated answers can be opposite for a substantial subgroup. c) (3) by itself: It might be a rather risky undertaking to narrow down an interval estimate to a definite decision given the overwhelming uncertainty; overly accounting for unmeasured confounding might erroneously recommend a sub-optimal decision to a subgroup. As motivated by the comparison between (1) and (3), we formalize the policy improvement idea following \citet{kallus2018confounding}. Note that minimizing the worst-case possible regret against a baseline policy ${\mathcal{D}}_0$ would improve upon those individuals for whom ${\mathcal{D}}_0(X)=-1, {\mathcal{L}}(X)>0$ and ${\mathcal{D}}_0(X)=1, {\mathcal{U}}(X)<0$. We revisit the real data example in Section~\ref{sec:real}. We first run a standard analysis (random forest: $Y$ on $X,A$) and obtain ${\mathcal{D}}_0(X)=\text{sign}\{\Pr(Y|X,A=1)-\Pr(Y|X,A=-1)\}$; among 3,010 subjects, 2,106 have ${\mathcal{D}}_0(X)=1$ and 904 have ${\mathcal{D}}_0(X)=-1$. Then we calculate IV conditional average treatment effect bounds, and there are 323 subjects with ${\mathcal{L}}(X)>0$ and 45 subjects with ${\mathcal{U}}(X)<0$. Then we use IV bounds as a sanity check/improvement: Only $4$ subjects with ${\mathcal{D}}_0(X)=-1$ switch to $1$, and $8$ subjects with ${\mathcal{D}}_0(X)=1$ switch to $-1$. Therefore, for most subjects in this application, the IV bounds do not necessarily invalidate the standard regression analysis, while IV bounds are still helpful to validate/invalidate decisions for a subgroup. \section{Discussion} In this article, we illustrated how one might pursue individualized decision-making using partial identification in a comprehensive manner. We established a formal link between individualized decision-making under partial identification and classical decision theory by considering a lower bound perspective of value/utility function. Building on this unified framework, we provided a novel minimax solution for opportunists who are unwilling to lose. We also pointed out that there is a mismatch between maximin utility and minimax regret. Moreover, we provided an interesting paradox to ground several interesting ideas on individualized decision-making and unmeasured confounding. To conclude, we list the following points that might be worth considering in future research. \begin{itemize} \setlength\itemsep{0.4em} \item As the proper use of multiple IVs is of growing interest in a lot of applications including statistical genetics studies, one could possibly construct multiple IVs and then try to find multiple bounds to conduct a better sanity check or improvement. Another possibility is to strengthen multiple IVs \citep{zubizarreta2013stronger,ertefaie2018quantitative}. A stronger IV might provide a tighter bound, and therefore a sign identification may be achieved \citep{cui2020necessary}. \item Including additional covariates which are associated with $A$ or $Y$ for stratification and then marginalizing over these covariates would potentially give a tighter bound. Therefore, carefully choosing variables used to stratify (which can be the same as decision variables or a larger set of variables) might be of interest for both theoretical and practical purposes. \item The proposed minimax regret method by leveraging a randomization scheme and other strategies in Table~\ref{table:1} might be of interest in optimal control settings such as reinforcement learning and contextual bandit where exploitation and exploration are under consideration. In addition, given observational data in which a potential IV is available, one can use different strategies to construct an initial randomized policy for use in a reinforcement learning and bandit algorithm. \item One important difference between decision-making with IV partial identification and classical decision theory is the source of uncertainty. For the former one, unmeasured confounding creates uncertainty, and overthinking confounding might create overwhelming uncertainty. Therefore, to better assess the uncertainty, it would also be of great interest to formalize a sensitivity analysis procedure for point identification such as under assumptions of no unmeasured confounding or no unmeasured common effect modifiers \citep{cui2020}. A similar question has also been raised by \citet{han2020}. \end{itemize} \subsection*{Disclosure Statement} The author is supported by NUS grant R-155-000-229-133. \subsection*{Acknowledgments} The author is thankful to three referees, associate editor, and Editor-in-Chief for useful comments, which led to an improved manuscript.
{'timestamp': '2021-10-22T02:38:31', 'yymm': '2110', 'arxiv_id': '2110.10961', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.10961'}
arxiv
\section{Introduction} Nowadays, powerful models with tremendous parameters trained with sufficient computation power are indispensable in Artificial Intelligence (AI), such as AlphaGo \citep{silver2016mastering}, Alphafold \citep{senior2020improved} and GPT-3 \citep{brown2020language}. However, billions of resource-constrained mobile and IoT devices have become the primary data source to empower the intelligence of many applications \citep{bonawitz2019towards, brisimi2018federated, li2019abnormal}. Due to privacy, security, regulatory and economic considerations \citep{voigt2017eu, li2018epa}, it is increasingly difficult and undesirable to pool data together for centralized training. Therefore, federated learning approaches \citep{mcmahan2017communication, smith2017federated, caldas2018leaf, kairouz2019advances, yang2019federated} allow all the participants to reap the benefits of shared models without sharing private data have become increasingly attractive. In a typical Federated Learning (FL) training process using FedAvg \citep{mcmahan2017communication}, each client sends its model parameters or gradients to a central server, which aggregates all clients' updates and sends the aggregated parameters back to the clients to update their local model. Because FL places computation burden on edge devices, its learnability is largely limited by the edge resources, on which training large models is often impossible. On the other hand, the server only directly aggregates the clients' models and its computation power is not fully exploited. In this work, we investigate the paradigm where the server adopts a \textit{larger} model in FL. \red{Here we use \textit{lar\textbf{g}er s\textbf{e}rver \textbf{m}odel}, or GEM to denote the setting where the size of the server model is larger than that of the clients (See Table \ref{tab:related_work}).} Making FL trainable with GEM is desirable to break through model capacity and enable collaborative knowledge fusion and accumulation at server. One feasible approach to bridge FL with GEM is through knowledge distillation (KD) \citep{hinton2015distilling}, where clients and the server transfer knowledge through logits. For example, FedGKT \citep{he2020group} adopts a server model as a downstream sub-model and transfers knowledge directly from smaller edge models. In FedGKT the large server model essentially learns from one small teacher at a time and doesn't learn consensus knowledge from multiple teachers. In FL, KD has also been applied \citep{li2019fedmd,lin2020ensemble} to transfer ensemble knowledge of clients through consensus of output logits rather than parameters. These works either assume no model on the server \citep{li2019fedmd} or a prototype server model of the same architecture as the client model \citep{lin2020ensemble}. \textbf{Contributions.} In this paper, we first propose a new paradigm to bridge FL with GEM, termed \textbf{FedGEM}, which can learn effectively and efficiently from fused knowledge by resource-constrained clients, and is also able to transfer knowledge back to clients with heterogeneous architectures. To further prevent negative and malicious knowledge transfer, we carefully design a \textbf{s}election and weighting criterion to enhance our knowledge transfer protocol, termed \textbf{FedGEMS}. We demonstrate with extensive experiments \red{on various image classification tasks} that our results significantly surpass the previous state-of-the-art baselines in both homogeneous and heterogeneous settings. Furthermore, thanks to our effective and selective protocol, our framework improves the robustness of FL on various malicious attacks and significantly reduces the overall communication. In summary, we propose a new framework to bridge FL with larger server models and simultaneously consolidate several benefits altogether, including superior performance, robustness of the whole system, and lower communication cost. \begin{figure} \centering \includegraphics[width=1\textwidth]{FedGEMS_V1.jpg} \vspace{-5mm} \caption{The framework of FedGEMS.} \vspace{-5mm} \label{fig:framework} \end{figure} \section{Related Work} \label{related} \textbf{Federated Learning with GEM.} FL is a collaborating learning framework without sharing private data among the clients. The classical method FedAvg \citep{mcmahan2017communication} and its recent variations \citep{mohri2019agnostic, lin2018don, li2019fair} directly transfer the clients' parameters or gradients to the server nodes. To tackle the performance bottleneck by training resource-constrained clients in FL, there are two lines of work to bridge FL with GEM. The first line of studies adopts model compression \citep{han2015deep, he2018amc, yang2018netadapt}, manually designed architectures \citep{howard2017mobilenets, zhang2018shufflenet, iandola2016squeezenet} or even efficient neural architecture search \citep{tan2019efficientnet, wu2019fbnet} to adapt a GEM to on-device learning. Another line is adopting knowledge distillation \citep{hinton2015distilling} to transfer knowledge through output logits rather than parameters between a client model and a GEM \citep{he2020group}. However, FedGKT \citep{he2020group}'s focus is to transfer knowledge directly from clients to server without considering the consensus knowledge fused from clients. Therefore its performance is limited. \textbf{Federated Learning with Knowledge Distillation.} In fact, ensemble knowledge distillation has been shown to boost collaborative performance in FL. Specifically, FedMD \citep{li2019fedmd} adopts a labeled public dataset and averaged logits to transfer knowledge. FedDF \citep{lin2020ensemble} proposes ensemble distillation for model fusion by aggregating both logits and models from clients. In addition, KD is used to enhance robustness in FL. Cronus \citep{chang2019cronus} and DS-FL \citep{itahara2020distillation} utilize a public dataset with soft labels jointly with local private dataset for local training, and combine with Cronus or entropy reduction aggregation, respectively, to defend against poisoning attacks in FL. In this work, we propose to exploit the benefit of both a larger server model and client knowledge fusion. Our work is also motivated by the recent studies in KD \citep{qin2021knowledge,you2017learning, DBLP:journals/corr/abs-2106-01489, yuan2021reinforced, wang2021selective}, which show that student models can have larger capacities by learning from multiple teacher models. \begin{table}[!t] \centering \small \begin{tabular}{cccccc} \toprule \textbf{Method} & \textbf{Public Data} & \textbf{Client Model Heterogeneity} & \textbf{Aggregation} & \textbf{Server model Size}\\ \midrule \textbf{FedAvg} & - & No & Average & - \\ \midrule \textbf{FedMD} & Labeled & Yes & Average & - \\ \midrule \textbf{Cronus} & Unlabeled & Yes & Cronus & - \\ \midrule \textbf{FedDF} & Unlabeled & No & Average & $=$ Client\\ \midrule \textbf{FedGKT} & - & Yes & - & $>$ Client \\ \midrule \textbf{DS-FL} & Unlabeled & Yes & Entropy-reduction & -\\ \midrule \textbf{FedGEM} & Labeled & Yes & Average & $>$ Client \\ \midrule \textbf{FedGEMS} & Labeled & Yes & Selective & $>$ Client \\ \bottomrule \end{tabular} \caption{Comparison of FedGEMS with related works.} \vspace{-4mm} \label{tab:related_work} \end{table} \section{Methodology} \subsection{Preliminaries} We assume that there are $K$ clients in federated learning process. The $k$th client has its own private labeled dataset $\boldsymbol{X}^{k}:=\{(\boldsymbol{x}_i^k, \boldsymbol{y}_i^k)\}_{i=1}^{N^{k}}$ that can be drawn from the same or different distribution, where $\boldsymbol{x}_i^k$ is the $i$th training sample in the $k$th client model, \red{$\boldsymbol{y}_i^k$} is its corresponding ground truth label, and $N^{k}$ denotes the total number of samples. Each client also trains its own model \red{$\boldsymbol{f}_{c}^k$} which can be of the same architecture (\textbf{homogeneous}) or different architecture (\textbf{heterogeneous}). There is also a public dataset $\boldsymbol{X}^{0}:=\{(\boldsymbol{x}_i^0, \boldsymbol{y}_i^0)\}_{i=1}^{N^{0}}$ which is accessible to both server and clients. On the server side, we assume that there is a larger server model to be trained, denoted as \red{$\boldsymbol{f}_{s}$}. \red{$\boldsymbol{L}_s$ and $\boldsymbol{L}_c^{k}$ denotes the logit tensors from the server and the $k$th client model.} \subsection{FedGEMS Framework} We illustrate our overall framework in Fig. \ref{fig:framework} and summarize our training algorithm in Algorithm \ref{alg:FedGEMS}. \textbf{FedGEM.} During each communication round, all client models first use private datasets to train several epochs, then transfer the predicted logits on public dataset as knowledge to the server model. The server model aggregates the clients' logits and then trains its server model with the guidance of fused knowledge. After training, the server model then transfers its logits back to all client models. Finally, each client model distills knowledge from received logits and continues their training on private datasets. Continuously iterating over multiple rounds, both the server and client models mutually learn knowledge from each other. Through this alternating training processing, we can obtain a large server model with accumulated knowledge and an ensemble of high-performance client models. \textbf{FedGEMS}: In FedGEMS, the server adopts a selection and weighting criterion to select knowledgeable clients for aggregation, which is detailed in the next section \ref{selective}. To illustrate the features of our framework, we compare it with the related studies of KD-based methods in federated learning in Table \ref{tab:related_work} on the following aspects: whether they use a labeled, unlabeled or no public dataset, whether client models can have heterogeneous architectures, the aggregation strategy on the server, and whether the server has a larger model. Note FedGEM can be regarded as placing a larger server model on top of the FedMD framework while keeping other settings the same. \subsection{Selective Knowledge Fusion in Server Model} \label{selective} \begin{algorithm}[!t] \caption{\textbf{Illustration of the Framework of FedGEMS.} $T$ is the number of communication rounds; $\boldsymbol{X}^{0}$ and $\boldsymbol{Y}^{0}$ denotes the images and their corresponding labels in public dataset; $\boldsymbol{X}^{k}$ and $\boldsymbol{Y}^{k}$ denotes the private dataset in the $k$th client model; $\boldsymbol{f}_s$ and $\boldsymbol{f}_c^k$ are the server with parameter \red{$\boldsymbol{W}_{s}$} and the $k$th client model with parameters \red{$\boldsymbol{W}_{c}^k$}; $\boldsymbol{L}_\text{Global}$ indicates the global logits to save correct logits; $\boldsymbol{L}_s$ and $\boldsymbol{L}_c^{k}$ are the logit tensors from the server and the $k$th client model. } \label{alg:FedGEMS} \vspace{-5mm} \small \begin{multicols}{2} \begin{algorithmic}[1] \State {\textbf{ServerExecute()}:} \For{each round $t=1,2,...,T$} \State {\emph{// Selective Knowldge Fusion}} \For{idx, $\boldsymbol{x}^0, \boldsymbol{y}^0 \in \{ \boldsymbol{X}^0, \boldsymbol{Y}^0 \}$} \If{$\boldsymbol{f}_s(\boldsymbol{W}_s;\boldsymbol{x}^0)$ predicts $y^0$} \State {$\mathcal{L}_s \leftarrow \mathcal{L}_{S_1}(\boldsymbol{x}^0, \boldsymbol{y}^0)$} \Comment{in Eq. \ref{eq:s1}} \State {$\boldsymbol{L}_\text{Global}[idx] \leftarrow \boldsymbol{L}_s[idx]$} \ElsIf{idx \text{in} $\boldsymbol{L}_\text{Global}$} \State {$\mathcal{L}_s \leftarrow \mathcal{L}_{S_2}(\boldsymbol{x}^0, \boldsymbol{y}^0, \boldsymbol{L}_\text{Global})$} \Comment{in Eq. \ref{eq:s2}} \Else \State {$\boldsymbol{L}_c \leftarrow \textbf{ClientSelect}(\text{idx})$} \State {$\mathcal{L}_s \leftarrow \mathcal{L}_{S_3} (\boldsymbol{x}^0, \boldsymbol{y}^0,\boldsymbol{L}_c)$} \Statex \Comment{in Eq. \ref{eq:entropy}, \ref{eq:weight}, \ref{eq:s3}} \EndIf \State {$\boldsymbol{W}_s \leftarrow \boldsymbol{W}_s - \eta_k\nabla{\mathcal{L}_s}$} \State {$\boldsymbol{L}_s[idx] \leftarrow \boldsymbol{f}_s(\boldsymbol{W}_s;\boldsymbol{x}^0)$} \EndFor \State {\emph{// Transfer Knowledge to Client Models}} \State {\textbf{ClientTrain}($\boldsymbol{L}_s$)} \EndFor \State {\textbf{ClientTrain}($\boldsymbol{L}_s$):} \For{each client $k$th \textbf{in parallel}} \State {\emph{// Knowledge Distillation on Clients}} \For{${\boldsymbol{x}^0, \boldsymbol{y}^0} \in \{ \boldsymbol{X}^0, \boldsymbol{L}_s, \boldsymbol{Y}^0 \}$} \State {$\mathcal{L}_c \leftarrow \mathcal{L}_{C} (\boldsymbol{x}^0, \boldsymbol{y}^0,\boldsymbol{L}_s)$} \Comment{in Eq. \ref{eq:client}} \State {$\boldsymbol{W}_c^{k} \leftarrow \boldsymbol{W}_c^{k} - \eta_k\nabla{\mathcal{L}_c}$} \EndFor \State {\emph{// Local Training on Clients}} \For{${\boldsymbol{x}^{k}, \boldsymbol{y}^{k}} \in \{\boldsymbol{X}^{k}, \boldsymbol{Y}^{k}\}$} \State {$\mathcal{L}_c \leftarrow \mathcal{L}_{CE} (\boldsymbol{x}^{k}, \boldsymbol{y}^{k})$} \State {$\boldsymbol{W}_c^{k} \leftarrow \boldsymbol{W}_c^{k} - \eta_k\nabla{\mathcal{L}_c}$} \EndFor \EndFor \Statex \State {\textbf{ClientSelect}(idx):} \State {\emph{// Selective Transfer to Server}} \For{each client $k$th \textbf{in parallel}} \State {$\boldsymbol{L}_c^{0}[idx] \leftarrow \boldsymbol{f}_c^{k}(\boldsymbol{W}_c^{k};\boldsymbol{x}^{0}[idx])$} \EndFor \State{Return $\boldsymbol{L}_c$ to server} \end{algorithmic} \end{multicols} \vspace{-3mm} \end{algorithm} Since clients' knowledge may negatively impact the server model in the heterogeneous or malicious setting and vice versa, we further propose selective strategies on both server and client sides to enforce positive knowledge fusion into the large server model as shown in Fig. \ref{fig:selective}. \subsubsection{\red{Self-Distillation of Server Knowledge}} \label{section:first} At each iteration, the server model first performs self evaluation on the public dataset and split the samples into two classes, those it can predict correctly, $S_\text{Correct}$, and those it predicts wrongly, $S_\text{Incorrect}$. For each sample $\boldsymbol{x}^i$ in $S_\text{Correct}$ where the model prediction matches the ground truth label, we simply adopt the cross-entropy loss between the predicted values and the ground truth labels to train the server model. \begin{equation} \label{eq:s1} \mathcal{L}_{S_1} = \mathcal{L}_{CE} = -\boldsymbol{y}^i\log (\boldsymbol{f}_{s}(\boldsymbol{x}^i)) \end{equation} At the same time, we save the correct logit $\boldsymbol{l}_s^i$ into the global pool of logits as $\boldsymbol{l}_{Global}^i$, which can be further used as memory to recover its reserved knowledge from self-distillation. For each sample $\boldsymbol{x}^i$ that the server predicts wrongly, we first check whether its corresponding global logit $\boldsymbol{l}_{Global}^i$ exists or not. We denote all samples that do not exist in $\boldsymbol{l}_{Global}$ as $S^*_\text{Incorrect}$, for which we believe the server model can not learn the sample entirely by itself and propose to use clients' collective knowledge as its teacher, which will be explained in the next section. If $\boldsymbol{l}_{Global}^i$ exists, it means that the knowledge was reserved by the server before, the server model performs self-distillation to recover this part of knowledge. The final training objective of self-distillation can be formulated as follows, where $\mathcal{D}_{KL}$ is the Kullback Leibler (KL) Divergence function and \red{$\epsilon$ is a hyper-parameter to control the weight of knowledge distillation in all the following formulations}. \begin{equation} \label{eq:s2} \begin{aligned} \mathcal{L}_{S_2} = \mathcal{L}_{SS} & = \epsilon\mathcal{L}_{CE} + (1 - \epsilon)\mathcal{D}_{KL}\left(\boldsymbol{l}_{Global}^i \| \boldsymbol{l}_{s}^i\right) \end{aligned} \end{equation} Our self-distillation strategy has at least two advantages. On the one hand, distilling knowledge from itself is better than from other models which have different architectures. On the other hand, learning from its stored logits can greatly reduce the communication cost as compared to transferring all redundant logits to client models. \subsubsection{\red{Selective Ensemble Distillation of Client Knowledge}} \label{section:second} For those samples in $S^*_\text{Incorrect}$ that the server model fails to predict correctly, we try to distill knowledge from the ensemble of clients. Furthermore, considering the correctness and relative importance of client models, we propose a weighted selective strategy on client side. Given an instance $(\boldsymbol{x}_i, \boldsymbol{y}_i)$ in $S^*_\text{Incorrect}$, we first split all clients $\{C_1, C_2, ..., C_K\}$ into the reliable and unreliable clients according to their predictions ${\bm{p}}_{C_j}$. For those clients who predict the wrong labels, we consider them as unreliable and discard their knowledge by setting their weights equal to $0$. As for the rest of clients who predict the labels correctly, we consider them as reliable and use their entropy $H({\bm{p}}_{C_j})$ as a measure of the confidence. \begin{equation} \label{eq:entropy} H({\bm{p}}_{C_j}) = -\sum_{i=1}^{N}{\bm{p}}(\boldsymbol{x}_i)log{\bm{p}}(\boldsymbol{x}_i) \end{equation} Following previous work \citep{DBLP:journals/corr/abs-2106-01489, pereyra2017regularizing, szegedy2016rethinking}, low entropy indicates high confidence, and vice versa. Specifically, given an instance $(\boldsymbol{x}_i, \boldsymbol{y}_i)$ in $S^*_\text{Incorrect}$, we design its corresponding weights to aggregate output logits from different clients as below. \begin{equation} \label{eq:weight} \boldsymbol{\alpha}_{C_j} = \begin{cases} 0 , & C_j \in C_{\text{Unreliable}} \\ \mathrm{softmax}(\frac{1}{H({\bm{p}}_{C_j})}) , & C_j \in C_{\text{Reliable}} \end{cases} \end{equation} \begin{figure}[!t] \centering \includegraphics[width=1\textwidth]{selection.jpg} \caption{Selective knowledge fusion module.} \vspace{-4mm} \label{fig:selective} \end{figure} Therefore, for samples in $S^*_\text{Incorrect}$, the knowledge transferred from ensemble clients to server model can be formulated as the following. \begin{equation} \label{eq:s3} \begin{aligned} \mathcal{L}_{S_3} = \mathcal{L}_{CS} & = \epsilon\mathcal{L}_{CE} + (1-\epsilon)\mathcal{D}_{KL}\left(\sum_{j=1}^{K}\boldsymbol{\alpha}_{C_j}\boldsymbol{l}_{C_j} \bigg| \bigg| \boldsymbol{l}_{s}\right) \end{aligned} \end{equation} Up to now, we have covered the selective knowledge fusion strategy for the server, next we will discuss the knowledge distillation on clients. \subsection{Training in Client Models} \label{client} Each client model first receives the logits $\boldsymbol{l}_{Server}^i$ of public dataset from the server model. Then it distills knowledge according to the logits as well as computes the cross-entropy loss to train on public dataset. \begin{equation} \label{eq:client} \begin{aligned} \mathcal{L}_{C} & = \epsilon\mathcal{L}_{CE} + (1-\epsilon)\mathcal{D}_{KL}\left(\boldsymbol{l}_{s}^i \| \boldsymbol{l}_{c}^i\right) \end{aligned} \end{equation} After knowledge distillation, each client model further adopts the cross-entropy loss to train on its local private dataset to better fit into its target distribution. \section{Experimental Evaluations} \subsection{Experiment Settings} \textbf{Task and Dataset.} For fair comparison, we use the same training tasks as \citet{he2020group}, which include image classifications on the CIFAR-10 \citep{krizhevsky2009learning} and CIFAR-100 \citep{krizhevsky2009learning} datasets. More details about these two datasets can be found in Appendix \ref{App:dataset}. For each dataset, we randomly split data into a public and a private dataset with a ratio of 1:1. We further study the impact of this ratio in Sec. \ref{sec:ratio} of our experiments. The public dataset is used for transferring knowledge between server node and client nodes, while the private dataset is for client training. Both of them further split into a training and a testing dataset with a ratio of 5:1. \textbf{Homogeneous Setting.} In our main experiments, we randomly shuffle and partition private dataset into \red{16} clients. As shown in Appendix \ref{homo_model}, our client models all adopt a tiny CNN architecture called ResNet-11, while the server model architecture is \red{ResNet-56}. \red{To investigate the influence of server model size and client number, we further vary the server model size from ResNet-20 to ResNet110 and the total client number from 4 to 64 in Sec. \ref{sec:model} and Sec. \ref{sec:number}, respectively}. \textbf{Heterogeneous Setting.} We adopt the Dirichlet distribution \citep{yurochkin2019bayesian, hsu2019measuring} to control the degree of heterogeneity in our non-iid setting. In this experiment, our $\alpha$ is $0.5$. We also introduce model heterogeneity in our experiments. The client models vary from ResNet-11 to Resnet-17 as shown in Appendix \ref{hetro_model}. \red{\textbf{Implementation Details.} In both homogeneous and heterogeneous settings, the number of local epochs are set to 1 after careful tuning, consistent with implementations in FedGKT. The number of communication round to reach convergence is 400. We adopt Adam optimizer \citep{kingma2014adam} with an initial learning rate 0.001. Following \citet{he2020group}, the learning rate can reduce once the accuracy is stable \citep{li2019exponential}. As for the factor $\epsilon$, we find that the best choice is \red{0.75}. Its impacts on server and client performance are shown in Appendix \ref{app:epsilon} .} \textbf{Baselines.} We compare our framework FedGEM/FedGEMS with the following baselines. (1) \textbf{Stand-Alone}: the server and client models train on their local datasets $\boldsymbol{X}^0$ and $\boldsymbol{X}^k$, respectively; (2) \textbf{Centralized}: the client model trains on the whole private dataset $\{\boldsymbol{X}^{1} + \cdots + \boldsymbol{X}^{k}\}$; (3) \textbf{Centralized-All}: the server and clients perform centralized training on the whole dataset $\{\boldsymbol{X}^{0} + \cdots + \boldsymbol{X}^{k}\}$, respectively. Note in reality no party has this complete dataset so this can be viewed as an upper limit of model performance. In addition, we also compare our performance with several existing related works, including \textbf{FedAvg} \citep{mcmahan2017communication}, \textbf{FedMD} \citep{li2019fedmd}, \textbf{Cronus} \citep{chang2019cronus}, \textbf{DS-FL} \citep{itahara2020distillation}, \textbf{FedDF} \citep{lin2020ensemble} and \textbf{FedGKT} \citep{he2020group}. For fair comparison, the settings of client models and the split of public and private dataset in all approaches are kept the same. \red{As for the server model, FedDF adopts the same architecture as its clients' model, ResNet-11, according to its design, while FedGKT and our FedGEMS utilize ResNet-56.} \red{Note FedGKT \citep{he2020group} only reported the performance of the server model. We empirically found that its clients' performance is lower due to constraints of model size. For a fair comparison with FedGKT, we only reported its performance on server side.} More details of their important hyper-parameters in our experiments are listed in Appendixes \ref{Hyper}, respectively. \subsection{Performance Evaluations} \begin{table}[!h] \small \centering \begin{tabular}{ccccccccc} \toprule \multirow{3}{*}{\textbf{Method}} & \multicolumn{4}{c}{\textbf{Homo}} & \multicolumn{4}{c}{\textbf{Hetero}} \\ \cmidrule(lr){2-5} \cmidrule(lr){6-9} & \multicolumn{2}{c}{\textbf{CIFAR-10}} & \multicolumn{2}{c}{\textbf{CIFAR-100}} & \multicolumn{2}{c}{\textbf{CIFAR-10}} & \multicolumn{2}{c}{\textbf{CIFAR-100}}\\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(lr){6-7} \cmidrule(lr){8-9} & \textbf{Server} & \textbf{Clients} & \textbf{Server} & \textbf{Clients} & \textbf{Server} & \textbf{Clients} & \textbf{Server} & \textbf{Clients}\\ \midrule \textbf{Stand-Alone} & 84.03 & 41.57 & 65.38 & 26.95 & 84.03 & 28.58 & 65.38 & 18.70\\ \textbf{Centralized} & - & 76.21 & - & 58.61 & - & 83.54 & - & 63.44 \\ \textbf{Centralized-All} & 91.27 & 82.45 & 78.13 & 65.51 & 91.27 & 88.54 & 78.13 & 70.96 \\ \textbf{FedAvg} & - & 53.33 & - & 31.47 & - & - & - & - \\ \textbf{FedMD} & - & 58.47 & - & 34.77 & - & 51.11 & - & 25.57 \\ \textbf{Cronus} & - & 57.73 & - & 34.19 & - & 53.47 & - & 29.71 \\ \textbf{DS-FL} & - & 50.78 & - & 25.70 & - & 43.83 & - & 16.69 \\ \textbf{FedDF} & - & 56.31 & - & 31.27 & - & - & - & - \\ \textbf{FedGKT} & 55.67 & - & 29.89 & - & 45.55 & - & 26.96 & - \\ \midrule \textbf{FedGEM} & 86.62 & 80.35 & 67.72 & 62.61 & 87.11 & 80.14 & 67.27 & 64.73 \\ \textbf{FedGEMS} & \textbf{88.08} & \textbf{81.86} & \textbf{69.08} & \textbf{63.81} & \textbf{87.97} & \textbf{84.18} & \textbf{67.72} & \textbf{65.93} \\ \bottomrule \end{tabular} \caption{\red{Model performance in homogeneous and heterogeneous settings.}} \vspace{-3mm} \label{tab:model_acc_16} \end{table} Table \ref{tab:model_acc_16} shows the comparisons of our approaches with other baselines with ResNet-56 as the server model. First of all, our approach FedGEM outperforms all the above KD-based federated learning baselines significantly on both server and client side, demonstrating the effectiveness of knowledge transfer with a larger server model. Compared with FedGKT which also adopts a larger server model, our performance is significantly improved by knowledge fusion from multiple clients. Compared to the performance of stand-alone server and clients, our framework simultaneously improves both the sever model and client model, indicating that server and clients mutually benefit from knowledge transfer. Using public labels for supervision and selection, our FedGEMS framework is able to enhance positive knowledge fusion and further improve performance on both server and clients. We also conduct experiments with 8 clients and ResNet-20 as server model, shown in Appendix \ref{App:client_8}. \subsection{Robustness} \textbf{Poisoning Attacks.} Following \citet{chang2019cronus}, we employ model poisoning attacks to evaluate the robustness of our methods. Our model poisoning attacks include Naive Poisioning (PAF), Little Is Enough Attack (LIE) \citep{baruch2019little} and OFOM \citep{chang2019cronus}. In PAF and LIE, the attacker poisons one client at each round via disturbing the logits or parameters which transfer from clients to server. In OFOM, two clients' benign predictions or parameters are poisoned at each round. The detailed algorithms about different poisoning attacks can be found in Appendix \ref{Poisoning}. \begin{table}[htp] \centering \vspace{-2mm} \small \resizebox{\textwidth}{17mm}{ \begin{tabular}{ccccccccc} \toprule \multirow{2}{*}{\textbf{Method}} & \multicolumn{2}{c}{\textbf{PAF}} & \multicolumn{2}{c}{\textbf{LIE}} & \multicolumn{2}{c}{\textbf{OFOM}} \\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(lr){6-7} & Server & Client & Server & Client & Server & Client\\ \midrule \textbf{FedMD} & - & 16.13 /-68.44 & - & 16.21/-68.28 & - & 22.53/-55.92\\ \textbf{DS-FL} & - & 37.94/-13.44 & - & 23.42/-46.57 & - & 23.32/-46.79\\ \textbf{Cronus} & - & \textbf{53.71/+00.45} & - & \textbf{53.98/+00.94} & - & \textbf{53.74 /-00.50} \\ \textbf{FedGKT} & 13.82/-69.66 & - & 10.42/-77.12 & - & 14.20/-68.83 & - \\ \midrule \textbf{FedGEM}& 55.94/-35.78 & 72.78/-09.18 & 74.86/-14.06 & 74.32/-07.26 & 85.22/-02.17 & 74.47/-07.08 \\ \textbf{FedGEMS} & \textbf{87.46/-05.80} & \textbf{82.58/-01.90} & \textbf{87.95/-00.02} & \textbf{83.27/-01.08} & \textbf{88.53/+00.64} & \textbf{82.76/-01.67} \\ \bottomrule \end{tabular}} \caption{\red{Comparison of model poisoning attacks in heterogeneous setting. The A in ``A/B'' denotes the model performance after attacks, while B denotes the percentage changes compared to the original accuracy (``+'' denotes increasing, and ``-'' denotes dropping). We remark both the best performance and the least changed ratio (\%) to its original accuracy.}} \vspace{-2mm} \label{tab:hetero_attack} \end{table} The results of poisoning attacks in \red{heterogeneous} setting on CIFAR-10 dataset are shown in Table \ref{tab:hetero_attack}. By adopting a selective strategy, our proposed FedGEMS provides consistent robustness across various attacks on both server and client models. FedGEM demonstrates superior robustness to FedMD on various model poisoning attacks. DS-FL is relatively more robust than FedMD via its proposed entropy reduction aggregation based on FedMD framework. Since Cronus specifically designs secure robust aggregation in a FedMD framework, its robustness to the attacks is strong, as expected. The performance of FedGKT drops marginally because it transmits extra feature maps which is vulnerable. Our selective knowledge transfer strategy shows comparably strong robustness on both clients and server side without additional computation cost for robust aggregation algorithms. \subsection{Communication Cost} \label{sub:comm} \red{Following \citet{itahara2020distillation}, we further evaluate the cumulative communication costs required to achieve specific accuracy in heterogeneous setting on CIFAR-10. The epochs in both client and server sides among all methods to achieve their best performances are the same as 1 which further ensures fairness. The formulations to calculate communication cost for different methods are shown in Appendix \ref{App:formu}. \begin{table}[!h] \centering \vspace{-2mm} \resizebox{\textwidth}{15mm}{ \begin{tabular}{crrrc} \toprule \textbf{Method} & \textbf{ComU@40\% (MB)} & \textbf{ComU@50\% (MB)} & \textbf{ComU@80\% (MB)} & \textbf{Top-Acc (\%)} \\ \midrule \textbf{FedMD} & 976.56 & 5,493.16 & - & 51.11\\ \textbf{Cronus} & 610.35 & 2,471.92 & - & 53.47\\ \textbf{DS-FL} & 3,692.63 & - & - & 43.83\\ \textbf{FedGKT} & 31,250.00 & - & - & 45.55 \\ \midrule \textbf{FedGEM} & 91.55 & 244.14 & 3,261.27 & 80.14\\ \textbf{FedGEMS} & 23.38 & 190.87 & 1,894.84 & 84.18 \\ \bottomrule \end{tabular}} \caption{\red{Comparison of communication cost and Top-Accuracy. ComU@x: the cumulative communication cost required to achieve the absolute accuracy of x. Top-Accuracy: the highest testing accuracy among the training process.}} \vspace{-2mm} \label{tab:com_co} \end{table} The results are shown in Table \ref{tab:com_co}. It is worth noting that FedMD, Cronus, DS-FL and FedGEM cost the same per round according to their designs. Therefore, to achieve the accuracy of 45\%, FedGEM costs much lower than other three methods which indicates that FedGEM converges fast. The communication cost of FedGKT is much higher than others because it sends a feature map per private data in training. Specifically, the communication cost per feature map is 64kb while the cost per logit is only 0.039kb. Furthermore, the communication cost of FedGEMS keeps lower than FedGEM in the whole training phase which means that our selective strategy can effectively reduce uploads to achieve the same performance. } \section{Understanding FedGEMS} \subsection{Knowledge Accumulation at Server} \begin{figure}[!h] \begin{minipage}[b]{.5\linewidth} \centering \includegraphics[width=\linewidth, height=30mm]{ablation_v1.png} \caption{\red{Total number of samples in different selective decisions.}} \label{fig:trend} \end{minipage} \begin{minipage}[b]{.5\linewidth} \centering \begin{tabular}{lcc} \toprule \textbf{Method} & \textbf{Server} & \textbf{Client} \\ \midrule FedGEMS & \textbf{88.08} & \textbf{81.86} \\ - Self-Training & 85.73 & 80.17 \\ - Self-Distillation & 86.12 & 81.30 \\ - Ensemble Distillation & 86.55 & 80.01 \\ \bottomrule \end{tabular} \vspace{3mm} \captionof{table}{\red{Ablation studies of three components in selective strategy.}} \label{tab:ablation} \end{minipage} \vspace{-7mm} \label{fig:my_label} \end{figure} To analyze the selective knowledge fusion process of the server model in our framework, we report the number of samples associated with each step in our decision-making process in our experiment on CIFAR-10 with 25,000 samples as public dataset. Each sample will choose one of three strategies according to our selective knowledge fusion module. Specifically, in Fig. \ref{fig:trend}, the line of self-training indicates the total number of samples the server model predicts correctly, while the lines of self-distillation and ensemble-distillation indicate the number of samples the server learns via self-distillation and client-side ensemble knowledge, respectively. In the initial stage, since both the server and client models learn from scratch, the number of samples that the server model can predict correctly is limited, and most of the knowledge is accumulated by distillation from the client models' fusion. As the training progresses, the server model needs to restore some of its knowledge from a self-distillation strategy. With the server model continually fusing sufficient knowledge, the model performance of server model eventually exceeds client models and the number of transferred samples from clients dropped to 0. Notice that in the final stage, there still remains some stubborn samples which are hard for the server model while most samples can be solved by the large server model with accumulated knowledge. \red{Furthermore, we conduct a series of ablation studies to detect the contributions of different components to the accumulated knowledge at server side. The results are shown in Table \ref{tab:ablation} and all the performances of both server and client models decrease. This phenomenon indicates that each component contributes to the overall performance. Comprehensively, self-training is the most important component and the most probable reason is that learning from the model itself is the most effective way. Ensemble distillation which avoids transferring knowledge from malicious clients can also help prompt the performance of client models in return.} \subsection{Effect of \red{Public and Private Dataset Ratio}} \label{sec:ratio} \red{Concerning the size of public dataset, we evaluate the effect of public and private dataset ratio on both model performance and communication cost per round. To change the ratio, we fix the size of private dataset, and vary the size of public dataset from 5,000 to 25,000. \begin{figure}[!h] \centering \vspace{-5mm} \includegraphics[width=\textwidth, height=35mm]{public_v1.jpg} \vspace{-9mm} \caption{\red{(a) Model performance of both server (top) and client (bottom) models on public dataset of different sizes; (b) Communication cost per round on public dataset of different sizes.}} \vspace{-2mm} \label{fig:public} \end{figure} The results of both model performance and communication cost per round are shown in Fig. \ref{fig:public} (a) and (b) respectively. } As for model performance, it can be seen that both the client and server model continuously improve as the size of public data increases, indicating that their performances are highly correlated. Our performance consistently outperforms FedMD, and the performance gap over FedMD continuously grows as more public dataset is available. Note again FedGEM is essentially FedMD with a larger server model so the performance gain is due to the accumulated knowledge on the server side. As for FedDF which owns an ensemble server model as same architecture as clients, the performance in both server and client models remains a huge gap to our performance. This phenomenon further demonstrates the importance of the large capacity of server model. FedGEMS can still outperform FedGEM especially on the client side which indicates that our selective strategy is efficient to fuse positive knowledge to boost performance. Due to the compact models deployed in client nodes, the bits of model parameters are limited, thus the communication overhead of FedAvg and FedDF is not always higher than typical KD-based methods when a large public dataset is used. Due to the enormous communication overhead of feature maps, we do not figure the flat line (irrelevance to the size of public dataset) of FedGKT which is always 1.6M (kb) per round. Thanks to our selection strategy, the communication cost of our proposed framework FedGEMS is the lowest among all methods. In summary, the results demonstrate that our selection strategy can greatly save the communication cost with reasonable public data size. \subsection{Effect of Server Model Size} \label{sec:model} We further investigate the influence of the server model size on the overall performance by gradually changing the server model from ResNet-20 to \red{ResNet-110}, while fixing the client models as ResNet-11. The details of the model parameters can be found in Appendix \ref{App:Large}. \begin{figure}[!h] \centering \vspace{-3mm} \includegraphics[width=\textwidth, height=32mm]{server_acc_v1.png} \vspace{-6mm} \caption{\red{(a) Server (top) and client (bottom) model performances of different server model sizes; (b) server (top) and client (bottom) model performances of different numbers of clients.}} \vspace{-3mm} \label{fig:size} \end{figure} The results are shown in Fig. \ref{fig:size} (a). It can be witnessed that the performance of both the server and client models improves as the server model becomes larger and deeper. This phenomenon verifies the importance of placing a larger deeper server model to boost the performance of both server and the resource-constrained client models. \subsection{\red{Effect of Number of Clients}} \label{sec:number} \red{We vary the number of clients from 4 to 64 of our proposed method FedGEMS while keeping the total number of private samples the same. Thus the number of private samples per client vary accordingly. The experimental results shown in Fig. \ref{fig:size} (b) indicate that with increased number of clients and less client data, the performance of our approaches is basically stable especially in client side, benefiting from our larger server model setting with fused knowledge. } \section{Conclusion} In this work, we first propose a new paradigm to apply a large deeper server model to effectively and efficiently fuse and accumulate knowledge, which can enhance the model performances on both server and client sides. Furthermore, we design a selection and weighted criterion on both sides to distill only positive knowledge into the server. We conduct a series of experiments to evaluate our proposed framework FedGEMS and our results show that FedGEMS can significantly surpass all baselines in both homogeneous and heterogeneous settings. Meanwhile, FedGEMS can further improve the robustness of FL on poisoning attacks as well as reduce the communication costs between server and client sides. \red{Our framework has certain limitations, such as the dependence of a labeled public dataset.} In future work, we will study the effectiveness of our work in other critical tasks, such as NLP and knowledge graph-based tasks, \red{and in the settings where public and private data are from different domains or distributions}.
{'timestamp': '2021-12-08T02:14:38', 'yymm': '2110', 'arxiv_id': '2110.11027', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.11027'}
arxiv
\subsubsection{Least-impedance} The least-impedance (LI) policy is to send the lambda request to $\bar{d}$, where $\bar{d} = \arg\min_j w_j$. Quite clearly, this policy is a limit case where there is no proportional fairness at all: LI is an extremely simple greedy approach which does not require any state to be maintained at the e-router. On the other hand, it may suffer from the herd effect mentioned above. \subsubsection{Random-proportional} The random-proportional (RP) policy is to send the lambda request to $d$ with probability $1/w_d$. It is straightforward to see that RP enjoys the property of \textit{long-term proportional fairness}: over a sufficiently large observation interval the ratio between the number of lambda requests served by any two e-computers $i$ and $j$ is $N_i/N_j=w_j/w_i$. However, in the short-term, fairness is not provided: due to the probabilistic nature of this policy, there is no mechanism preventing any destination (or sub-set of destinations) to be selected repeatedly for an arbitrary number of times, thus making RP arbitrarily unfair over any finite time horizon. \subsubsection{Round-robin} The round-robin (RR) algorithm is inspired from a high-level discussion in~\cite{Destounis2016} and combines together the proportional nature of RP with the greediness of LI\@. With RR we maintain an \textit{active list} of destinations $\mathcal{A} = \{ w_j | w_j \le 2 \cdot \min_h w_h \}$. For each destination $j \in \mathcal{A}$ we keep a \textit{deficit counter} $\Delta_j$ initially set to $0$. The policy is then to send the lambda request to $d = \arg\min_j \Delta_j$ and at the same time increase $\Delta_d$ by $w_d$. Once a destination goes out of the active list, it is re-admitted for a single ``probe'' after an initial back off time, doubled every time the probe request fails to meet the active list admission criterion; when the active set is updated we decrease all $\Delta_j$ by $\min_h \Delta_h$. We note that, as a new destination is added, a trivial implementation following from the algorithm definition would have $\mathcal{O}(n)$ time complexity since all destinations in $\mathcal{A}$ need have their deficit counter updated. However, a simple data structure that avoids such linear update can be adopted: the active destination deficit counters can be stored in a list sorted by increasing deficit counters, where only the differences with the previous elements are kept. For instance, if the deficit counters are $\{4, 6, 7, 7\}$ the data structure will hold $\{4, 2, 1, 0\}$; since the front element of the list is always the minimum, the update can be done in $\mathcal{O}(1)$ by simply resetting this value. \begin{figure} {\small \begin{center} \added{ \fbox{\parbox{3.2in}{ {\bf initialization}: $\mathcal{A} = \mathcal{P} = \emptyset$, $\forall j : w_j = e_j = 0, b_j = b_{\min}$ \vspace{0.5em} {\bf function} {\it leastImpedance()}: \hspace{1em} {\bf return} $\arg\min_j \left\{ w_j \right\}$ \vspace{0.5em} {\bf function} {\it randomProportional()}: \hspace{1em} {\bf return} random $d$ with probability $1/w_d$ \vspace{0.5em} {\bf function} {\it roundRobin()}: \hspace{1em} select random $d \in \left\{ j | e_j > now() \land j \notin \mathcal{P} \right\}$ \hspace{1em} {\bf if} $\exists d$: $\mathcal{P} = \mathcal{P} \cup \{ d \}$ \hspace{1em} {\bf else}: \hspace{2em} $d = \arg\min_j \left\{ \Delta_j | j \in \mathcal{A} \right\}$ \hspace{2em} $\Delta_d = \Delta_d + w_d$ \hspace{1em} {\bf return} $d$ \vspace{0.5em} {\bf function} {\it onReceiveResponse($\delta, d$)}: ($\delta$ is the latency measured for the response from $d$) \hspace{1em} {\bf if} {\it leastImpedance} $\lor$ {\it randomProportional}: \hspace{2em} $w_d = \alpha \cdot w_d + (1 - \alpha) \cdot \delta$ \hspace{1em} {\bf else}: {\tt /*} {\it roundRobin} {\tt */} \hspace{2em} {\bf if} $d \in \mathcal{P}$: \hspace{3em} $\mathcal{P} = \mathcal{P} \setminus \{ d \}$ \hspace{3em} {\bf if} $\delta \leq 2 \cdot \min_j \left\{ w_j | j \in \mathcal{A} \right\}$: \hspace{4em} $\forall j \in \mathcal{A}: \Delta_j = \Delta_j - \min_j \{ \Delta_j \}$ \hspace{4em} $\mathcal{A} = \mathcal{A} \cup \{ d \}$ \hspace{4em} $b_d = b_{\min}, \Delta_d = w_d = \delta$ \hspace{3em} {\bf else}: \hspace{4em} $b_d = 2 \cdot b_d, e_d = now() + b_d$ \hspace{2em} {\bf else}: \hspace{3em} $w_d = \alpha \cdot w_d + (1 - \alpha) \cdot \delta$ \hspace{3em} {\bf if} $w_d > 2 \cdot \min_j \left\{ w_j | j \in \mathcal{A} \right\}$: $\mathcal{A} = \mathcal{A} \setminus \{ d \}$ }} } \end{center} } \vspace{-0.5em} \caption{Pseudo-code of the algorithms in \rsec{algorithms}.} \label{fig:pseudocode} \vspace{-1.5em} \end{figure} \added{ The algorithms presented so far in natural language are also described with the pseudo-code in \rfig{pseudocode} (corner cases not addressed for simplicity, we refer the interested reader to the real implementation, available as \textit{open source} for full details), where $b_j$ is the relative backoff time before a destination is probed for its inclusion in the active list (starting with minimum value $b_{\min}$) and $e_j$ is the absolute time when it will be considered for inclusion in the set $\mathcal{P}$ of probed destinations. Note that least-impedance and random-proportional only use $w_j$ state variables. } In the following we show that RR achieves both short-term and long-term proportional fairness. To this aim, we introduce a more formal definition of the algorithm. Let $\mathcal{A}$ be the set of active destinations, each with a deficit counter $\Delta_i$ initialized to $0$. At time $n$, select destination $x = \arg\min_i\{\Delta_i\}$, breaking ties arbitrarily; then, update the deficit counter of the destination selected as follows: $\Delta_x = \Delta_x + \tilde{\delta_x}$, where $\tilde{\delta_x}$ is an estimate of the time required for the lambda function requested to complete if forwarded to edge computer $x$. We denote as $\delta_x$ the \textit{actual} completion time, but this cannot be known at the time the forwarding decision is taken. When a new edge computer $y$ is added to $\mathcal{A}$ it is assigned $\Delta_y = 0$ and all the other deficit counters are updated as follows: \begin{gather} \Delta^{\min} = \min_{i \in \mathcal{A} \setminus y}\left\{\Delta_i\right\} \\ \forall i \in \mathcal{A} \setminus y : \Delta_i = \Delta_i - \Delta^{\min} \end{gather} After each update $\exists i \in \mathcal{A} | \Delta_i = 0$. \begin{lemma}\label{lemma1} The difference between any two deficit counters is bounded by a finite constant equal to the maximum completion time estimate ($\tilde\delta^{\max}$), i.e.: \begin{equation} \max_{i,j}\left\{\Delta_i - \Delta_j\right\} \leq \tilde\delta^{\max} \end{equation} \end{lemma} \begin{proof} The statement can be proved by contradiction. Assume: \begin{equation}\label{eq:lemma1a} \exists i,j | \Delta_i(n) - \Delta_j(n) = \tilde\delta^{\max} + \epsilon \end{equation} Without loss of generality, we can assume that $i$ was the destination selected at time $n-1$ (it this was not the case, then one can substitute $n-1$ in the following with the last time $i$ was selected; meanwhile we can assume that $j$ was never selected otherwise its deficit counter would have increased, which would have \textit{reduced} the gap between deficit counters). In this case, it is: \begin{equation}\label{eq:lemma1b} \Delta_i(n-1) = \Delta_j(n-1) = \Delta_j(n) \end{equation} Putting together~\req{lemma1a} and~\req{lemma1b} we obtain: \begin{align} \Delta_i(n) &= \Delta_j(n) + \tilde\delta^{\max} + \epsilon = \\ &= \Delta_i(n-1) + \tilde\delta^{\max} + \epsilon \end{align} From which it is: \begin{equation} \tilde\delta_i = \tilde\delta^{\max} + \epsilon \end{equation} Which is impossible for any $\epsilon > 0$ by definition of $\tilde\delta^{\max}$. \end{proof} In the following we assume for simplicity that the completion time estimates are constant over time, i.e.\ it is $\tilde\delta_i(n) = \delta_i$ for any destination $i$. Furthermore, we define $s_i(n)$ as the number of times the destination $i$ was selected by the forwarding algorithm since $n=0$. \begin{lemma}[short-term fairness] For any two destinations $i,j$ at any time $n$ the difference between their number of services weighted by the respective completion time is bounded by the maximum completion time $\delta^{\max} = \max_i\{\delta_i\}$: \begin{equation} \forall i,j \in \mathcal{A} : s_i(n) \delta_i - s_j(n) \delta_j \leq \delta^{\max} \end{equation} \end{lemma} \begin{proof} To prove the statement let us consider the update process of both $s_i(n)$ and $\Delta_i(n)$: \begin{equation}\label{eq:lemma2a} s_i(n) = s_i(n-1) + \begin{cases} 1 & \text{if } i = \arg\min_j\left\{\Delta_j(n-1)\right\} \\ 0 & \text{otherwise} \end{cases} \end{equation} \begin{equation}\label{eq:lemma2b} \Delta_i(n) = \Delta_i(n-1) + \begin{cases} \delta_i & \text{if } i = \arg\min_j\left\{\Delta_j(n-1)\right\} \\ 0 & \text{otherwise} \end{cases} \end{equation} From~\req{lemma1a} and~\req{lemma1b} it follows that: \begin{equation} \Delta_i(n) = s_i(n) \delta_i \end{equation} which proves the statement with Lemma~\ref{lemma1}. \end{proof} \mytabfull% {schedexample}% {Visual forwarding example used in Lemma~\ref{lemma3} with three destinations with $\delta_1 = 2$, $\delta_2 = 3$, $\delta_3 = 4$.} \begin{lemma}[long-term fairness]\label{lemma3} Over a long enough time horizon the number of services of any destination $i$ is inversely proportional to its completion time $\delta_i$, i.e.: \begin{equation} \exists i,j \in \mathcal{A}, n >0 | \frac{s_i(n)}{s_j(n)} = \frac{\delta_j}{\delta_i} \end{equation} \end{lemma} \begin{proof} Let us start with the assumption that $\delta_i \in \mathbb{N}$. In this case, using the visual example in~\rtab{schedexample}, it is easy to see that there is a time $n^*$ where $\Delta_i = \Delta_j$ for any $i,j$, which can be computed as: \begin{equation} n^* = \sum_i \frac{T}{\delta_i} \end{equation} where $T = lcm_i\{\delta_i\}$, which gives: \begin{equation} s_i(n^*) = \frac{T}{\delta_i} \end{equation} from which the lemma follows. The statement can be easily extended to the case of $\delta_i \in \mathbb{Q}$ as follows. Find $D$ as the LCM of the denominators of $\delta_i$, then set $\delta'_i = D/den(\delta_i)$. We now have new $\delta'_i$ values that are in $\mathbb{N}$ by construction and the same method as above can be used. \end{proof} \section{ETSI MEC integration} \input{etsimec.tex} \section{Avoiding loops in the hierarchical overlay} \input{scalability-examples} \section{Performance evaluation (further results)} In this section we report the results from two scenarios aimed at evaluating the following basic properties of the solution proposed: \begin{itemize}[leftmargin=*,label={--}] \item Our fairness notion (see~\rsec{algorithms:destination}) is highly related to an efficient load balancing among e-computers. % This is shown in a \textit{line topology} (\rsec{eval:line}) with a single e-router having ample choice of destination among many e-computers. % Specifically, in these conditions LI, which is the most unfair of the three algorithms studied, is not even reported because it exhibits very poor performance, whereas RR, which enjoys both short- and long-term fairness, achieves best results in terms of delay. \item Network congestion is tackled efficiently by exploiting a cross-layer interaction with the \ac{SDN} controller (top branch of \req{weightupdate}), as illustrated in a \textit{ring tree topology} (\rsec{eval:ring}). \item Our solution is efficient in edge-cloud scenarios. This is shown in a \textit{pods topology} (\rsec{eval:pods}), where the e-routers automatically prefer remote (powerful) e-computers or nearby (low-power) devices, depending on their instantaneous load conditions, always aiming at reducing the latency of lambda responses. \end{itemize} We then conclude the extra results in the appendix with a scenario in a \textit{tree topology} (\rsec{eval:tree}) that exacerbates the effect on delay with hierarchical vs.\ flat forwarding, already visible in \rsec{eval:large}. Some of the results in this section have already been presented in in~\cite{Cicconetti2018}. \myssec{Emulator}{eval:emulator} \input{emulator} \myssec{Line topology}{eval:line} \input{eval-line} \myssec{Pods topology}{eval:pods} \input{eval-pods} \myssec{Ring tree topology}{eval:ring} \input{eval-ring} \myssec{Tree topology}{eval:tree} \input{eval-tree} \section{#1}% \label{sec:#2}% \input{#2}% } \newcommand{\myssec}[2]{% \subsection{#1}% \label{sec:#2}% } \newcommand{\rsec}[1]{% Sec.~\ref{sec:#1}% } \newcommand{\claudio}[1]{% \sethlcolor{cyan}{% {\it \hl{[CC] #1}}% }% } \newcommand{\todo}[1]{% \sethlcolor{yellow}{% \hl{#1}% }% } \newcommand{\added}[1]{% {\color{blue}#1% }% } \renewcommand{\added}[1]{#1} \newcommand{\removed}[1]{% {\color{red}#1% }% } \renewcommand{\removed}[1]{} \newcommand{\highpar}[1]{% \noindent\colorbox{yellow}{% \parbox{\dimexpr\linewidth-2\fboxsep {% #1 }% }% } \setlength{\algomargin}{2em} \newcommand{\myalgo}[2]{% \begin{algorithm}% {\small \include{algorithms/#1}% \caption{#2}% \label{algo:#1}% } \end{algorithm}% } \newcommand{\mytab}[2]{% \begin{table}[tbp]% \caption{#2}% \centering% \include{tables/#1}% \label{tab:#1}% \end{table}% } \newcommand{\mytabfull}[2]{% \begin{table*}[tbp]% \caption{#2}% \centering% \include{tables/#1}% \label{tab:#1}% \end{table*}% } \newcommand{\myfigeps}[3][width=3.1in]{% \begin{figure}[t]% \centering% \includegraphics[#1]{figures/#2}% \vspace{-1em}% \caption{#3}% \label{fig:#2}% \vspace{-1.5em}% \end{figure}% } \newcommand{\myfigfulleps}[3][width=\textwidth]{% \begin{figure*}[t]% \centering% \includegraphics[#1]{figures/#2}% \caption{#3}% \label{fig:#2}% \end{figure*}% } \newcommand{\myfigtex}[2]{% \begin{figure}[]% \centering% \input{figures/#1}% \caption{#2}% \label{fig:#1}% \end{figure}% } \newcommand{\rfig}[1]{Fig.~\ref{fig:#1}} \newcommand{\ralgo}[1]{Fig.~\ref{algo:#1}} \newcommand{\rtab}[1]{Table~\ref{tab:#1}} \newcommand{\req}[1]{Eq.~(\ref{eq:#1})} \newtheorem{lemma}{Lemma} \newenvironment{myinlinelist}% {% \begin{enumerate*}[label=(\roman*)]% }% {% \end{enumerate*}% } \newenvironment{myitemlist}% {% \begin{itemize}[parsep=0em,leftmargin=*,label={--}]% }% {% \end{itemize}% } \newenvironment{myenumlist}% {% \begin{enumerate}[parsep=0em,leftmargin=*,label=\arabic*.]% }% {% \end{enumerate}% }
{'timestamp': '2021-10-22T02:38:59', 'yymm': '2110', 'arxiv_id': '2110.10974', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.10974'}
arxiv
\section{Introduction} \label{sec:intro} The concept of \emph{geometric kernel} of a polygon, a polyhedron, or more generally of a shape, is a pillar of computational geometry. Intuitively, the kernel of a close, geometric shape $S$ is the locus of the points internal to $S$ from which the whole shape $S$ is visible. This concept is particularly interesting when applied to non convex polytopes, as for convex shapes the kernel coincides with the shape itself. In the simplest scenario, that is if the shape is a polygon, the standard way of computing its kernel is by intersecting appropriate half-planes generated from its edges. This problem has been tackled since 70s, when \cite{ShamosHoey} presented an efficient algorithm that performed the kernel computation in $O(e\log e)$ operations, where $e$ is the number of edges of a polygon, as the intersection of $e$ half-edges. After that, an optimal algorithm able to run in $O(n)$ operations, being $n$ the number of vertices of the polygon, has been proposed in \cite{LeePreparata}. Up to our knowledge, computational tools and libraries like \textit{Boost} \cite{BoostLibrary}, \textit{Geogram} \cite{levy2015geogram}, \textit{CGAL} \cite{fabri2009cgal}, or \textit{Libigl} \cite{jacobson2017libigl} implement routines to compute intersections between polygons and planes, which can be used to estimate the kernel. In the first attempts, for example in \cite{PreparataShamos}, the extension of the problem to the 3D case was treated only from a theoretical point of view. Starting from this perspective, the natural approach of extending of the 2D method (which we call the \textit{geometric approach)} was soon dismissed as unattractive for computational reasons. It was replaced by a new approach (which we call \textit{algebraic)} which makes use of linear algebra and homogeneous coordinates, and that is the state of the art for computing 3D kernels currently implemented by libraries like CGAL. During years, the polygon kernel computation has become popular to address several problems based on simple polygon analysis, such as star-component decomposition and visibility algorithms that are of interest in robotics, surveillance, geometric modeling, computer vision and, recently, in the emerging field of additive manufacturing \cite{demir2018near}. Today, the geometric kernel of a polytope is a pivotal information for understanding the geometrical quality of an element in the context of finite elements analysis. While in the past years finite elements methods were only designed to work on convex elements like triangles/tetrahedra or quadrangles/hexahedra \cite{ciarlet2002finite}, recent and more complex methods like the Mimetic Finite Difference Method \cite{lipnikov2014mimetic}, the Virtual Elements Method \cite{beirao2013basic}, the Discontinuous Galerkin Mehod \cite{cockburn2012discontinuous} or the Hybrid High Order Method \cite{di2019hybrid} are able to deal with non convex polytopes. This enrichment of the class of admissible elements led researchers to further investigate the idea of the geometric quality of a polytope, and to define quality measures and metrics for the elements of a mesh \cite{attene2021benchmark,sorgente2021role}. In this setting, the geometric kernel is often associated with the concepts of \textit{shape regularity} and \textit{star-shapedness} of an element. For example, as analyzed in \cite{sorgente2021vem}, most of the error estimates regarding the VEM (but the same holds for other polytopal methods) are based on the theory of polynomial approximation in Sobolev spaces, assuming the star-shapedness of the elements \cite{Brenner-Scott:2008,dupont1980polynomial}. As a consequence there are a number of sufficient geometrical assumptions on the computational domain for the convergence of the method, which require an estimate of the kernel. Mesh quality measures/metrics/indicators require to compute the kernel of thousands of polytopes, each of them with a limited number of faces and vertices, in the shortest possible time \cite{sorgente2021role}. In this paper we define an algorithm for the implementation of the geometric approach to the computation of the kernel of a polyhedron, and empirically show how this approach can significantly outperform the algebraic one when applied in the context of finite elements methods, with elements having a limited number of faces and vertices. The paper is organized as follows. In Section~\ref{sec:preliminary} we introduce and define the concept of kernel of a polytope in dimension 2 and 3. In Section~\ref{sec:kernel} we detail the algorithm for the construction of the kernel of a polyhedra. In Section~\ref{sec:examples} we exhibit some examples of computed kernels and analyze the performance of the algorithm, also with comparisons with an implementation of the algebraic approach. In Section~\ref{sec:conclusions} we sum up pros and cons of the algorithm and draw some conclusions. \section{Terminology and preliminary concepts} \label{sec:preliminary} Let us introduce some basic concepts, useful to the computation of the kernel of a polyhedron. Following the notation adopted in \cite{PreparataShamos}, a \textit{polyhedron} is defined by a finite set of plane polygons such that every edge of a polygon is shared by exactly one other polygon and no subset of polygons has the same property. The vertices and the edges of the polygons are the \textit{vertices} and the \textit{edges} of the polyhedron; the polygons are the \textit{faces} of the polyhedron. In this work we only consider \textit{simple} polyhedra, which means that there is no pair of nonadjacent faces sharing a point. A polyhedron $P$ is \textit{convex} if, for any two points $p_1$ and $p_2$ in $P$, the segment $(p_1,p_2)$ is entirely contained in $P$. It can be shown that the intersection of convex polyhedra is a convex polyhedron. Two points $p_1$ and $p_2$ inside $P$ are said to be \textit{visible} if the line segment connecting $p_1$ and $p_2$ does not intersect with the exterior of the $P$. It is easily seen that any two points inside a convex polyhedron are visible. The \textit{kernel} of a $P$ is the set of points from which all points inside $P$ are visible. Some polyhedra may not have a kernel, or we also say their kernel is empty. The polyhedron $P$ is called \textit{star-shaped} if there exists a sphere completely contained in its kernel. A polyhedron is not star-shaped if its kernel is empty. In Fig.~\ref{fig:tent} we present a parametric polyhedron shaped like a tent, with the parameter regulating the height of the "entrance". As the parameter increases, the set of points from which the whole polyhedron is visible becomes smaller, and so does the kernel. The last example of Fig.~\ref{fig:tent} is not star-shaped anymore, i.e. the kernel is empty. \begin{figure}[htbp] \centering \includegraphics[width=\linewidth]{pics/tent.png} \caption{Evolution of the kernel (in red) in a sequence of parametric polyhedra.} \label{fig:tent} \end{figure} In Section~\ref{sec:kernel} we will make use of the concept of \textit{signed distance}. Given a plane $p$ with unit normal vector $\boldsymbol n$ and a point $\boldsymbol p$ on it, the signed distance between a point $\boldsymbol x$ and the plane is given by the scalar product $d(\boldsymbol x, p) = \boldsymbol n\cdot(\boldsymbol p-\boldsymbol x)$. We say that $\boldsymbol x$ is strictly (weakly) below $p$ if $d(\boldsymbol x, p)<0$ $(\le0)$, $\boldsymbol x$ is strictly (weakly) above if $d(\boldsymbol x, p)>0$ $(\ge0)$, and $\boldsymbol x$ is on $p$ if $d(\boldsymbol x, p)=0$. \subsection{Geometric vs algebraic approach} \label{subsec:geometric_algebraic} The state of the art algorithm in the 2D case follows a geometric approach: the kernel of a polygon is found as the intersection of half-planes originating from its edges. We use the term "geometrical" because the algorithm computes repeatedly a sequence of geometric intersections between polygons and planes. This idea was optimized until obtaining an algorithm able to run in $O(n)$ operations, which has been proven to be optimal. One natural way to define a method for the 3D kernel computation is to extend the 2D algorithm, which is well studied and documented, to the upper dimension. The problem with the 3D case is that whereas two convex polygons with respectively $n_1$ and $n_2$ vertices can be intersected in time $O(n)$, being $n=n_1+n_2$, two convex polyhedra with the same parameters are intersected in time $O(n\log n)$, thus the generalization of the two-dimensional instance would yield an $O(n\log^2 n)$ algorithm. This is in contrast with the result shown in \cite{PreparataShamos}, where a lower bound for the intersection of convex polyhedra is established at $O(n\log n)$. This brought to the definition of a new algorithm based on the so-called "double duality trick", which makes use of linear algebra and homogeneous coordinates, able to compute the intersection of $n$ half-spaces in time $O(n\log n)$ \cite{PreparataShamos}. This algebraic approach can be implemented inside the framework of the CGAL library, although there is currently not an explicit routine for computing the kernel of a polyhedron and one has to connect the function for the intersection of half-spaces to the polyhedron data structure. While from a theoretical point of view the cited results are indubitable, we believe that in many practical situations the geometric approach could perform better than the algebraic one. Intuitively, if the number of faces and vertices of the polyhedron is low, this method can be more efficient than the algebraic one, as the cost of solving a linear problem does not go under a certain bound while the intersection of half-spaces can become extremely cheap if performed intelligently. \section{Computing the kernel of a Polyhedron} \label{sec:kernel} In this section, we induce our method for computing the kernel of a polyhedron. It has a modular structure composed of four nested algorithms, each one calling the next one in its core part. It is modular in the sense that each algorithm can be entirely replaced by another one performing the same operation(s). For instance, one could use another strategy for computing the intersection between a polygon and a plane and simply replace Algorithm~\ref{alg:polygon-plane} (and Algorithm~\ref{alg:line-plane} if not needed). In the next subsections we adopt the following data structure inherited by the \textit{cinolib} library \cite{livesu2019cinolib}, in which the code has been written: \begin{itemize} \item \textit{Polyhedron:} class composed by a field \textit{verts} containing the vertices (in 3D coordinates) and a field \textit{faces} containing the faces of a polyhedron. \item \textit{Points:} array of unordered 3D points. \item \textit{Face:} array of unsigned integers representing the indices of the vertices of a face, ordered counter-clockwise. \item \textit{Plane:} class composed by a 3D point $d$ indicating a random point on the plane, and a 3D point $n$ indicating the unit normal of the plane. \end{itemize} We point out that we always consider a plane $p$ together with the direction indicated by its normal vector $p.n$, which is equivalent to considering the half-space originating in $p$ and containing $p.n$. \subsection{Polyhedron Kernel} \label{subsec:polyhedron_kernel} Algorithm~\ref{alg:kernel} tackles the main problem: given a polyhedron $P$, we want to find the polyhedron $K$ representing the kernel of $P$. We will also need as input an array containing the outwards normals of the polyhedron faces, as it is not always possible to compute the orientation of a face only from its vertices (for example with non-convex faces). We start by defining $K$ as the axis aligned bounding box (AABB) of $P$, i.e. the box with the smallest volume within which all the vertices of $P$ lie, aligned with the axes of the coordinate system. We then recursively "cut" this box with a number of planes. For each face $f$ of $P$ we compute the plane $p$ which contains it, with the orientation given by the opposite of its normal $N(f)$ (that is to say, $p.n=-N(f)$). In general $p$ will separate $K$ into two polyhedra, and between those two we choose the one containing the vector $p.n$, which points towards the interior of $K$. This operation is performed by the \textit{Polyhedron-Plane-Intersection} algorithm detailed in Section \ref{subsec:polygon_plane}, which replaces $K$ with the chosen polyhedron. We point out that cutting a convex polyhedron with a plane will always generate two convex polyhedra, and since we start from the bounding box (which is convex), we are guaranteed for $K$ to be always a convex polyhedron. We could as well start with considering the polyhedron's convex hull instead of its bounding box, but it would be less efficient because the convex hull costs in general $O(n\log n)$ while the AABB is $O(n)$. Note that even if we used the convex hull, we would still need to intersect the polyhedron with each of its faces. As we iterate through the faces, we generate a sequence of convex polyhedra $K_i$, $i=1,\dots,\#$\textit{faces}, such that $K_i\subseteq K_{i-1}$. No matter how weird the initial element $P$ is, from this point on we will only be dealing with convex polyhedra and convex faces. \begin{algorithm}[htbp] \caption{Polyhedron-Kernel} \label{alg:kernel} \begin{algorithmic}[1] \Require Polyhedron $P$, Points $N$ (faces normals); \Ensure Polyhedron $K$ \State $K$ := AABB of $P$; \For{Face $f$ in $P.faces$} \State Plane $p$ := plane containing $f$ with normal $-N(f)$; \State $K$ := Polyhedron-Plane-Intersection($K$, $p$); \EndFor \State \Return $K$; \end{algorithmic} \end{algorithm} \subsection{Polyhedron-Plane-Intersection} \label{subsec:polyhedron_plane} With the second algorithm we want to intersect a polyhedron $P$ with a plane $p$. This intersection will in general be composed of two polyhedra, and between these two we are interested in the one containing the normal vector of $p$ (conventionally called the one "above" the plane and indicated with $A$). This algorithm is inspired from \cite{ahn2008geometric}, where the authors define an algorithm for the intersection of a convex polyhedron with an half-space. \begin{figure}[htbp] \centering \begin{tabular}{cc} \includegraphics[width=.49\linewidth]{pics/clipping.png} & \includegraphics[width=.49\linewidth]{pics/capping.png}\\ (a) & (b) \end{tabular} \caption{Intersection of a polyhedron with a plane: (a) clipping and (b) capping of a cube.} \label{fig:polyhedron-plane} \end{figure} The first part of Algorithm~\ref{alg:polyhedron-plane} is called the "clipping" part (recalling the terminology from \cite{ahn2008geometric}) and consists in cutting each face of $P$ with the plane $p$, see Fig.~\ref{fig:polyhedron-plane}(a). We preliminarly evaluate the signed distances (defined in Section~\ref{sec:preliminary}) between the vertices of $P$ and the plane to understand their position with respect to $p$. Faces strictly below $p$ are discarded, faces weakly above $p$ are added to $A$ together with their vertices, and faces intersected by $p$ are split by the \textit{Polygon-Plane-Intersection} algorithm. While we visit every face only once, the same does not hold for vertices, hence we need to check if a vertex is already present in $A$ before adding it. This simple idea of processing in advance the faces which are only weakly above the plane resolves several implementation issues and in some cases significantly improves the efficiency of the algorithm. By doing this, we make sure that only the faces properly intersected by the plane are passed to Algorithm~\ref{alg:polygon-plane}, so that we do not need to implement all the particular cases of intersections in a single point or along an edge or of faces contained in the plane. In addition, for every face not passed to Algorithm~\ref{alg:polygon-plane} we have an efficiency improvement, and this happens frequently in models with many coplanar faces like the ones considered in Section~\ref{subsec:refinements}. If at the end of this step $p$ intersects $A$ in more than two points, given that $A$ and all its faces are convex, the vertices shared by $p$ and $A$ will define a "cap" face of $A$ completely contained in $p$, see Fig.~\ref{fig:polyhedron-plane}(b). In order to sort counter-clockwise the points contained in \textit{capV} we project them onto a plane and apply the algorithm proposed in \cite{baeldung} for 2D points. Note that if the cap face was not convex it would make no sense to order its vertices, but the intersection between a plane and a convex polyhedron will always generate convex faces. Last, we need to check that this face is not already present in $A$: for example if $p$ is tangent to $P$ along a face, this face could be added to $A$ both as an intersection face and as a cap face. If this is not the case we add \textit{capF} to $A.faces$, but we do not need to add any vertex from \textit{capV}, as we can assume they are all already present in $A.verts$. \begin{algorithm}[htbp] \caption{Polyhedron-Plane-Intersection} \label{alg:polyhedron-plane} \begin{algorithmic}[1] \Require Polyhedron $P$, Plane $p$ \Ensure Polyhedron $A$ \State evaluate the position of all points in $P.verts$ with respect to $p$; \For{Face $f$ in $P.faces$} \State Points $f_v=$ vertices in $P.verts$ relative to $f$; \If{all vertices in $f_v$ are strictly below $p$} continue; \ElsIf{all vertices in $f_v$ are weakly above $p$} \State $A.verts\leftarrow$ $f_v$, $A.faces\leftarrow f$; \Else \State \textit{aboveV},\textit{aboveF}:=Polygon-Plane-Intersection$(f_v,f,p)$; \State $A.verts\leftarrow$ \textit{aboveV}, $A.faces\leftarrow$ \textit{aboveF}; \EndIf \EndFor \State Points \textit{capV}:= vertices in $A.verts$ which are on $p$; \If{size(\textit{capV})$<3$} return $A$; \EndIf \State Face \textit{capF} := \textit{capV} indices ordered counter-clockwise; \If{\textit{capF} $\notin$ $A.faces$} $A.faces\leftarrow$ \textit{capF}; \EndIf \State \Return $A$; \end{algorithmic} \end{algorithm} \subsection{Polygon-Plane-Intersection} \label{subsec:polygon_plane} Algorithm~\ref{alg:polygon-plane} describes the intersection of a polygon (representing a face of the polyhedron), defined by an array of 3D points \textit{polyV} and an array of indices \textit{polyF}, with a plane $p$. In analogy to Algorithm~\ref{alg:polyhedron-plane}, the intersection will in general produce two polygons and we are only interested in the one above the plane, see Fig.~\ref{fig:polygon-line-plane}(a), defined by vertices \textit{aboveV} and indexes \textit{aboveF}. We generically say that a vertex $v$ is added to \textit{above} meaning that $v$ is added to \textit{aboveV} and its index $id_v$ is added to \textit{aboveF}. We preliminarly evaluate the signed distances between the vertices of the polygon and the plane to understand their position with respect to $p$. Then we iterate on the edges of \textit{poly}: in order to avoid duplicates, for each couple of consecutive vertices $v_1, v_2$, we only accept to add to \textit{above} the second vertex $v_2$ or the intersection vertex $v$, but never $v_1$. When applying the algorithm recursively, as in the case of kernel computation, this idea requires to have all faces oriented coherently. If both vertices are strictly below $p$ we ignore them, unless $v_2$ lies exactly on the plane, in which case we add it to \textit{above}. If they are both above or on $p$ we add $v_2$ to \textit{above}, otherwise we perform the \textit{Line-Plane-Intersection} algorithm and find a new vertex $v$. Its index $id_v$ will be equal to the maximum value in \textit{polyF} plus one, just to make sure that we are not using the index of an existing vertex. Now, if $v_1$ is above $p$ (and consequently $v_2$ is below) we only add $v$ to \textit{above}, while if $v_1$ is below $p$ (and $v_2$ is above) we add both $v$ and $v_2$. As already noted in Section~\ref{subsec:polyhedron_plane}, treating separately the weak intersections makes the code simpler and more efficient. \begin{figure}[htbp] \centering \begin{tabular}{cc} \includegraphics[width=.4\linewidth]{pics/polygon-plane.png} & \includegraphics[width=.4\linewidth]{pics/line-plane.png}\\ (a) & (b) \end{tabular} \caption{(a) Intersection between a polygon and a plane, with the above part coloured in green. (b) Intersection between a line and a plane.} \label{fig:polygon-line-plane} \end{figure} \begin{algorithm}[htbp] \caption{Polygon-Plane-Intersection} \label{alg:polygon-plane} \begin{algorithmic}[1] \Require Points \textit{polyV}, Face \textit{polyF}, Plane $p$. \Ensure Points \textit{aboveV}, Face \textit{aboveF}. \State evaluate the position of all points in \textit{polyV} with respect to $p$; \For{$i=1$ : size(\textit{polyF})} \State $id_1:=$ \textit{polyF}$(i)$, $id_2:=$ \textit{polyF}$(i+1)$; \State $v_1:=$ \textit{polyV}$(id_1)$, $v_2:=$ \textit{polyV}$(id_2)$; \If{$v_1$ and $v_2$ are strictly below $p$} \State continue; \ElsIf{$v_1$ is weakly below $p$ and $v_2$ is on $p$} \State \textit{aboveV} $\leftarrow v_2$, \textit{aboveF} $\leftarrow id_2$; \ElsIf{$v_1$ and $v_2$ are weakly above $p$} \State \textit{aboveV} $\leftarrow v_2$, \textit{aboveF} $\leftarrow id_2$; \Else \State $v:=$ Line-Plane-Intersection$(v_1,v_2,p)$; \State $id_v:=$ max(\textit{polyF})+1; \If{$v_1$ is strictly above $p$} \State \textit{aboveV} $\leftarrow v$, \textit{aboveF} $\leftarrow id_v$; \Else \ \State \textit{aboveV} $\leftarrow v$, \textit{aboveF} $\leftarrow id_v$; \State \textit{aboveV} $\leftarrow v_2$, \textit{aboveF} $\leftarrow id_2$; \EndIf \EndIf \EndFor \State \Return \textit{aboveV}, \textit{aboveF}; \end{algorithmic} \end{algorithm} \subsection{Line-Plane-Intersection} \label{subsec:line_plane} This last algorithm returns the intersection point between a line, given as a couple of vertices, and a plane. It is a very simple and well known procedure, and we report it here only for completeness. The intersection vertex $v$ is defined by a linear combination of $v_1$ and $v_2$, with a coefficient $t$ which may also fall outside the standard range $[0,1]$. The only difficulty lies in the definition of $t$, which is the negative ratio between two scalar products involving the plane normal $p.n$ and a generic other point on the plane, $p.s$, other than $v_1$ and $v_2$, see Fig~\ref{fig:polygon-line-plane}(b). If the denominator $D$ vanishes, it means that either the line does not intersect the plane or that the line is contained in it: we treat these exceptions as errors because in Algorithm~\ref{alg:polygon-plane} we only call this algorithm after checking that the edge $(v_1,v_2)$ properly intersects the plane $p$. \begin{algorithm}[htbp] \caption{Line-Plane-Intersection} \label{alg:line-plane} \begin{algorithmic}[1] \Require vertices $v_1,v_2$, Plane $p$. \Ensure vertex $v$. \State $N:=(p.n)\cdot(v_1-p.s)$; \State $D:=(p.n)\cdot(v_2-v_1)$; \If{$D=0$ \ \& \ $N\neq0$} error: no intersections; \ElsIf{$D=0 \ \& \ N=0$} error: line contained in the plane; \EndIf \State $t:=-N/D$; \State \Return $v:=v_1+t(v_2-v_1)$; \end{algorithmic} \end{algorithm} \subsection{Computational complexity} \label{subsec:computational_complexity} Making advantage of the modularity of our algorithms, we can estimate separately the computational cost of each algorithm and then include them into a single formula. We start with a polyhedron $P$ with $n_v$ vertices and $n_f$ faces. For Algorithm~\ref{alg:kernel} we need to compute its AABB, which is $O(n_v)$, and then perform Algorithm~\ref{alg:polyhedron-plane} for $n_f$ times, therefore $N_1=n_v+n_f N_2$. In Algorithm~\ref{alg:polyhedron-plane} we receive as input a polyhedron which is potentially different from $P$, but we empirically measured that the number of vertices and faces remain approximately constant when applying this routine. We preliminarly compute $n_v$ signed distances; then, only in the cases in which the vertices of a face do not all lie by the same side, run Algorithm~\ref{alg:polygon-plane}. If only $m_1$ faces needs to be cut (with $m_1<n_f$), the clippping part takes $n_v + m_1 N_3$ operations. If we have a cap face (which is not always true) with $n_{vc}$ verts, we need to sort them with a QuickSort routine which is on average $O(n_{vc}\log n_{vc})$. Altogether, Algorithm~\ref{alg:polyhedron-plane} takes $N_2 =n_v + m_1 N_3 + n_{vc}\log n_{vc}$ operations. Given a face $f_i$ with $n_{vi}$ vertices, in Algorithm~\ref{alg:polygon-plane} we start by computing $n_{vi}$ signed distances. Then, if only $m_2$ of the edges intersect the plane (where $m_2<n_{vi}$), perform Algorithm~\ref{alg:line-plane}. This means that $N_3=n_{vi}+m_2 N_4$, and Algorithm~\ref{alg:line-plane} only consists of 4 operations. Collecting all costs together, we obtain: \begin{align*} N_4 &= 4;\\ N_3 &= n_{vi}+4m_2;\\ N_2 &= n_v + m_1 \left(n_{vi}+4m_2\right) + n_{vc}\log n_{vc};\\ N_1 &= n_v+n_f \left(n_v + m_1 \left(n_{vi}+4m_2\right) + n_{vc}\log n_{vc}\right);\\ &=n_v+n_f \left(n_v + C\right). \end{align*} Let us focus our attention on the term $C$. Since $m_2\le n_{vi}$ and $n_{vc}$ is the number of vertices of the cap face, we can substitute them with an average $n_a$ of the number of vertices per face and get $C=m_1 n_a + n_a\log n_a$. For the very majority of the considered models (especially the more complex ones) we can assume that both $m_1$ and $n_a$ are negligible compared to $n_v$: a plane can intersect a polyhedron in a very limited number of its faces, and the average number of vertices per face is significantly smaller than the total number of vertices. The term $C$ can therefore be included in $n_v$, and as a realistic approximation of the computational cost we get $O(n_v(1+n_f))$. \section{Examples and discussions} \label{sec:examples} \begin{figure*}[ht!] \centering \begin{tabular}{c} \includegraphics[width=\linewidth]{pics/tet10.png} \\ \includegraphics[width=\linewidth]{pics/tet30.png} \\ \includegraphics[width=\linewidth]{pics/voro.png} \end{tabular} \caption{Polyhedra and kernels from datasets \textit{tet10}, \textit{tet30} and \textit{voro}.} \label{fig:dataset} \end{figure*} In this section we test our method over a collection of polyhedra, comparing its performance to the results obtained using our implementation of the algebraic method in CGAL. Experiments have been performed on a MacBook Pro equipped with a 2,3 GHz Intel Core i5 processor with four CPUs and 16GB of RAM. Source code is written in C++ and it is accessible at \url{https://github.com/TommasoSorgente/polyhedron_kernel} together with all datasets. \subsection{Collections of polyhedral elements} \label{subsec:datasets} As an initial test we built four datasets containing 1000 non-convex polyhedra each, simulating a typical configuration in which a tessellation of a complex 3D computational domain come with non-convex elements. As elements of a tessellation on which to perform numerical simulations, they typically present a fairly simple shape and possess a fairly limited number of vertices. A gallery of examples is visible in Fig.~\ref{fig:dataset}. The first three are denoted \textit{tet10}, \textit{tet20} and \textit{tet30}, where the number indicates the number of vertices of the contained polyhedra. Each polyhedron is built by sampling the relative number of points randomly in the space and connecting them in a Delaunay tetrahedalization using \textit{Tetgen} \cite{si2015tetgen}. Then one vertex is moved to the polyhedron's centroid, in order to get a non convex element. Note that \textit{Tetgen} outputs the convex hull of the Delaunay tetrahedralization of a set of points, therefore the initial polyhedron is guaranteed to be convex, its centroid is guaranteed to lie inside its volume and the operation of moving a vertex towards the polyhedron centroid does not generate connectivity problems. The fourth dataset, \textit{voro}, contains 1000 random non-convex polyhedra with non-triangular faces. For building each polyhedron we start from a Voronoi cell and triangulate the face with the largest area connecting the face vertices to the face centroid. Then we move the face centroid to the polyhedron centroid to obtain a non convex element. It is not possible to know a priori the exact number of vertices of each Voronoi cell, but after the definition of dataset \textit{voro} we measured that the number of vertices of its elements ranges from 5 to 20. \begin{table}[htbp] \caption{Computational times for estimating the kernel on the whole dataset (in seconds) and ratio between the CGAL time and ours.} \label{table:time:dataset} \centering \begin{tabular}{ccccc} \hline\noalign{\smallskip} dataset & $\#$vertices & our & CGAL & ratio\\ \noalign{\smallskip}\hline\noalign{\smallskip} \textit{tet10} & 10 & 0.29 & 2.49 & 8.58 \\ \textit{tet20} & 20 & 0.49 & 3.62 & 7.39 \\ \textit{tet30} & 30 & 0.63 & 4.49 & 7.13 \\ \textit{voro} & 5-20 & 0.24 & 1.92 & 8 \\ \noalign{\smallskip}\hline \end{tabular} \end{table} We measure the computational time needed to estimate the kernels of all polyhedra in each dataset and compare it with the performance of the CGAL library in Table~\ref{table:time:dataset}. On this kind of polyhedra, the geometrical approach performs significantly better (between seven and eight times) than the algebraic one. This may be due to the fact that, with a limited number of planes, computing the geometric intersection between them is cheaper than solving a linear problem. As the number of vertices increases the difference between the two approaches becomes smaller. \subsection{Refinements} \label{subsec:refinements} As a second setting for our tests we wanted to measure the asymptotic behaviour of our method as the number of vertices increases. We considered two polyhedra taken from the dataset \textit{Thingi10K} \cite{zhou2016thingi10k}: the so-called \textit{laser-chess} and \textit{flex}. These models are given in the form of a surface mesh and we treat them as single volumetric cell, analyzing the performance of our algorithm as we refine them. \begin{figure}[th] \centering \includegraphics[width=.8\linewidth]{pics/laser_chess.png} \caption{Original laser-chess model and its third refinement. The kernels are identical.} \label{fig:laser-chess} \end{figure} The \textit{laser-chess} model is extremely simple, being defined by only eight planes. Even refining its faces with a midpoint strategy, the planes induced by its faces remain identical and the kernels of the refined models are all equal (Fig.~\ref{fig:laser-chess}). On this example our method performs on average 6.8 times better that the algebraic method (see Table~\ref{table:time:refinements}), and the computational time scales with a constant rate (see the red lines in Fig.~\ref{fig:rate}). Our implementation takes advantage of the fact that Algorithm~\ref{alg:polyhedron-plane} recognises coplanar faces and performs Algorithm~\ref{alg:polygon-plane} only eight times, independently of the number of faces. \begin{figure}[htbp] \centering \includegraphics[width=.95\linewidth]{pics/flex.png} \caption{Original flex model and its third refinement. Small perturbations in the faces lead to slightly different kernels.} \label{fig:flex} \end{figure} The \textit{flex} model is more complex, as it presents a curved surface which generates a lot of different planes defining the kernel. Moreover, we refined this model using the Loop's algorithm and this generated faces lying on completely new planes. This explains the difference between the two kernels in Fig.~\ref{fig:flex}. Our geometric method improves the performance of the algebraic one by one order of magnitude, even if the difference between the two approaches decreases (from 13 times to 9, see Table.~\ref{table:time:refinements}) as the number of vertices increases. \begin{table}[htbp] \caption{Computational times for the laser-chess and flex refinements (in seconds) and ratio between the CGAL time and ours.} \label{table:time:refinements} \centering \begin{tabular}{ccccc} \hline\noalign{\smallskip} mesh & $\#$vertices & our & CGAL & ratio \\ \noalign{\smallskip}\hline\noalign{\smallskip} \textit{laser-chess1} & 10 & 0 & 0.001 & 1 \\ \textit{laser-chess2} & 127 & 0.001 & 0.007 & 7 \\ \textit{laser-chess3} & 493 & 0.004 & 0.027 & 6.75 \\ \textit{laser-chess4} & 1945 & 0.017 & 0.11 & 6.47 \\ \textit{laser-chess5} & 7729 & 0.06 & 0.41 & 6.83 \\ \textit{laser-chess6} & 30817 & 0.24 & 1.73 & 7.21 \\ \hline \textit{flex1} & 834 & 0.026 & 0.35 & 13.46 \\ \textit{flex2} & 3130 & 0.097 & 1.17 & 12.06 \\ \textit{flex3} & 11216 & 0.45 & 5.1 & 11.33 \\ \textit{flex4} & 26560 & 1.33 & 14.19 & 10.67 \\ \textit{flex5} & 35566 & 2.31 & 22.1 & 9.57 \\ \textit{flex6} & 42659 & 3.57 & 33.26 & 9.32 \\ \noalign{\smallskip}\hline \end{tabular} \end{table} \begin{figure}[htbp] \centering \includegraphics[width=.8\linewidth]{pics/rate.png} \caption{Computational times for the refinement of the flex and laser-chess models. Time is expressed in milliseconds.} \label{fig:rate} \end{figure} \subsection{Complex models} \label{subsec:complex_models} \begin{figure*}[ht] \centering \includegraphics[width=\linewidth]{pics/complex.png} \caption{Examples of our kernel evaluation for complex models: \textit{bot-eye, rt4-arm, super-ellipse, playset, leg, fandisk}.} \label{fig:complex} \end{figure*} Last, we try to compute the kernel of some more complex models, taken again from the dataset \textit{Thingi10K} and treated as single volumetric cells. Note that most of the models in Thingi10K are not star-shaped, thus making it useless to compute their kernels. Even if our method is designed for dealing with a large number of simple polyhedra (i.e., with a relatively small number of vertices), our algorithms are still able to compute the kernel of a whole object with thousands of vertices. In Fig.~\ref{fig:complex} we present the kernel computation of six complex objects, and the computational times are reported in Table~\ref{table:time:complex}. \begin{table}[th] \caption{Computational times for complex models (in seconds) and ratio between the CGAL time and ours.} \label{table:time:complex} \centering \begin{tabular}{ccccc} \hline\noalign{\smallskip} mesh & $\#$vertices & our & CGAL & ratio \\ \noalign{\smallskip}\hline\noalign{\smallskip} \textit{bot-eye} & 453 & 0.28 & 0.048 & 0.17\\ \textit{rt4-arm} & 655 & 0.21 & 0.11 & 0.52\\ \textit{super-ellipse} & 290 & 0.02 & 0.04 & 2\\ \textit{playset} & 1416 & 0.01 & 0.08 & 8\\ \textit{leg} & 87 & 0.003 & 0.03 & 10\\ \textit{fandisk} & 7229 & 0.07 & 3.58 & 51.14\\ \noalign{\smallskip}\hline \end{tabular} \end{table} We notice that the number of vertices of the element, by itself, is not strictly related to the efficiency of the method. Much more influence has the shape of the object: in accordance to the results of Section~\ref{subsec:refinements}, over simple models like \textit{leg} or models with numerous ajacent coplanar faces like \textit{playset} and \textit{fandisk} our method is preferable. Note in particular the different performance of the two methods over the \textit{fandisk} model, which has a high number of vertices. Vice versa, over elements with significant curvatures like \textit{bot-eye}, \textit{rt4-arm} or \textit{super-ellipse}, the algebraic method performs similarly or better than ours even on relatively small models. \section{Conclusions} \label{sec:conclusions} We presented an algorithm for the computation of the kernel of a polyhedron based on the extension to the 3D case of the geometric approach adopted in two dimensions. The algorithm showed up to be robust and reliable, as it computed successfully the kernel of every considered polyhedron. We compared its efficiency to the one of the algebraic approach to the problem, implemented in CGAL. From a theoretical point of view, the computational complexity evaluation of Section~\ref{subsec:computational_complexity} suggests that our method is in general quadratic, while the algebraic approach has a lower bound at $n\log(n)$. Nonetheless, we proved in Section~\ref{sec:examples} that in several circumstances our approach outperforms the algebraic one. Our method performs significantly better than the algebraic approach over polyhedra with a limited number of vertices and faces, as shown in Section~\ref{subsec:datasets}, making it particularly suitable for the analysis of volumetric tessellations with non-convex elements. Indeed, we point out that our algorithm is specifically designed to be used with simple polyhedra, possibly composing a bigger and more complex 3D model, and not with a complete model itself. When the size of the polyhedron increases, our method is still particularly efficient if the model has numerous coplanar faces, like in some of the complex examples in Section~\ref{subsec:complex_models}. This is a very common situation in models representing mechanical parts. On the other side the algebraic approach is preferable over curved domains, with numerous vertices and faces lying on different planes. In conclusion, with this work we do not aim at completely replacing the algebraic approach for the kernel computation but instead to give an alternative which can be preferred for specific cases, such as the quality analysis of the elements in a 3D tessellation, in the same way as bubble-sort is to be preferred to optimal sorting algorithms when dealing with very small arrays. As a future development, we plan to include this tool in a suite for the generation and analysis of tessellations of three dimensional domains, aimed at PDE simulations. The kernel of a polyhedron has a great impact on its geometrical quality, and the geometrical quality of the elements of a mesh determines the accuracy and the efficiency of a numerical method over it. We therefore plan to use this algorithm for better understanding the correlations between the shape of the elements and the performance of the numerical simulations, and be able to adaptively generate, refine or fix a tessellation accordingly to them. \section*{Acknowledgements} We would like to thank Dr. M. Manzini for the precious discussions and suggestions, and all the people from IMATI institute involved in the CHANGE project. Special thanks are also given to the anonymous reviewers for their comments and suggestions. This work has been partially supported by the ERC Advanced Grant CHANGE contract N.694515. \bibliographystyle{plain}
{'timestamp': '2021-10-28T02:20:54', 'yymm': '2110', 'arxiv_id': '2110.11054', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.11054'}
arxiv
\section{Introduction} \label{sec:intro} With the popularization of service robots and surveillance cameras, dynamic face recognition (DFR) in the wild has become widely used. DFR is different from static face recognition (SFR). In SFR such as Apple face ID, the aim is to recognize faces within a specific area or range with relatively high requirements for the angle, distance, and position, which often requires human cooperation. However, in DFR applications such as surveillance, the aim is to automatically recognize persons walking in natural forms, generally requiring no human cooperation. The traditional pipeline for DFR is to: 1) face detection and tracking; 2) head pose estimation and face image quality evaluation; 3) image selection based on the head pose and quality; 4) face identity comparison. The face recognition can be deployed on device with low computing power or cloud side. However, cloud service is often interrupted by unstable network connection and limited bandwidth. Therefore, real-time face detection and head pose estimation in mobile side become necessary for DFR in the wild. Face detection is a prerequisite step of facial image analysis such as facial attribute, e.g., expression ~\cite{zhang2018joint}, age ~\cite{pan2018mean} and face identity ~\cite{schroff2015facenet, liu2017sphereface, deng2019arcface}. With the recent development of deep learning, significant improvements have been achieved in face detection by utilizing CNN-based object detectors. Among these methods, single-stage based deep learning methods have shown to be promising ~\cite{zhang2018single,zhang2017s3fd,najibi2017ssh,tang2018pyramidbox}. The single-stage methods detect the faces of different scales without significant increment of time-consumption even when there is an increased number of faces in the images. These methods densely sample face locations and scales on feature pyramids ~\cite{liu2016ssd, lin2017feature}, demonstrating promising performance and yielding high speed. Very often, the five facial landmarks are localized simultaneously ~\cite{deng2019retinaface}. However, landmark localization is still insufficient for pose estimation in DFR due to poor accuracy for face with large angles. In this work, we propose a novel low latency and lightweight framework for real-time face detection, landmark localization and pose estimation. To avoid a large increment in computation, we propose to detect face, locate the landmarks and estimate the head pose simultaneously. There are three major challenges. Firstly, it is not an easy task to learn face detection, facial landmark localization and head pose estimation simultaneously and get accurate results for all tasks with low computational resources ~\cite{ranjan2017hyperface, deng2019retinaface}. Secondly, the existing datasets for face detection, facial landmark localization and head pose estimation are non-unified and inconsistent of the scales for joint training while it is difficult to obtain accurate pose annotations, especially for small faces ~\cite{zhuang2019fldet}. Lastly, false positive in face detection affects the user experience and it is very challenging to reduce it with low computational resources. Intuitively, attention area by pose estimation shall be consistent with that by face classification. Therefore, we train a multi-task network and utilize the feature maps to validate our assumption visually. The result shows that the attention area for pose estimation and classification are highly overlapped. This motivates us to integrate the pose estimation into face detection such that it may maintain or even improve the accuracy while reducing extra step for pose estimation. In addition, we observe that the landmark localization is more difficult in faces with large angles and propose an additional constraint called pose loss to regularize the training. In order to train a model for simultaneous face detection and head pose estimation, we further label the pose of each face for the WIDER FACE dataset, which will be released. The main contributions are summarized as follows: \begin{enumerate} \item We propose a low latency and lightweight architecture for face detection, facial landmark localization and head pose estimation simultaneously. \item We propose uncertainty multi-task loss to make the face detection, landmark localization and head pose estimation more accurate. \item We propose an online data-feedback augmentation strategy, which improves the data balance in face detection. \item The results show that our method outperforms other lightweight methods, especially for the \textit{hard} subset. \end{enumerate} \section{Related Work} \label{related} \begin{figure*} \centering \includegraphics[width=5in]{iccv_overall} \caption{ Overview of the proposed method. MOS adopts the feature pyramid from $P3$ to $P5$ followed by SSH context head module and a multi-task head module. A cross stitch unit ($n\times c$, $n$ denotes task number and $c$ denotes channel number) is used in the multi-task head to combine the feature maps linearly for face detection, landmark localization and head pose estimation. } \label{fig2} \end{figure*} \textbf{Face detection: }Face detection ~\cite{Yang2016WIDER,jain2010fddb} has been a hot topic in the past decades. Earlier methods ~\cite{viola2004robust} for face detection are mostly based on hand-crafted features. Existing methods are divided into two categories: two-stage methods (e.g. Faster R-CNN ~\cite{ren2015faster}) and single-stage methods (e.g. SSD ~\cite{liu2016ssd}). Single-stage methods have great advantages in inference speed, though these detectors often lead to higher false positive. There are some methods ~\cite{liu2020hambox,chi2019selective} that reduce the false positive detection by improving the quality of the matching box. Another problem is how to detect small faces. S3FD ~\cite{zhang2017s3fd} used multiple strategies to improve the performance of small faces. ProgressFace ~\cite{zhuprogressface} proposed a novel scale-aware progressive training mechanism to address large scale variations across faces. \textbf{Head pose estimation: }Head pose estimation has been widely studied. Early method uses the facial landmarks ~\cite{kazemi2014one, bulat2017far, zhu2016face, kumar2017kepler} to estimate the head pose. The methods based on facial landmarks and Perspective-n-Point (PnP) ~\cite{pnp1981} are very popular because there is no need to include a pose estimation model. However, the error in landmark localization will be propagated. Recently, CNN based methods for direct pose estimation made some progress. Hopenet ~\cite{2018Fine} combined ResNet50 with a multi-loss function, which is composed of a classification loss and regression loss. FSAnet ~\cite{2019FSA} proposed to learn a fine grained structure mapping for spatially grouping features before aggregation. Although some of these methods ~\cite{hsu2018quatnet,zhou2020whenet,dai2020rankpose} achieve excellent results on pose estimation, none of them is combined with face detection. \textbf{Multi-task learning: } The recent progress in multi-task learning mainly focuses on the shared network architecture ~\cite{misra2016cross} and the loss function weights of the tasks ~\cite{kendall2018multi}. In MTAN ~\cite{MTAN2019}, Liu \textit{et al.} proposed a new network based on SegNet ~\cite{badrinarayanan2017segnet} and obtained the state-of-the-art performance on the tasks of semantic segmentation and depth estimation on the outdoor CityScapes dataset ~\cite{cordts2016cityscapes}. There are some methods attempting to solve the problem of face detection and alignment in one model. In MTCNN ~\cite{zhang2016joint}, Zhang \textit{et al.} used a cascaded architecture with three stages of shallow networks to predict face and landmark locations in a coarse-to-fine manner. In RetinaFace ~\cite{deng2019lightweight}, Deng \textit{et al.} manually annotated five facial landmarks on the WIDER FACE dataset and observed significant improvement in \textit{hard} subset with the assistance of this extra supervision. There are also some efforts to include head pose estimation and other face attributes~\cite{zhang2014facial,ranjan2017hyperface}. Ranjan \textit{et al.} ~\cite{ranjan2017hyperface} presented an algorithm for simultaneous face detection, landmark localization, head pose estimation and gender recognition, which shows that the multi-task learning can get better results. However, these methods use hard parameter connection, which limits the feature sharing among different tasks. \section{Method} \label{method} In this paper, we propose a low latency and lightweight framework including the following sub-tasks: face classification, bounding box regression, landmark regression and head pose estimation. Fig. \ref{fig2} shows the overview of the proposed method. \subsection{Multi-Task Head} Most of the multi-task branches of face detection \cite{deng2019retinaface,ranjan2017hyperface,zhang2016joint} are forked from the last layer directly, and therefore these sub-tasks actually share all the previous features. Fig. \ref{fig3a} shows the baseline head module \cite{deng2019retinaface, ranjan2017hyperface} with hard parameter connection. Although some correlation exists between them, there are still many differences among the sub-tasks. For example, landmark regression pays more attention to the location of each landmark while bounding box regression pays more attention to the edge of face area \cite{zhuang2019fldet}. Inspired by the above, we propose a novel head sharing unit called multi-task head (MTH). The MTH units try to find the best shared representations for multi-task learning. Different heads share representations through linear combinations and learn the optimal combinations for these tasks. Fig. \ref{fig3a} shows the structure of MTH Different from the baseline head module \cite{deng2019retinaface, ranjan2017hyperface} with hard parameter connection, we further include a cross stitch unit size of $n\times c$ in Fig. \ref{fig3a}, where $n$ denotes the number of tasks and $c$ denotes the number of channels. It computes a linear combination of feature maps followed by additional $1\times 1$ convolutions. It shall be noted that the cross stitch unit here is different from that in \cite{misra2016cross}. In our unit, we use channel-wise weights in each channel while shared values were used in \cite{misra2016cross}. \begin{figure}[htb] \centering {\subfigure[The different connection method of head modules]{ \includegraphics[width=2.1in,height=2in]{mthnew618} \label{fig3a} }} {\subfigure[ The pipeline of online feedback sampling]{ \includegraphics[width=2in,height=2in]{stitcher} \label{fig3b} }} \caption{(a) The top figure is the baseline head module with hard parameters connection; The bottom is the proposed MTH module with cross-connection. (b) Online Feedback Sampling: Compute $L_{box}^s$ for faces no larger than $25\times 25$ and apply stitching accordingly after every iteration, and value $T$ is set to 0.35; Update the set $S$ after every epoch. The yellow and red boxes in the test image refer to false detection and correct detection respectively. The images will be added into the set $S$ according to the number of false detection boxes. } \label{fig3} \end{figure} \subsection{Multi-task Loss} \subsubsection{Loss functions used for the tasks} \textbf{The classification loss } is a softmax loss for binary classification denoted as $L_{cls}(p_{i},p_{i}^{*})$, where ${p}_{i}$ is the predicted probability of anchor ${i}$ being a face and ${p}_{i}^{*}$ is 1 for the positive anchor and 0 for the negative anchor. \textbf{The bounding box regression loss } is a Smooth $\ell_1$ loss \cite{girshick2015fast} denoted as $L_{box}(t_{i},t_{i}^{*})$, where ${t}_{i}=({t}_{x},{t}_{y},{t}_{w},{t}_{h})$ and ${t}_{i}^{*}=({t}_{x}^{*},{t}_{y}^{*},{t}_{w}^{*},{t}_{h}^{*})$ represent the coordinates of the predicted box and ground-truth box associated with the positive anchors respectively. \textbf{The landmark regression loss } $L_{pts}(l_i, l_{i}^*)$ is also based on Smooth $\ell_1$, where $l_i=\{l_{x_1}, l_{y_1}, \cdots, l_{x_5}, l_{y_5} \}$ and $l_i^*=\{l_{x_1}^*, l_{y_1}^*, \cdots, l_{x_5}^*, l_{y_5}^* \}$ represent the predicted landmarks and ground truth with the positive anchors respectively. \textbf{Head Pose estimate loss: } Previously, a regression loss $L_{pose}$ based on cross entropy and mean square error is used for pose estimation \cite{2018Fine}. \begin{equation} L_{pose}=H{(a,\hat{a})}+\beta \cdot MSE(a,\hat{a}), \end{equation} where ${H{(a,\hat{a})}}$ denotes the cross entropy, $MSE$ denotes the mean square error, $a$ and ${\hat{a}}$ denote the annotated bins and the predict bins. Similar to that in \cite{2018Fine}, we use 66 bins, ${\beta}$ is set to 0.001. \subsubsection{Uncertainty Multi-task Loss} The weights in multi-task learning are set empirically in RetinaFace \cite{deng2019retinaface} and MTCNN \cite{zhang2016joint}. Recently, some work utilizes the uncertainty to estimate the output in the generic object detection \cite{he2019bounding, kendall2018multi}. In this work, we derive a uncertainty multi-task loss (UML) function by maximizing the overall likelihood with the network. Let $f^{W}(x)$ be the output of a neural network with input $x$ and weights $W$. The multi-task likelihood is defined as the multiplication of single-task probabilities. In this work, we have one classification task and three regression tasks. \begin{equation p(y|f^{W}(x))=p(y_{1}|f^{W}(x))...p(y_{4}|f^{W}(x)), \label{eq3} \end{equation} where $y=(y_{1},...,y_{4})$ denotes the distribution of the four tasks. In maximum likelihood estimation, we compute the log likelihood of the model: \begin{equation \log(p(y|f^{W}(x)))=\sum_{k=1}^{4}\log(p(y_{k}|f^{W}(x))) \end{equation} Following \cite{kendall2018multi}, the classification likelihood is defined as Boltzmann distribution function: \begin{equation p(y_{cla}|f^{W}(x))=\mathtt{Softmax}(\frac{1}{T^2}f^{W}(x)), \end{equation} where the subscript ${cla}$ denotes the classification task. $T$ is temperature of the system. The uncertainty loss of classification task ${L_{cla}^*(W,T)}$ is computed as: \begin{equation L_{cla}^*(W,T) =\frac{1}{T^2}L_{cla}(W)+\log(T), \end{equation} The cross entropy loss without coefficient $T$ can be defined as $L_{cla}(W)$, and it represents the loss function of the classification task without the temperature factor $T$. The likelihood of a regression task can be defined as a Gaussian with the mean given by the model output $N(f^{W}(x),\sigma^{2})$, where $\sigma$ is the model's observation noise parameter. The uncertainty loss of the regression task $L_{reg}^*(W,\sigma)$ is computed as : \begin{equation L_{reg}^*(W,\sigma)\propto\frac{1}{2\sigma^2}L_{reg}(W)+\log(\sigma), \label{eq7} \end{equation} Where $L_{reg}(W)$ denotes the $L_2$ norm of the regression task, including two bounding box regression tasks, a landmark regression task and pose estimation task in this work. Applying (\ref{eq3})-(\ref{eq7}) on the losses of individual tasks, we compute the overall loss function $L^{*}$ as: \begin{equation \begin{aligned} L^{*} =\frac{1}{T_1^2}p_i^*L_{cls}+\frac{1}{2\sigma_1^2}p_i^*{L_{box}}+ \frac{1}{2\sigma_2^2}p_i^*{L_{pts}}+ \frac{1}{2\sigma_3^2}p_i^*{L_{pose}}+\log(T_1\sigma_1\sigma_2\sigma_3) \end{aligned}, \end{equation} where $T_1$ is the temperature of the classification task, $\sigma_1, \sigma_2, \sigma_3$ are the observation noise of the bounding box detection, landmark regression and pose estimation tasks. These parameters are obtained through learning. \subsection{Online Feedback Sampling} Some methods improve the accuracy of small face by changing the distribution of face samples. In PyramidBox++ \cite{li2019pyramidbox++}, Li \textit{et al.} propose to resize the images into different scales evenly. These strategies are beneficial for multi-scale sample training, but it needs empirical parameters to prevent the network from over-fitting. In this work, we propose an online feedback method for data augmentation. An illustration of the algorithm is shown in Fig. \ref{fig3b}. In the method, the training data is adjusted dynamically according to the actual effect in each iteration, which is beneficial to keep a balance on face scales. In our method, we construct a set $S$ which starts from all training samples for face detection. In each iteration, we calculate the loss $L_{box}^s$ of face size less than $25\times 25$. The stitching strategy is used if the ratio of $L_{box}^s/L_{box}$ is less than value $T$. After each epoch, we test the current model on the training data and obtain all images with false positive and false negative boxes. Then we update $S$ with these difficult images. In this way, the proposed method improves the balance of the data automatically. \section{Experiments} \label{experiments} \subsection{Implementation details} \textbf{Training Dataset:}The first dataset we use is the WIDER FACE dataset \cite{Yang2016WIDER}. It consists of 32,203 images and 393,703 face bounding boxes. As the original dataset does not contain pose labels, we first annotate the pose for the dataset. Head pose annotation from 2D images is an extremely challenging and time-consuming task, especially for very small faces. In our annotation, we annotate in a semi-supervised way and skip faces smaller than $35\times 35$ pixels. We first pre-label the data through FSAnet \cite{2019FSA} and Hopenet \cite{2018Fine}, and then two trained experts adjust the pre-labelled annotations manually after careful examination and mutual agreement. In our annotation, we mainly adjust the Yaw, which is most important for DFR. To facilitate the research in this area, we are preparing the data for release and the data will be available at https://github.com/lyp-deeplearning/MOS-Multi-Task-Face-Detect. \textbf{Evaluation Metrics:}The AFLW \cite{koestinger2011annotated} dataset is used to test the landmark localization accuracy. It contains 25993 faces with up to 21 landmarks per image. The evaluation is based on the mean errors measured by the distances between the estimated landmarks and the ground-truth, normalized with the face box size $\sqrt{w\times h}$. We conduct testing of Head Pose estimate on AFLW2000 \cite{zhu2016face} dataset. It provides ground-truth 3D faces with pose angles for the first 2,000 images of the AFLW dataset. We follow the protocol of Hopenet ~\cite{2018Fine}. \textbf{Model architecture and training protocols: } We implement MOS-S based on lightweight backbone ShuffleNet V2 \cite{ma2018shufflenet}. MOS-S employs three feature pyramid levels from $P3$ to $P5$. The backbones are pretrained on the Imagenet. We use online hard example mining \cite{shrivastava2016training} and constrain the ratio of positive and negative anchors to 1:3. The SSH \cite{najibi2017ssh} module is added to increase the receptive field. The anchor aspect ratio is set to 1:1. In MOS-S, we train the model with 640$\times$640 input images, the feature pyramid is set to $P3(80\times80)$, $P4(40\times40)$, $P5(20\times20)$, which leads to 16800 anchors. Although we mainly focus on the lightweight backbones, we also implement MOS-L with heavy backbone ResNet152 \cite{he2016deep} to explore the performance of the proposed modules in this situation. We train the face detection networks with a batch size of 64 using 1 NVIDIA Tesla V100 GPUs. We use SGD optimizer with momentum at 0.9, weight decay at 0.0005. The initial learning rate is set to 0.001 and then divided by 10 at 150 and 180 epochs. The training terminates at 200 epochs. For inference, we use multi-scale testing strategy as in \cite{zhang2017s3fd}. \subsection{Ablation Study} To justify the effectiveness of each component in MOS-S, we conduct the following ablation studies. The baseline approach is based on ShuffleNet V2 and SSH without MTH, as shown in Fig. \ref{fig2} and Fig. \ref{fig3a}. Then we add the four modules including MTH, Pose loss, UML, Online Feedback and the commonly used deformable convolution network (DCN) \cite{dcnv2} one by one. The results are shown in Table \ref{table2}. \begin{table}[] \footnotesize \caption{Ablation study of the proposed modules on the WIDER FACE validation set and AFLW2000 ~\cite{zhu2016face}. The baseline adopts the the hard connect structure in Fig. \ref{fig3a} with MOS-S.} \begin{center} \begin{tabular}{lcccc}\hline {Method} & Easy & Medium & Hard & Avg. MAE \\ \hline Baseline & 89.32 & 88.45 & 80.20 & 6.73 \\ {+ MTH} & 90.11 & 89.31 & 81.64 & 6.49 \\ {+ UML} & 91.18 & 90.26 & 83.01 & 6.14 \\ {+ Online Feedback} & 92.41 & 91.37 & 85.24 & 6.09 \\ {+ DCN} & 92.91 & 91.61 & 85.72 & 5.97 \\ \hline \end{tabular} \end{center} \label{table2} \end{table} \textbf{Multi-task head.} To justify the effectiveness of MTH, we first add MTH into the baseline, denoted as +MTH. As shown in Table \ref{table2}, it obtains 0.79\%, 0.86\%, and 1.44\% improvement on the \textit{easy}, \textit{medium} and \textit{hard} subsets respectively for lightweight backbones. \textbf{Uncertainty Multi-task Loss.} The baseline uses heuristic weights ($L_{cls}:L_{box}:L_{pts}:L_{pose}=2:1:1:0.25$) for multi-tasking. Table. \ref{table2} compares the results of face detection and pose estimation tasks using UML. The UML loss further improves the performance by 1.07\%, 0.95\% and 1.37\%. Simultaneously, this method also improves the result of head pose estimation from 6.49 to 6.14. \textbf{Online Feedback data-augmentation.} In the online feedback, we add the samples with small losses and false positive. The results are denoted as +Online Feedback. Table \ref{table2} show that it obtains an improvement of 1.23\%, 1.11\% and 2.23\% for \textit{easy}, \textit{medium} and \textit{hard} subsets respectively. This shows that the proposed feed-back strategy improves the balance of the data and therefore the accuracy of face detection. In our experiments, we have observed that arbitrary increase of small faces would bring the training into a bottleneck as many false detection come from medium or large faces. \begin{table} \footnotesize \caption{Comparison of AP with other methods for light networks in the WIDER FACE validation and test set. * indicates the work without peer review. Blue indicates the best result with lightweight backbone.} \begin{center} \begin{tabular}{lccccc}\hline {Method} & backbone & \textit{easy(val$\lVert$test)} & \textit{medium(val$\lVert$test)} & \textit{hard(val$\lVert$test)} & {\textit{Multi-task}} \\ \hline MTCNN\cite{zhang2016joint} & Customized & 0.851 $\lVert$ $\ \ -\ \ \ \ $ & 0.820 $\lVert$ $\ \ -\ \ \ \ $ & 0.607 $\lVert$ $\ \ -\ \ \ \ $ & \Checkmark \\ {FACEBOXES}\cite{zhang2017faceboxes} & Customized & 0.879 $\lVert$ 0.881 & 0.857 $\lVert$ 0.853 & 0.771 $\lVert$ 0.774 & \XSolid \\ {lffd v1*}\cite{he2019lffd} & Customized & 0.910 $\lVert$ 0.896 & 0.881 $\lVert$ 0.865 & 0.780 $\lVert$ 0.770 & \XSolid \\ {ASFD-D0*}\cite{zhang2020asfd} & Customized & 0.901 $\lVert$ $\ \ -\ \ \ \ $ & 0.875 $\lVert$ $\ \ -\ \ \ \ $ & 0.744 $\lVert$ $\ \ -\ \ \ \ $ & \XSolid \\ {RetinaFace}\cite{deng2019retinaface} & MobileNet-0.25 & {0.914} $\lVert$ $\ \ -\ \ \ \ $ & {0.901} $\lVert$ $\ \ -\ \ \ \ $ & {0.782} $\lVert$ $\ \ -\ \ \ \ $ & \Checkmark \\ {img2pose*}\cite{albiero2020img2pose} & ResNet-18 & 0.908 $\lVert$ 0.900 & 0.899 $\lVert$ 0.891 & 0.847 $\lVert$ 0.839 & \Checkmark \\ MOS-S & ShuffleNet V2 &\color{blue}{0.929 $\lVert$ 0.922} &\color{blue}{0.916 $\lVert$ 0.911} &\color{blue}{0.859 $\lVert$ 0.857} & \Checkmark \\ MOS-L & ResNet-152 &{0.969 $\lVert$ 0.955} &{0.961 $\lVert$ 0.952} &{0.921 $\lVert$ 0.913} &\Checkmark \\ \hline \end{tabular} \end{center} \label{table4} \end{table} \subsection{Benchmark Results} \textbf{Face Detection Accuracy. }We train the model on the training set and test on the WIDER FACE validation and test sets. We follow the standard practices of \cite{najibi2017ssh, zhang2017s3fd} and employ flip as well as multi-scale strategies. The standard Average Precision (AP) is computed. Table \ref{table4} shows the comparison in the validation set. Taking the lightweight ShuffleNet V2 as backbone, MOS-S achieves AP of 92.9\%, 91.6\% and 85.9\% on the three subsets respectively, surpassing other methods. Taking the lightweight Mobilenet V2 ~\cite{sandler2018mobilenetv2} as backbone, MOS-Mobilenetv2 achieves AP of 94.19\%, 93.25\% and 88.34\% on the three subsets respectively which confirms that our method is also effective on other lightweight backbones. MOS-S has achieved trade-off between speed and accuracy. Using the ResNet152 as backbone, MOS-L achieves AP of 96.9\%, 96.1\%, 92.1\% on the three subsets respectively. \textbf{Landmark Localization Accuracy. }To evaluate the accuracy of the landmark localization, we compare MOS-S with the commonly used MTCNN \cite{zhang2016joint} and RetinaFace \cite{deng2019retinaface} with landmark output. We train MOS-S on the WIDER FACE and test on the AFLW \cite{koestinger2011annotated} dataset. Fig. \ref{fig-zhuxinga} compares the proposed MOS-S with RetinaFace and MTCNN. As we can see, MOS-S performs the best. \begin{figure*} \centering {\subfigure[Accuracy of landmark detection]{ \includegraphics[width=2.4in,height=1.0in]{b11} \label{fig-zhuxinga} }} {\subfigure[Pose angle distribution in WIDER FACE training set]{ \includegraphics[width=2.0in,height=1.0in]{b22} \label{fig-zhuxingb} }} \caption{(a) The comparison of MOS-S with other multi-task face detector on AFLW dataset. (b) The pose angle distribution in WIDER FACE training set. We can observe that majority of face angles are concentrated below 30 degrees. } \label{fig-zhuxing} \end{figure*} \begin{minipage}{\textwidth}\scriptsize \vspace{0.3cm} \begin{minipage}[t]{0.48\textwidth} \makeatletter\def\@captype{table} \caption{Evaluation on AFLW2000. } \begin{tabular}{lcccccc} \hline {Method} & \begin{tabular}[c]{@{}c@{}}Yaw \end{tabular} & \begin{tabular}[c]{@{}c@{}}Pitch \end{tabular} & \begin{tabular}[c]{@{}c@{}}Roll \end{tabular} & MAE\\ \hline {Dlib(68 points) \cite{kazemi2014one}} & 23.1 &13.6 &10.5 & 15.8 \\ {Fan(12 points) \cite{bulat2017far}} &6.36 &12.3 & 8.71 & 9.12 \\ {3DDFA \cite{zhu2016face}} & 5.40 &8.53 &8.25 & 7.39 \\ {Hopenet \cite{2018Fine} ($\alpha=2$)} & 6.47 & 6.56 & 5.44 & 6.16 \\ {FsaNet \cite{2019FSA} } & 4.50 & 6.08 & 4.64 & 5.07 \\ {QuatNet \cite{hsu2018quatnet} } & \color{blue}3.97 & \color{blue}{5.62} & \color{red}{3.92} & \color{blue}4.50 \\ \textbf{MOS-S-widerface} & 4.52 & 6.91 & 6.48 & 5.97 \\ \textbf{MOS-L-widerface} & 4.05 & 6.29 & 5.87 & 5.40 \\ \textbf{MOS-S-300wlp} & \color{red}{3.91} & \color{red}5.42 & \color{blue}3.98 & \color{red}4.43 \\ \hline \end{tabular} \label{table5} \end{minipage} \begin{minipage}[t]{0.48\textwidth} \makeatletter\def\@captype{table} \caption{Avearge inference time in WIDER FACE validation set.} \begin{tabular}{lcc} \hline Method & Time (ms) \\ \hline {RetinaFace-M\cite{deng2019retinaface}}+ PnP \cite{pnp1981}(GPU) & 7.2 \\ {RetinaFace-M\cite{deng2019retinaface}} + Hopenet \cite{2018Fine}(GPU) & 47.9 \\ {RetinaFace-M\cite{deng2019retinaface}} + FSAnet \cite{2019FSA}(GPU) & 41.1 \\ \textbf{MOS-S}(GPU) & 10.8 \\ \textbf{MOS-S}(ARM) & 68 \\ \textbf{MOS-L}(GPU) & 62.2 \\ \hline \end{tabular} \label{table6} \end{minipage} \vspace{0.3cm} \end{minipage} \textbf{Head Pose Estimation Accuracy. }We evaluate the pose estimation using the AFLW2000 \cite{zhu2016face}. Of the six methods \cite{kazemi2014one,bulat2017far,zhu2016face,2018Fine,2019FSA,hsu2018quatnet} compared, MOS-S is the only method to predict face location and head pose simultaneously. From Table \ref{table5}, we observe that MOS-S-widerface performs good in Yaw, but worse in Pitch and Roll. The lower performance of in Pitch and Roll estimation is likely because of few samples with large pitch and roll angles in the training data. Fig. \ref{fig-zhuxingb} plots the distribution of the angles. As we can see, the WIDER FACE dataset has few faces with large pitch and roll angle. Note that the comparison here is not a completely fair one as MOS is trained using WIDER FACE while others are trained using 300W-LP \cite{zhu2016face} which include various distribution angle data. For fair comparison, we add another experiment by training the model using only the 300W-LP dataset. MOS-S-300wlp in Table \ref{table5} achieves state-of-the-art accuracy and minimal inference time. Some examples have been given to compare MOS-S with RetinaFace with different pose estimation methods in Fig. \ref{fig9p}. As we can see, PnP \cite{pnp1981} performs poorly while Hopenet \cite{2018Fine} requires more computational time. Our method is able to provide accurate results efficiently. \textbf{Comparison with Hyperface. }For a fair comparison, we use AFLW as the training set, same as that in Hyperface \cite{ranjan2017hyperface}. We compared MOS-S and Hyperface-alexnet in face detection and pose estimation. For face detection, MOS-S achieves mAP of 93.2\% on the FDDB dataset\cite{jain2010fddb}, which is better than 90.1\% by Hyperface-alexnet. For pose estimation task, MOS-S achieves 4.89 MAE better than 5.88 by Hyperface-alexnet in the AFLW dataset. \begin{figure*} \centering {\subfigure{ \includegraphics[width=1.4in,height=0.76in]{r1-retina} }} {\subfigure{ \includegraphics[width=1.4in,height=0.76in]{hopenet2_49ms} }} {\subfigure{ \includegraphics[width=1.4in,height=0.76in]{r2-mos} }} \vspace{-0.1in} \\ \setcounter{subfigure}{0} {\subfigure[RetinaFace+PnP \cite{pnp1981}]{ \includegraphics[width=1.4in,height=0.76in]{r3-retina} }} {\subfigure[RetinaFace+Hopenet \cite{2018Fine}]{ \includegraphics[width=1.4in,height=0.76in]{hopen12_16ms} }} {\subfigure[MOS-S]{ \includegraphics[width=1.4in,height=0.76in]{r4-mos} }} \caption{Visual comparison of results between MOS-S and RetinaFace (MobileNet-0.25 backbone) with different pose methods. We only show the yaw angle which is most important in DFR, and the yellow circle indicates cases with large errors. It takes 7.6ms, 49.0ms, and 12.1ms to process the images in the first row by the three different methods respectively. } \label{fig9p} \end{figure*} \subsection{Inference Efficiency} In order to better compare the results in dynamic face detection, MOS-S is compared with RetinaFace-M( MobilenetV1\cite{howard2017mobilenets}) combined with Hopenet or FSAnet. The average time for images (resized to $640 \times 480$) from the WIDER FACE validation set are summarized in Table \ref{table6}. We measure inference time of MOS using RTX 2060 GPU and ARM platform(RK3399). With lightweight backbones, MOS-S outperforms state of the art in face detection and pose estimation with less inference time. With heavy backbones, MOS-L takes about 62.2 ms. Besides the above, we have also deployed MOS-S using ncnn with multi-threads on ARM platform and it achieves 15 FPS for a mobile device. \section{Conclusion} Real-time face detection, landmark localization and head pose estimation with low computational resource are challenging tasks. In this work, we propose a novel low latency and lightweight backbone to learn the three tasks simultaneously, which facilitates the computation for DFR in mobile devices such as robots. Uncertain multi-task loss has been proposed to regularize the learning. Moreover, we propose an online feedback sampling to augment the data according to the performance of the trained models in the training iterations. The experimental results show that the proposed method achieves the state-of-the-art results compared with other methods with similar computation resources. Our codes and annotation will be made publicly available to facilitate further research in the area. \textbf{Acknowledgment:} The work is supported in part by  Key-Area Research and Development Program of Guangdong Province, China, under grant 2019B010154003, and the Program of Guangdong Provincial Key Laboratory of Robot Localization and Navigation Technology, under grant 2020B121202011.
{'timestamp': '2021-11-02T01:27:41', 'yymm': '2110', 'arxiv_id': '2110.10953', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.10953'}
arxiv
\section{Introduction} \label{sec:intro} We consider a matching problem in a bipartite graph $G = (A \cup B,E)$ with {\em one-sided} preferences. Nodes in~$A$, also called {\em agents}, have preferences in partial order over their neighbors while nodes in~$B$, also called {\em objects}, have no preferences. This model is often called the {\em house allocation} problem as it arises in campus housing allocation in universities~\cite{AS98}. The fact that preferences are {\em one-sided} here makes this model very different from the {\em marriage} problem introduced by Gale and Shapley~\cite{GS62} in 1962, where {\em all} nodes have preferences over their neighbors. Usually one seeks a matching in $G$ that is {\em optimal} in some sense. Popularity is a well-studied notion of optimality in the model of one-sided preferences. Any pair of matchings, say $M$ and $N$, can be compared by holding an election between them where agents are voters. Every agent prefers the matching where she gets assigned a more preferred partner and being unmatched is her worst choice. Let $\phi(M,N)$ be the number of agents who prefer $M$ to~$N$. Then we say that $M$ is \emph{more popular than}~$N$ if $\phi(M,N) > \phi(N,M)$. Let us write $\Delta(M,N) = \phi(M,N) - \phi(N,M)$. \begin{definition} \label{def:popular-matching} A matching $M$ is {\em popular} if there is no matching more popular than $M$, i.e., $\Delta(M,N) \ge 0$ for all matchings $N$ in $G$. \end{definition} The \myproblem{popular matching} problem involves deciding if $G$ admits a popular matching, and finding one if so. This is a well-studied problem from 2005, and there is an efficient algorithm to solve it~\cite{AIKM07}. Consider applications where the {\em size} of the matching is of primary importance. It is natural that as many students as possible be assigned campus housing. Another application is in assigning final year medical and nursing students to hospitals during emergencies (such as a pandemic) to overcome staff shortage~\cite{ET21}. Preferences of these students are important but the size of the matching is more important, since we want to augment human resources as much as possible. Thus what we seek is not a popular matching but a popular {\em maximum matching}, i.e., among maximum matchings, a best one. Our approach to prioritize the cardinality of the matching is in stark contrast with most existing results in the area of popular matchings, where the foremost requirement is usually popularity. By augmenting $G$ with dummy agents and artificial objects (see Section~\ref{sec:prelims}), we can assume that $G$ admits a perfect matching, i.e., an \emph{assignment}. So our problem becomes the popular perfect matching problem---we will call this the \myproblem{popular assignment} problem in $G$. In other words, we seek an assignment of objects to agents such that every agent is assigned an object and, roughly speaking, there is no assignment that makes more agents happier than it makes unhappier. \begin{definition} \label{def:assignment} A perfect matching $M$ is a {\em popular assignment} if there is no perfect matching in~$G$ that is more popular than $M$, i.e., $\Delta(M,N) \ge 0$ for all perfect matchings~$N$ in~$G$. \end{definition} Thus, a popular assignment is a {\em weak Condorcet winner}~\cite{Con85,condorcet} where all perfect matchings are candidates and agents are voters. Weak Condorcet winners need not exist in a general voting instance; in our setting as well, a popular assignment need not exist in $G$. Consider the following simple example where $A = \{a_1,a_2,a_3\}$, $B = \{b_1,b_2,b_3\}$ and $G$ is the complete bipartite graph~$K_{3,3}$, i.e., every agent and object are adjacent. Suppose every agent has the same (strict) preference ordering: $b_1 \succ b_2 \succ b_3$, i.e., $b_i$ is the $i$-th choice for $i = 1,2,3$. It is easy to check that for every assignment, there is a more popular assignment; so this instance has no popular assignment. \medskip \noindent{\em The \myproblem{popular assignment} problem.} Given a bipartite graph $G = (A \cup B, E)$ where every $a \in A$ has preferences in partial order over her neighbors, does $G$ admit a popular assignment? If so, find one. \smallskip It is easy to show instances that admit popular assignments but do not have any popular matching (see Section~\ref{app:no-pop-assignment}). Interestingly, an algorithm for the \myproblem{popular assignment} problem also solves the \myproblem{popular matching} problem. By augmenting the given instance with artificial {\em worst-choice} objects and some dummy agents, we can construct an instance $G'$ on at most twice as many nodes as in $G$ such that $G$ admits a popular matching if and only if $G'$ admits a popular assignment (this simple reduction is given in Section~\ref{app:pop-matching-reduction}). Thus, the \myproblem{popular assignment} problem generalizes the \myproblem{popular matching} problem. By adjusting the usage of worst-choice objects appropriately, an algorithm for \myproblem{popular assignment} can solve the following more general variant of both the \myproblem{popular matching} problem and the \myproblem{popular assignment} problem, and thus opens possibilities to a wide spectrum of applications. \medskip \noindent{\em Popularity with diversity.} Consider instances~$G = (A \cup B, E)$ where every agent has one of $k$ colors associated with it, and we are interested in only those (not necessarily perfect) matchings that match for every $i \in \{1,\ldots,k\}$, $c_i$ agents of color~$i$, where $s_i \le c_i \le t_i$ for some given bounds~$s_i$ and~$t_i$, i.e., only those matchings that satisfy these lower and upper bounds for every color are admissible. We seek a matching that is popular {\em within} the set of admissible matchings (see Section~\ref{app:pop-matching-reduction} for a reduction to \myproblem{popular assignment}). Public housing programs constitute an application where such problems arise. For example, in Singapore, $70\%$ of the residential real estate is managed by a public housing program which promotes ethnic diversity by imposing quotas on each housing block and ethnic group. Motivated by this market, Benabbou et al. \cite{BCH+18a} study a similar model with cardinal utilities. \subsection{Our contribution} Our first result is that the \myproblem{popular assignment} problem can be solved in polynomial time. Let $|A| = |B| = n$ and $|E| = m$. \begin{theorem} \label{thm:algo} The \myproblem{popular assignment} problem in $G = (A \cup B, E)$ can be solved in $O(m\cdot n^{5/2})$ time. \end{theorem} When a popular assignment does not exist in~$G$, a natural extension is to ask for an {\em almost} popular assignment, i.e., an assignment with {\em low} unpopularity. How do we measure the unpopularity of an assignment? A well-known measure is the {\em unpopularity margin}~\cite{McC08} defined for any assignment~$M$ as $\mu(M) = \max_N (\phi(N,M) - \phi(M,N))=\max_N \Delta (N,M)$, where the maximum is taken over all assignments, that is, all perfect matchings~$N$ in~$G$. Thus $\mu(M)$ is the maximum margin by which another assignment defeats~$M$. An assignment~$M$ is popular if and only if $\mu(M) = 0$. Let the \myproblem{$k$-unpopularity margin} problem be the problem of deciding if $G$ admits an assignment with unpopularity margin at most~$k$. We generalize Theorem~\ref{thm:algo} to show the following result. \begin{theorem} \label{thm:unpopmargin-algo-xp} For any $k \in \mathbb{Z}_{\ge 0}$, the \myproblem{$k$-unpopularity margin} problem in $G=(A \cup B,E)$ can be solved in $O(m^{k+1} \cdot n^{5/2})$ time. \end{theorem} Rather than the exponential dependency on the parameter~$k$ in Theorem~\ref{thm:unpopmargin-algo-xp}, can we solve the \myproblem{$k$-unpopularity margin} problem in polynomial time? Or at least can we achieve a running time of the form $f(k)\mathsf{poly}(m,n)$ for some function~$f$ so that the degree of the polynomial is independent of~$k$? That is, can we get a \emph{fixed-parameter tractable} algorithm with parameter~$k$? The following hardness result shows that the algorithm of Theorem~\ref{thm:unpopmargin-algo-xp} is essentially optimal for the \myproblem{$k$-unpopularity margin} problem. See Section~\ref{hardness:k-unpop-margin} for the definition of $\mathsf{W}_l[1]$-hardness. \begin{theorem} \label{thm:unpopmargin-hardness} The \myproblem{$k$-unpopularity margin} problem is $\mathsf{W}_l[1]$-hard with parameter~$k$ when agents' preferences are weak rankings, and it is $\mathsf{NP}$-complete even if preferences are strict rankings. \end{theorem} We next consider the \myproblem{minimum-cost popular assignment} problem in $G$. Suppose that there is a cost function $c:E \rightarrow \mathbb{R}$ on the edges and a budget $\beta$ and we want to know if $G$ admits a popular assignment whose sum of edge costs is at most $\beta$. Computing a minimum-cost popular assignment efficiently would also imply an efficient algorithm for finding a popular assignment with \emph{forced/forbidden} edges. We show the following hardness result. \begin{theorem} \label{thm:mincost-nphard-01} The \myproblem{minimum-cost popular assignment} problem is $\mathsf{NP}$-complete, even if each edge cost is in $\{0,1\}$ and agents have strict preferences. \end{theorem} Interestingly, in spite of the above hardness result, the popular assignment problem with partial order preferences and forced/forbidden edges is tractable. Note that the assignment $M$ must be popular among \emph{all} assignments, not only those adhering to the forced and forbidden edge constraints. We show the following positive result. \begin{theorem} \label{thm:forced-forbidden} Given a set $F^+ \subseteq E$ of forced edges and another set $F^- \subseteq E$ of forbidden edges, we can determine in polynomial time if there exists a popular assignment $M$ in $G = (A \cup B, E)$ such that $F^+ \subseteq M$ and $F^- \cap M = \emptyset$. \end{theorem} Thus the \myproblem{popular assignment} problem is reminiscent of the well-known \myproblem{stable roommates} problem\footnote{This problem asks for a stable matching in a general graph (which need not be bipartite) with strict preferences.}; in a roommates instance, finding a stable matching can be solved in polynomial time~\cite{Irv85} even with forced/forbidden edges~\cite{FIM07}, however finding a minimum-cost stable matching is $\mathsf{NP}$-hard~\cite{Fed92}. \paragraph{Application to housing markets.} Finally, in Proposition~\ref{prop:pop_allocation} we present an application of the algorithm of Theorem~\ref{thm:algo} that allows us to find popular allocations in so-called \emph{housing markets}, a model defined by Shapley and Scarf~\cite{SS74}; see Section~\ref{sec:housing} for all definitions concerning housing markets. We contrast this with Theorem~\ref{thm:housealloc-nphard}, a strengthening of Theorem~\ref{thm:mincost-nphard-01}, showing that it is $\mathsf{NP}$-hard to find a popular allocation that maximizes the number of trading agents in the housing market. \medskip \subsection{Background} The notion of popularity in a marriage instance (where preferences are {\em two-sided} and strict) was introduced by G{\"a}rdenfors~\cite{Gar75} in 1975. Popular matchings always exist in such an instance, since any stable matching is popular~\cite{Gar75}. When preferences are one-sided, popular matchings need not exist. A simple and clean combinatorial characterization of popular matchings (see Section~\ref{app:characterization-of-pop-matchings}) was given in \cite{AIKM07}, leading to an $O(m\sqrt{n})$ time algorithm~\cite{AIKM07} for the \myproblem{popular matching} problem. By contrast, a combinatorial characterization of popular assignments remains elusive. Finding a minimum unpopularity margin matching was proved to be $\mathsf{NP}$-hard~\cite{McC08}. In the last fifteen years, popularity has been a widely studied concept. Researchers have considered extensions of the \myproblem{popular matching} problem where one aims for a popular matching satisfying some additional optimality criteria such as rank-maximality or fairness~\cite{KN09,MI11}, or where the notion of popularity is adjusted to incorporate capacitated objects or weighted agents~\cite{Mestre14,SM10}. Another variant of the popular matching problem was considered in \cite{CHK17} where nodes in $A$ have strict preferences and nodes in $B$, i.e., objects, have no preferences, however each object cares to be matched to any of its neighbors. We refer to \cite{Cseh17} for a survey on results in this area. Among the literature on popular matchings, only a few studies have considered a setting that focuses on popularity within a restricted set of admissible solutions. The paper that comes closest to our work is \cite{Kav14} which considered the popular maximum matching problem in a marriage instance (where preferences are two-sided and strict). It was shown there that a popular maximum matching always exists in a marriage instance and one such matching can be computed in $O(mn)$ time. Very recently, it was shown in \cite{Kav20} that a minimum-cost popular maximum matching in a marriage instance can be computed in polynomial time. These results use the rich machinery of stable matchings in a marriage instance~\cite{GS62,Rot92}. In contrast to these positive results for popular maximum matchings, computing an {\em almost-}stable maximum matching (one with the least number of blocking edges) in a marriage instance is $\mathsf{NP}$-hard~\cite{BMM10}. \subsection{Techniques} Our popular assignment algorithm is based on LP duality. We show that a matching~$M$ is a popular assignment if and only if it has a \emph{dual certificate} $\vec{\alpha} \in \{0, \pm 1,\ldots, \pm (n-1)\}^{2n}$ fulfilling certain constraints induced by the matching $M$. Our algorithm (see Section~\ref{sec:algo}) can be viewed as a search for such a dual certificate. It associates a {\em level} $\ell(b)$ with every $b \in B$. This level function $\ell$ guides us in constructing a subgraph $G_{\ell}$ of $G$. If $G_{\ell}$ contains a perfect matching, then this matching is a popular assignment in $G$ and the levels determine a corresponding dual certificate. If $G_{\ell}$ has no perfect matching, then we increase some $\ell$-values and update $G_{\ell}$ accordingly, until eventually~$G_{\ell}$ contains a perfect matching or the level of an object increases beyond the permitted range, in which case we prove that no popular assignment exists. The LP method for popular matchings was introduced in \cite{KMN09} and dual certificates for popular matchings/maximum matchings in marriage instances were shown in \cite{Kav16,Kav20}. However, dual certificates for popular matchings in instances with one-sided preferences have not been investigated so far. The existence of simple dual certificates for popular assignments is easy to show (see Section~\ref{sec:prelims}), but this does not automatically imply polynomial-time solvability. Our main novelty lies in showing a combinatorial algorithm to search for dual certificates in an instance $G$ and in using this approach to solve the \myproblem{popular assignment} problem in polynomial time. \paragraph{\bf Our other results.} Our algorithm for the \myproblem{popular assignment} problem with {\em forced/forbidden} edges (see Section~\ref{sec:edge-restrictions}) is a natural extension of the above algorithm where certain edges are excluded. The \myproblem{$k$-unpopularity margin} algorithm (see Section~\ref{sec:min-unpopular}) associates a {\em load} with every edge such that the total load is at most $k$ and the overloaded edges are treated as {\em forced} edges. Our $W_l[1]$-hardness result shows that this $O^*(m^k)$ algorithm for the \myproblem{$k$-unpopularity margin} problem is essentially optimal, i.e., it is highly unlikely that this problem admits an $f(k)m^{o(k)}$ algorithm for any computable function~$f$. The $\mathsf{NP}$-hardness for the \myproblem{minimum-cost popular assignment} problem (see Section~\ref{sec:mincost}) implies that given a set of desired edges, it is $\mathsf{NP}$-hard (even for strict preferences) to find a popular assignment that contains the maximum number of desired edges. Thus, although the {\em forced} edges variant is easy, the {\em desired} edges variant is hard. \section{Preliminaries} For any $v \in A\cup B$, let $\mathsf{Nbr}_G(v)$ denote the set of neighbors of $v$ in $G$, and $\delta(v)$ the set of edges incident to $v$. For any $X \subseteq A\cup B$, we let $\mathsf{Nbr}_G(X)= \cup_{v \in X} \mathsf{Nbr}_G(v)$; we may omit the subscript $G$ if it is clear from the context. For any set $X$ of vertices (or edges) in $G$, let $G-X$ be the subgraph of~$G$ obtained by deleting the vertices (or edges, respectively) of $X$ from $G$. For a matching~$M$ in~$G$ and a node~$v$ matched in~$M$, we denote the partner of~$v$ by~$M(v)$. The preferences of node $a \in A$ on its neighbors are given by a strict partial order $\succ_a$, so $b \succ_a b'$ means that $a$ prefers $b$ to $b'$. We use $b \sim_a b'$ to denote that $a$ is indifferent between $b$ and $b'$, i.e., neither $b \succ_a b'$ nor $b' \succ_a b$ holds. The relation $\succ_a$ is a \emph{weak ranking} if $\sim_a$ is transitive. In this case, $\sim_a$ is an equivalence relation and there is a strict order on the equivalence classes. When each equivalence class has size~1, we call it a \emph{strict ranking} or a \emph{strict preference}. We will also use the notation $[k]=\{1,2,\dots, k\}$ for any positive integer~$k$. \subsection{A characterization of popular matchings from \cite{AIKM07}}\label{app:characterization-of-pop-matchings} In order to characterize popular matchings, as done in \cite{AIKM07}, it will be convenient to add artificial worst-choice or last resort objects to the given instance~$G = (A \cup B, E)$. So $B = B \cup \{l(a): a \in A\}$, i.e., corresponding to each~$a \in A$, a node~$l(a)$ gets added to~$B$ and we set this node $l(a)$ as the worst-choice object for~$a$. Thus we have $E = E \cup \{(a,l(a)): a \in A\}$. Let $E_1 = \{(a,b)\in E: b \text{ is a top-choice object for } a\}$. Call an object $b$ {\em critical} if every maximum matching in $G_1 = (A \cup B, E_1)$ matches $b$, call $b$ {\em non-critical} otherwise. \begin{theorem}[\cite{AIKM07}] A matching $M$ in $G = (A \cup B, E)$ is popular if and only if $M$ matches all critical objects and every agent $a$ is matched to either one of her top-choice objects or one of her most preferred non-critical objects. \end{theorem} \subsection{An instance without popular matchings that admits a popular assignment}\label{app:no-pop-assignment} We describe a simple example that does not admit any popular matching, but admits a popular assignment. Let $G = (A \cup B, E)$ where $A = \{a_1,a_2,a_3\}$ and $B = \{b_1,b_2,b_3\}$ and the preference order of both $a_1$ and $a_2$ is $b_1 \succ b_2$ while the preference order of $a_3$ is $b_1 \succ b_2 \succ b_3$. It follows from the characterization of popular matchings from \cite{AIKM07} that a popular matching $M$ has to match each of $a_1,a_2,a_3$ to either $b_1$ or $b_2$. Since this is not possible, this instance has no popular matching. It is easy to check that $M^* = \{(a_1,b_1),(a_2,b_2),(a_3,b_3)\}$ is a popular assignment in $G$. \subsection{Some simple reductions to the popular assignment problem}\label{app:pop-matching-reduction} We will first show a reduction from the \myproblem{popular matching} problem to the \myproblem{popular assignment} problem. Let $G = (A \cup B, E)$ be an instance of the \myproblem{popular matching} problem. Let $B' = B \cup \{l(a): a \in A\}$. That is, corresponding to each~$a \in A$, an object~$l(a)$ (the last resort of~$a$) is in~$B'$ and we set this object~$l(a)$ as the worst-choice of~$a$. Let $A' = A \cup \{d_1,\ldots,d_{|B|}\}$, i.e., there are $|B|$ many dummy agents in~$A'$. Each dummy agent~$d_i$ is adjacent to all objects in~$B'$ and is indifferent between any two of them. It is easy to see that every matching~$M$ in~$G$ can be extended to a {\em perfect matching}~$M'$ in this new graph~$G' = (A'\cup B',E')$ and conversely, every perfect matching~$M'$ in~$G'$ projects to a matching $M$ in $G$. For any pair of matchings~$M$ and~$N$ in~$G$, observe that $\Delta(M,N) = \Delta(M',N')$. Thus an algorithm that finds a popular assignment in~$G'$ solves the \myproblem{popular matching} problem in~$G$. \medskip \noindent{\em Popularity with diversity.} Recall this problem defined in Section~\ref{sec:intro} where every agent in an instance~$G = (A\cup B,E)$ has one of $k$ colors associated with it, and admissible matchings are those that for every $i \in \{1,\ldots,k\}$ match $c_i$ agents of color~$i$ where $s_i \le c_i \le t_i$ for some given bounds $s_i$ and $t_i$. We seek a matching that is popular within the set of admissible matchings. We augment $B$ by adding $n_i-s_i$ artificial objects for each $i$, where $n_i$ is the number of agents colored $i$. For each color $i$, these $n_i-s_i$ objects are tied as the worst choices of all agents colored~$i$. Let~$A' = A \cup \{d_1,\ldots,d_{n'}\}$, where $n' = |B| - \sum_is_i$. Every dummy agent $d \in \{d_1, \dots, d_{n'}\}$ is adjacent to all objects in $B$ and for each color $i$ some fixed $t_i-s_i$ artificial objects meant for color class~$i$ introduced above---as before, $d$ is indifferent between any two of its neighbors. So for each $i$, there are $n_i-t_i$ artificial objects not adjacent to any dummy agent. Let $G'$ be the new instance. It is easy to see that an algorithm that finds a popular assignment in~$G'$ solves our problem in~$G$. \section{Dual certificates for popular assignments} \label{sec:prelims} Let $G = (A \cup B, E)$ be an input instance and let $\nu$ be the size of a maximum matching in $G$. Let us augment $G$ with $|B|- \nu$ dummy agents that are adjacent to all objects in $B$ (and indifferent among them), along with $|A|-\nu$ artificial objects that are tied as the worst-choice neighbors of all non-dummy agents. Any maximum matching~$M$ in the original graph extends to a perfect matching (i.e., assignment)~$M'$ in the augmented graph; moreover, $\Delta(M,N) = \Delta(M',N')$ for any pair of maximum matchings $M$ and~$N$ in $G$. Thus, we can assume without loss of generality that the input instance~$G$ admits a perfect matching. Let $|A| = |B| = n$ and $|E| = m$. Let $M$ be any perfect matching in $G$. The following edge weight function~$\mathsf{wt}_M$ in $G$ will be useful. For any $(a,b) \in E$ \begin{equation*} \mathrm{let}\ \mathsf{wt}_M(a,b) = \begin{cases} \phantom{-} 1 & \text{if\ $a$\ prefers\ $b$\ to\ $M(a)$;}\\ -1 & \text{if\ $a$\ prefers\ $M(a)$\ to\ $b$;}\\ \phantom{-} 0 & \text{otherwise,\ i.e., if\ $b \sim_a M(a)$.} \end{cases} \end{equation*} Let $\mathsf{wt}_M(N)= \sum_{e \in N} \mathsf{wt}_M(e)$ for any edge set $N \subseteq E$. Consider the following linear program~\ref{LP1} and its dual~\ref{LP2}. \iffalse \begin{linearprogram} { \label{LP1} \maximize{\sum_{e\in E}}\mathsf{wt}_M(e)\cdot x_e } \sum_{e \in {\delta}(v)}x_e \ & = \ 1 \ \ \forall\, v \in A\cup B\notag \\ x_e \ & \ge\ 0 \ \ \forall e \in E\notag. \end{linearprogram} The optimal value of~\ref{LP1} is $\max_N\mathsf{wt}_M(N)$ where $N$ is a perfect matching in $G$. The definition of $\mathsf{wt}_M$ implies that $\mathsf{wt}_M(N) = \Delta(N,M)$ where $\Delta(N,M) = \phi(N,M) - \phi(M,N)$. So $M$ is a popular assignment if and only if the optimal value of~\ref{LP1} is at most 0. In fact, the optimal value of \ref{LP1} is exactly 0 since $\Delta(M,M) = 0$. Hence for a popular assignment $M$, the edge incidence vector of $M$ is an optimal solution to \ref{LP1}. Consider the dual LP---this is \ref{LP2} given below. \begin{linearprogram} { \label{LP2} \minimize{\sum_{u\in A\cup B}}y_u } y_a + y_b\ & \ge \ \mathsf{wt}_M(a,b) \ \ \forall\, (a,b) \in E\notag. \end{linearprogram} \fi \begin{table}[H] \vspace{-10pt} \begin{minipage}[t]{0.45\linewidth}\centering \begin{align} \label{LP1} \max \sum_{e \in E} \mathsf{wt}_M(e)\cdot x_e &\mbox{\hspace*{0.1in}}\tag{LP1}\\ \notag \text{s.t.}\qquad\sum_{e \in \delta(u)}x_e = 1 &\mbox{\hspace*{0.1in}}\forall\, u \in A \cup B\\ \notag x_e \ge 0 &\mbox{\hspace*{0.1in}}\forall\, e \in E. \end{align} \end{minipage} \hspace{0.6cm} \begin{minipage}[t]{0.45\linewidth}\centering \begin{align} \label{LP2} \min \sum_{u \in A \cup B}y_u &\mbox{\hspace*{0.1in}}\tag{LP2}\\ \notag \text{s.t.}\qquad y_{a} + y_{b} \ge \mathsf{wt}_{M}(a,b) &\mbox{\hspace*{0.1in}}\forall\, (a,b)\in E. \end{align} \end{minipage} \end{table} \ref{LP1} is well-known to be integral, and hence its optimal value is $\max_N\mathsf{wt}_M(N)$ where $N$ can be any perfect matching in $G$. The definition of $\mathsf{wt}_M$ implies that $\mathsf{wt}_M(N) = \Delta(N,M)$; recall also the definition $\Delta(N,M) = \phi(N,M) - \phi(M,N)$. So $M$ is a popular assignment if and only if the optimal value of~\ref{LP1} is at most 0. In fact, the optimal value of \ref{LP1} is then exactly~0, by $\Delta(M,M) = 0$. Hence for a popular assignment $M$, the edge incidence vector of $M$ is an optimal solution to \ref{LP1}. Theorem~\ref{thm:certificate} gives a useful characterization of popular assignments. The proof of Theorem~\ref{thm:certificate} is given in Section~\ref{sec:min-unpopular} along with the proof of a related result (Theorem~\ref{thm:dual-cert-unpopular}). A {\em dual certificate} of a popular assignment~$M$ is an optimal solution~$\vec{\alpha}$ to~\ref{LP2} as given in Theorem~\ref{thm:certificate}. \begin{theorem} \label{thm:certificate} $M$ is a popular assignment if and only if there exists an optimal solution $\vec{\alpha}$ to \ref{LP2} such that $\alpha_a \in \{0, 1, 2,\ldots, (n-1)\}$ for all $a \in A$, $\alpha_b \in \{0, -1, -2,\ldots, -(n-1)\}$ for all $b \in B$, and $\sum_{u\in A\cup B}\alpha_u = 0$. \end{theorem} \section{The popular assignment algorithm} \label{sec:algo} The goal of our algorithm is to construct a perfect matching $M$ in $G$ along with a dual certificate~$\vec{\alpha}$. Every $b \in B$ will have an associated {\em level} $\ell(b)$ in this algorithm and the $\alpha$-value of $b$ will be $-\ell(b)$, i.e., we set $\alpha_b=-\ell(b)$. Given a function $\ell:B \rightarrow \mathbb{N}$ called a {\em level function}, for any $a \in A$ let $\ell^*(a)=\max_{b \in \mathsf{Nbr}(a)}\ell(b)$ be the highest level at which agent $a$ has neighbors. Now we define the subgraph $G_\ell = (A \cup B, E_\ell)$ \emph{induced by levels $\ell(\cdot)$} by putting an edge $(a,b) \in E$ into $E_\ell$ if and only if \begin{itemize}[leftmargin=25pt] \item[(i)] $b$ has level $\ell^*(a)$, and $a$ has no neighbor in level $\ell^*(a)$ that she prefers to $b$, or \item[(ii)] $b$ has level $\ell^*(a)-1$, and $a$ prefers $b$ to each of her neighbors in level $\ell^*(a)$, and moreover, $a$ prefers none of her neighbors in level $\ell^*(a)-1$ to $b$. \end{itemize} Thus in the subgraph $G_{\ell}$, every agent has edges to her favorite {\em highest-level} neighbors and to her favorite neighbors one level below, provided these neighbors are preferred to all of her highest-level neighbors (see Figure~\ref{fig:G_ell} for an illustration). The following lemma will be very useful. { \begin{figure}\centering \begin{minipage}{0.45\textwidth} \centering \begin{tikzpicture} \draw [fill=black!10,draw=none,rounded corners] (1.7,1.8) rectangle (2.3,1.2); \draw [fill=black!10,draw=none,rounded corners] (1.7,0.8) rectangle (2.3,0.2); \draw [fill=black!10,draw=none,rounded corners] (1.7,-.2) rectangle (2.3,-1.4); \node[circle,fill=black,label=left:$a_1$,inner sep = 2pt] (a1) at (0,1){}; \node[circle,fill=black,label=left:$a_2$,inner sep = 2pt] (a2) at (0,-1.1){}; \node[rectangle, draw=black,inner sep = 2pt] (b1) at (2,1.5){$2$}; \node[rectangle, draw=black,inner sep = 2pt] (b2) at (2,0.5){$1$}; \node[rectangle, draw=black,inner sep = 2pt] (b3) at (2,-.5){$0$}; \node[rectangle, draw=black,inner sep = 2pt] (b4) at (2,-1.1){$0$}; \draw[very thick] (a1) -- (b1) node [fill=white, inner sep=0.05cm, pos=0.2] {\scriptsize $2$}; \draw[dashed] (a1) -- (b2) node [fill=white, inner sep=0.05cm, pos=0.4] {\scriptsize $3$}; \draw[dashed] (a1) -- (b3) node [fill=white, inner sep=0.05cm, pos=0.2] {\scriptsize $1$}; \draw[very thick] (a2) -- (b2) node [fill=white, inner sep=0.05cm, pos=0.2] {\scriptsize $2$}; \draw[very thick] (a2) -- (b3) node [fill=white, inner sep=0.05cm, pos=0.4] {\scriptsize $1$}; \draw[very thick] (a2) -- (b4) node [fill=white, inner sep=0.05cm, pos=0.3] {\scriptsize $1$}; \node (d1) at (3.5,1.5) {}; \end{tikzpicture} \caption{Illustration of the subgraph $G_{\ell}$ of~$G$ for an instance with weak rankings and a level function~$\ell$. Circles indicate agents and squares objects; the $\ell$-level of each object is written inside the square depicting it. Numbers on the edges indicate the agents' weak rankings. Bold edges are included in $G_{\ell}$ and dashed edges are not. All but two agents were omitted.} \label{fig:G_ell} \end{minipage}\hspace{.3cm} \begin{minipage}{0.45\textwidth} \centering \begin{tikzpicture} \node[circle,fill=black,label=left:$a_0$,inner sep = 2pt] (a1) at (0,3){}; \node[circle,fill=black,label=left:$a_{t-1}$,inner sep = 2pt] (a2) at (0,2){}; \node[circle,fill=black,label=left:$a_t$,inner sep = 2pt] (a3) at (0,1){}; \node[circle,fill=black,inner sep = 2pt] (a4) at (0,0){}; \node[rectangle, fill=black,inner sep = 2pt,label=right:$b_{0}$] (b1) at (2,3.5){}; \node[rectangle, fill=black,inner sep = 2pt, label=right:$b_{t-1}$] (b2) at (2,2.5){}; \node[rectangle, fill=black,inner sep = 2pt,label=right:$b_{t}$] (b3) at (2,1.5){}; \node[rectangle, fill=black,inner sep = 2pt] (b4) at (2,.5){}; \draw[thick,densely dashed] (a1) -- (b1); \draw[thick] (a1) -- (b2) node[fill=white, inner sep=0.1cm, pos=0.5,rotate=-13]{$\dots$}; \draw[thick, densely dashed] (a2) -- (b2); \draw[thick] (a2) -- (b3); \draw[thick,densely dashed] (a3) -- (b3) node[pos=0.7,below]{\scriptsize $\not \in E_{\ell}$}; \draw[thick] (a3) -- (b4) node[fill=white, inner sep=0.1cm, pos=0.5,rotate=-13]{$\dots$}; \draw[thick, densely dashed] (a4) -- (b4); \end{tikzpicture} \caption{An illustration of the $M$-augmenting path~$P$ within the proof of Lemma \ref{lem:alpha-vs-ell}. Solid edges are in~$M$ and dashed edges are in $M^\star$. The edge $(a_t, b_t)$ is not contained in $E_\ell$.} \label{fig:my_label2} \end{minipage} \end{figure} } \iffalse { \begin{figure}\centering \begin{minipage}{0.45\textwidth} \begin{tikzpicture} \draw [fill=black!10,draw=none,rounded corners] (1.7,1.8) rectangle (2.3,1.2); \draw [fill=black!10,draw=none,rounded corners] (1.7,0.8) rectangle (2.3,0.2); \draw [fill=black!10,draw=none,rounded corners] (1.7,-.2) rectangle (2.3,-1.4); \node[circle,fill=black,label=left:$a_1$,inner sep = 2pt] (a1) at (0,1){}; \node[circle,fill=black,label=left:$a_2$,inner sep = 2pt] (a2) at (0,-1.1){}; \node[rectangle, draw=black,inner sep = 2pt] (b1) at (2,1.5){$2$}; \node[rectangle, draw=black,inner sep = 2pt] (b2) at (2,0.5){$1$}; \node[rectangle, draw=black,inner sep = 2pt] (b3) at (2,-.5){$0$}; \node[rectangle, draw=black,inner sep = 2pt] (b4) at (2,-1.1){$0$}; \draw[very thick] (a1) -- (b1) node [fill=white, inner sep=0.05cm, pos=0.2] {\scriptsize $2$}; \draw[dashed] (a1) -- (b2) node [fill=white, inner sep=0.05cm, pos=0.4] {\scriptsize $3$}; \draw[dashed] (a1) -- (b3) node [fill=white, inner sep=0.05cm, pos=0.2] {\scriptsize $1$}; \draw[very thick] (a2) -- (b2) node [fill=white, inner sep=0.05cm, pos=0.2] {\scriptsize $2$}; \draw[very thick] (a2) -- (b3) node [fill=white, inner sep=0.05cm, pos=0.4] {\scriptsize $1$}; \draw[very thick] (a2) -- (b4) node [fill=white, inner sep=0.05cm, pos=0.3] {\scriptsize $1$}; \node (d1) at (3.5,1.5) {}; \node at (-1,2) {The subgraph $G_{\ell}$}; \end{tikzpicture} \caption{Illustration of the subgraph $G_{\ell}$ of~$G$ for an instance with weak rankings and a level function $\ell$. Circles indicate agents and squares objects; the $\ell$-level of each is written inside the square depicting it. Numbers on the edges indicate the agents' weak rankings. Bold edges are included in~$G_{\ell}$ and dashed edges are not. All but two agents were omitted.} \label{fig:G_ell} \end{minipage}\hspace{.3cm} \begin{minipage}{0.45\textwidth} \centering \begin{tikzpicture} \node[circle,fill=black,label=left:$a_0$,inner sep = 2pt] (a1) at (0,3){}; \node[circle,fill=black,label=left:$a_{t-1}$,inner sep = 2pt] (a2) at (0,2){}; \node[circle,fill=black,label=left:$a_t$,inner sep = 2pt] (a3) at (0,1){}; \node[circle,fill=black,inner sep = 2pt] (a4) at (0,0){}; \node[rectangle, fill=black,inner sep = 2pt,label=right:$b_{0}$] (b1) at (2,3.5){}; \node[rectangle, fill=black,inner sep = 2pt, label=right:$b_{t-1}$] (b2) at (2,2.5){}; \node[rectangle, fill=black,inner sep = 2pt,label=right:$b_{t}$] (b3) at (2,1.5){}; \node[rectangle, fill=black,inner sep = 2pt] (b4) at (2,.5){}; \draw[thick,densely dashed] (a1) -- (b1); \draw[thick] (a1) -- (b2) node[fill=white, inner sep=0.1cm, pos=0.5,rotate=-13]{$\dots$}; \draw[thick, densely dashed] (a2) -- (b2); \draw[thick] (a2) -- (b3); \draw[thick,densely dashed] (a3) -- (b3) node[pos=0.7,below]{\scriptsize $\not \in E_{\ell}$}; \draw[thick] (a3) -- (b4) node[fill=white, inner sep=0.1cm, pos=0.5,rotate=-13]{$\dots$}; \draw[thick, densely dashed] (a4) -- (b4); \end{tikzpicture} \caption{An illustration of the $M$-augmenting path $P$ within the proof of Lemma \ref{lem:alpha-vs-ell}. Solid edges are in~$M$ and dashed edges are in~$M^\star$. The edge $(a_t, b_t)$ is not contained in $E_\ell$.} \label{fig:my_label2} \end{minipage} \end{figure} } \fi \begin{lemma} \label{lem:G-ell} A matching $M$ in $G$ is a popular assignment if and only if there exists a level function~$\ell$ such that $M$ is a perfect matching in $G_{\ell}$. Further, this happens if and only if there is a level function~$\ell$ and a dual certificate~$\vec \alpha$ for $M$ where $\ell(b) = |\alpha_b|$ for all $b \in B$ and $M$ is a perfect matching in $G_{\ell}$. \end{lemma} \begin{proof} Let us first show that if there exists a level function $\ell$ such that $M$ is a perfect matching in $G_{\ell}$, then $M$ is a popular assignment in~$G$. We construct a dual certificate for $M$ as follows. Let~$\alpha_b = -\ell(b)$ for all $b \in B$ and $\alpha_a = \ell(M(a))$ for all $a \in A$. Note that the value of $\vec{\alpha}$ as a solution for~\ref{LP2} is $\sum_{v \in A\cup B} \alpha_v = \sum_{a \in A} (\alpha_a + \alpha_{M(a)}) = 0 = \sum_{e \in M} \mathsf{wt}_M(e)$. Thus $\vec \alpha$ is optimal for \ref{LP2} if it is feasible. It remains to show that $\alpha_a + \alpha_b \geq \mathsf{wt}_M(a,b)$ for every $(a, b) \in E$. To this end, let $(a, b) \in E$ and let $b' := M(a)$. Note that $\alpha_a + \alpha_b = \ell(b') - \ell(b)$. We are going to show that $\ell(b') - \ell(b) \geq \mathsf{wt}_M(a, b)$. Because $(a, b') \in E_\ell$, one of the following cases holds: \begin{itemize} \item Case (i): $\ell(b') = \ell^*(a)$, so $a$ prefers no neighbor of hers in level $\ell^*(a)$ to $b'$. We have two subcases: \begin{itemize} \item If $\ell(b) = \ell^*(a)$, then $a$ does not prefer $b$ to $b'$ and hence $\mathsf{wt}_M(a, b) \leq 0 = \ell(b') - \ell(b)$. \item If $\ell(b) < \ell^*(a)$, then $\ell(b') - \ell(b) \geq 1 \geq \mathsf{wt}_M(a, b)$. \end{itemize} \item Case (ii): $\ell(b') = \ell^*(a) - 1$, so $a$ prefers $b'$ to each of her neighbors in level $\ell^*(a)$, and $a$ prefers none of her neighbors in level $\ell^*(a)-1$ to $b'$. We have three subcases: \begin{itemize} \item If $\ell(b) = \ell^*(a)$, then $a$ prefers $b'$ to $b$ and hence $\mathsf{wt}_M(a, b) = -1 = \ell(b') - \ell(b)$. \item If $\ell(b) = \ell^*(a) - 1$, then $a$ does not prefer $b$ to $b'$ and hence $\mathsf{wt}_M(a, b) \le 0 = \ell(b') - \ell(b)$. \item If $\ell(b) < \ell^*(a) - 1$, then $\ell(b') - \ell(b) \geq 1 \geq \mathsf{wt}_M(a, b)$. \end{itemize} \end{itemize} Thus in each of these cases $\mathsf{wt}_M(a, b) \leq \ell(b') - \ell(b) = \alpha_a + \alpha_b$. Hence $\alpha$ is a dual certificate for $M$, and thus $M$ is a popular assignment by Theorem~\ref{thm:certificate}. \smallskip We now show the converse. Let $M$ be a popular assignment in $G$ and let $\vec{\alpha}$ be a dual certificate for $M$. We claim that $M$ is a matching in the graph $G_{\ell_{\alpha}}$ induced by levels $\ell_{\vec{\alpha}}$ with $\ell_{\vec{\alpha}}(b) = |\alpha_b|$ for all $b \in B$. To prove this, we use that $\alpha_a + \alpha_b \ge \mathsf{wt}_{M}(a,b)$ for every $(a,b) \in E$. First, because the incidence vector of $M$ and $\vec \alpha$ are optimal solutions to \ref{LP1} and \ref{LP2}, respectively, by complementary slackness we get $\alpha_a + \alpha_{M(a)} = 0$ for each $a \in A$. This implies $\alpha_a = -\alpha_{M(a)} = \ell_{\vec \alpha}(M(a))$. Therefore, we have $\ell_{\vec \alpha}(M(a)) \geq \ell_{\vec \alpha}(b) + \mathsf{wt}_M(a, b)$ for all $(a, b) \in E$. Since $\mathsf{wt}_{M}(e) \ge -1$ for all edges $e$, any agent $a$ has to be matched in~$M$ to either (i)~an {\em undominated} neighbor in level $\ell^*_{\vec\alpha}(a)$ (i.e., $a$ prefers none of her neighbors in this level to~$M(a)$) or (ii)~an undominated neighbor in level $\ell^*_{\vec\alpha}(a)-1$ which, moreover, has to {\em dominate} (i.e., be preferred by $a$ to) all of $a$'s neighbors in level~$\ell^*_{\vec\alpha}(a)$. So $M$ is a perfect matching in $G_{\ell_{\vec\alpha}}$. \qed \end{proof} \noindent{\bf The algorithm.} Consider Algorithm~\ref{alg:popassign} on input $G = (A \cup B, E)$. In search for a dual certificate, this algorithm will maintain a \emph{level} $\ell(b)$ for every $b \in B$. Initially, $\ell(b) = 0$ for every $b \in B$. Our algorithm checks whether there exists a popular assignment by computing a perfect matching in the graph $G_\ell$. If no such matching exists, the levels of unmatched objects are increased, the graph~$G_{\ell}$ is updated accordingly, and the search continues. Eventually, either a perfect matching in $G_\ell$ is found, or the level of an object exceeds $n-1$. In the latter case we can conclude that no popular assignment exists, as we will show below. \begin{algorithm} \caption{Finding a popular assignment}\label{alg:popassign} \begin{algorithmic}[1] \ForAll{$b \in B$} $\ell(b) = 0$. \EndFor \While{$\ell(b) < n$ for all $b \in B$} \State Construct the graph $G_\ell$ and compute a maximum matching $M$ in $G_{\ell}$. \If{$M$ is a perfect matching} \textbf{return} $M$. \EndIf \ForAll{$b \in B$ unmatched in $M$} $\ell(b) = \ell(b) + 1$. \EndFor \EndWhile \State \textbf{return} ``$G$ has no popular assignment''. \end{algorithmic} \end{algorithm} \iffalse \begin{enumerate} \item Initialize $\ell(b) = 0$ for all $b \in B$. \item While $\ell(b) < n$ for all $b \in B$ do \begin{enumerate} \item Construct the graph $G_\ell$ and compute a maximum matching $M$ in $G_{\ell}$. \item If $M$ is a perfect matching, then return $M$. \item For each object $b \in B$ that is unmatched in $M$ do: $\ell(b) = \ell(b) + 1$. \end{enumerate} \item Return ``$G$ has no popular assignment''. \end{enumerate} \fi \noindent{\em Running time.} Computing a maximum matching in $G_\ell$ takes $O(m\sqrt{n})$ time. In every iteration of the algorithm, the value $\sum_{b\in B}\ell(b)$ increases. So the number of iterations is at most $n^2$. Hence the running time of our algorithm is $O(m\cdot n^{5/2})$. \begin{theorem} \label{thm:pop} If our algorithm returns a matching $M$, then $M$ is a popular assignment in $G$. \end{theorem} Theorem~\ref{thm:pop} follows immediately from Lemma~\ref{lem:G-ell}. The more difficult part in our proof of correctness is to show that whenever our algorithm says that $G$ has no popular assignment, the instance~$G$ indeed has no popular assignment. This is implied by Theorem~\ref{thm:pop2}. \begin{theorem} \label{thm:pop2} Let $M^\star$ be a popular assignment in $G$ and let $\vec{\alpha}$ be a dual certificate of $M^\star$. Then for every $b \in B$, we have $|\alpha_b| \ge \ell(b)$, where $\ell(b)$ is the level of $b$ when our algorithm terminates. \end{theorem} If our algorithm terminates because $\ell(b) = n$ for some $b \in B$, then $|\alpha_b| \ge n$ for any dual certificate $\vec{\alpha}$ by Theorem~\ref{thm:pop2}. However $|\alpha_b| \le n-1$ by definition, a contradiction. So $G$ has no popular assignment. The following lemma is crucial for proving Theorem~\ref{thm:pop2}. It guarantees that when the algorithm increases $\ell(b)$ for some unmatched object $b \in B$, then the new level function does not exceed $|\alpha_b|$. \begin{lemma}\label{lem:alpha-vs-ell} Let $M^\star$ be a popular assignment, let $\vec \alpha$ be a dual certificate of $M^\star$, and let $\ell: B \rightarrow \mathbb{N}$ be such that $\ell(b) \leq |\alpha_b|$ for all $b \in B$. Let $M$ be a maximum matching in $G_\ell$ and let $b_0 \in B$ be an object that is left unmatched in $M$. Then $\ell(b_0) < |\alpha_{b_0}|$. \end{lemma} Before we turn to the proof of Lemma~\ref{lem:alpha-vs-ell}, we point out that Theorem~\ref{thm:pop2} follows from this lemma by a simple induction. \begin{proof}[of Theorem~\ref{thm:pop2}] Let $\ell_i$ be the level function on the set $B$ at the start of the $i$-th iteration of our algorithm. We are going to show by induction that for every $i$ we have $|\alpha_b| \ge \ell_i(b)$ for all~$b \in B$. This is true for $i = 1$, since $\ell_1(b) = 0$ for all $b \in B$. Now suppose that $|\alpha_b| \ge \ell_i(b)$ for all $b \in B$. Let $b_0 \in B$. If $b_0$ is matched in the maximum matching $M$ in $G_{\ell_i}$, then we know $\ell_{i+1}(b_0) = \ell_{i}(b_0) \leq |\alpha_{b_0}|$. If $b_0$ is left unmatched in $M$, then $\ell_{i+1}(b_0) = \ell_{i}(b_0) + 1$ and $\ell_{i}(b_0) < |\alpha_{b_0}|$ by Lemma~\ref{lem:alpha-vs-ell}. Thus $\ell_{i+1}(b_0) \leq |\alpha_{b_0}|$ in either case, completing the induction. \qed \end{proof} \begin{proof}[of Lemma~\ref{lem:alpha-vs-ell}] By Lemma~\ref{lem:G-ell}, $M^\star$ is a perfect matching in $G_{\ell_{\vec\alpha}}$ where $\ell_{\vec\alpha}(b) = |\alpha_b|$ for~$b \in B$. Thus, the symmetric difference $M \oplus M^\star$ in $G$ contains an $M$-augmenting path~$P$ starting at~$b_0$. However, as $M$ is of maximum size in~$G_{\ell}$, the path $P$ must contain an edge that is not in~$E_{\ell}$. Let $(b_0, a_0, b_1, a_1, \dots, b_t, a_t)$ be any prefix of $P$ such that $(a_t, b_t) \notin E_{\ell}$; see Figure~\ref{fig:my_label2} for an illustration. Note that $(a_0, b_0)$ and $(a_t, b_t)$ are in $M^\star$, since $M$ leaves $b_0$ unmatched and $M \subseteq E_{\ell}$. Thus $(a_h, b_h) \in M^{\star} \subseteq E_{\ell_{\vec\alpha}}$ for all $h \in \{0, \dots, t\}$ and $(a_h, b_{h+1}) \in M \subseteq E_{\ell}$ for all $h \in \{0, \dots, t - 1\}$. We will show that $\ell(b_h) < \ell_{\vec\alpha}(b_h)$ for all $h \in \{0, \dots, t\}$, and thus in particular, $\ell(b_0) < \ell_{\vec\alpha}(b_0) = |\alpha_{b_0}|$. We first show that $\ell(b_t) < \ell_{\vec\alpha}(b_t)$. Assume for contradiction that $\ell(b_t) = \ell_{\vec\alpha}(b_t)$. Using the fact that $(a_t, b_t) \notin E_{\ell}$, one of the following cases must hold: \begin{itemize} \item[$\bullet$] $a_t$ has a neighbor in level at least $\ell(b_t)+2$, or \item[$\bullet$] $a_t$ has a neighbor in level $\ell(b_t)+1$ that is not dominated by $b_t$, or \item[$\bullet$] $a_t$ has a neighbor in level~$\ell(b_t)$ that is preferred to $b_t$. \end{itemize} As $\ell_{\vec\alpha}(b_t) = \ell(b_t)$ and $\ell_{\vec\alpha}(b) \ge \ell(b)$ for all $b \in B$, in each case we get $(a_t, b_t) \notin E_{\ell_{\vec\alpha}}$, a contradiction. Now suppose there is an index $h \in \{0, \dots, t-1\}$ with $\ell(b_{h+1}) < \ell_{\vec\alpha}(b_{h+1})$ but $\ell(b_h)= \ell_{\vec\alpha}({b_h})$. Recall that $(a_h,b_{h+1}) \in M \subseteq E_\ell$, which leaves us with the following possibilities: \begin{itemize} \item[$\bullet$] $\ell(b_{h+1}) \ge \ell(b_h) + 1$: then $\ell_{\vec\alpha}(b_{h+1}) \geq \ell_{\vec\alpha}(b_h) + 2$; \item[$\bullet$] $\ell(b_{h+1}) = \ell(b_h)$: then $a_h$ does not prefer $b_h$ to $b_{h+1}$, but $\ell_{\vec\alpha}(b_{h+1}) \ge \ell_{\vec\alpha}(b_{h}) + 1$; \item[$\bullet$] $\ell(b_{h+1}) = \ell(b_h) - 1$: then $a_h$ prefers $b_{h+1}$ to $b_h$, but $\ell_{\vec\alpha}(b_{h+1}) \ge \ell_{\vec\alpha}(b_{h})$. \end{itemize} In each of these cases, we get $(a_h,b_h) \notin E_{\ell_{\vec\alpha}}$ by the definition of $G_{\ell_{\vec\alpha}}$, again a contradiction. \qed \end{proof} We remark that if a popular assignment exists, then the algorithm returns a popular assignment~$M$ and a corresponding dual certificate $\vec\alpha$ such that $\ell_{\vec\alpha} \leq \ell_{\vec\alpha'}$ for any dual certificate $\vec\alpha'$ of any popular assignment $M'$. This shows that there is a unique minimal dual certificate in this sense. \paragraph{Relation to the popular matching algorithm.} It can be shown that for graphs corresponding to popular matching instances (i.e., those with last resort houses and dummy agents as described in Section \ref{app:pop-matching-reduction}) we can terminate our algorithm as soon as some object reaches level $2$. This is because in any such instance a dual certificate $\vec{\alpha}$ for a popular assignment satisfies $|\alpha_b| \leq 1$ for all $b \in B$. Note that this essentially leads to the popular matching algorithm by Abraham et al.~\cite{AIKM07}. \medskip We close this section by pointing out a generalization of Lemma~\ref{lem:alpha-vs-ell} that encapsulates the main argument of the preceding proof. This insight will be useful for generalizing our algorithmic result in the next two sections. \begin{lemma}\label{lem:alpha-vs-ell-general} Let $\ell, \ell': B \rightarrow \mathbb{N}$ be such that $\ell(b) \leq \ell'(b)$ for all $b \in B$. Let $M$ and $M'$ be matchings in~$G_\ell$ and~$G_{\ell'}$, respectively. Let $b_0 \in B$ be an object that is matched in $M'$ but not in $M$. Let $P$ be the path in $M \oplus M'$ containing~$b_0$. If $P$ contains an edge not in $E_\ell$, then $\ell(b_0) < \ell'(b_0)$. \end{lemma} \section{Finding a popular assignment with forced/forbidden edges} \label{sec:edge-restrictions} In this section we consider a variant of the \myproblem{popular assignment} problem where, in addition to our instance, we are given a set $F^+$ of \emph{forced} edges and a set $F^-$ of \emph{forbidden} edges, and we are looking for a popular assignment that contains $F^+$ and is disjoint from $F^-$. Observe that it is sufficient to deal with forbidden edges, since putting an edge $(a,b)$ into $F^+$ is the same as putting all the edges in the set $\{(a,b'): b' \in \mathsf{Nbr}(a) \textrm{ and } b' \neq b\}$ into $F^-$. \medskip \noindent{\em The \myproblem{popular assignment with forbidden edges} problem.} Given a bipartite graph $G = (A \cup B, E)$ where every $a \in A$ has preferences in partial order over her neighbors, together with a set $F \subseteq E$ of forbidden edges, does $G$ admit a popular assignment $M$ avoiding $F$, i.e., one where $M \cap F=\emptyset$? \medskip We will show that in order to deal with forbidden edges, it suffices to modify our algorithm in Section~\ref{sec:algo} as follows; see Algorithm~\ref{alg:popassignforbidden}. The only difference from the earlier algorithm is that we find a maximum matching in the subgraph $G_{\ell} - F$, i.e., on the edge set $E_{\ell}\setminus F$. \begin{algorithm} \caption{Finding a popular assignment with forbidden edges}\label{alg:popassignforbidden} \begin{algorithmic}[1] \ForAll{$b \in B$} $\ell(b) = 0$. \EndFor \While{$\ell(b) < n$ for all $b \in B$} \State Construct the graph $G_\ell = (A\cup B, E_\ell)$ and find a maximum matching $M$ in $G_\ell-F$. \If{$M$ is a perfect matching} \textbf{return} $M$. \EndIf \ForAll{$b \in B$ unmatched in $M$} $\ell(b) = \ell(b) + 1$. \EndFor \EndWhile \State \textbf{return} ``$G$ has no popular assignment with forbidden set $F$''. \end{algorithmic} \end{algorithm} \iffalse \begin{enumerate} \item Initialize $\ell(b) = 0$ for all $b \in B$. \item While $\ell(b) < n$ for all $b \in B$ do \begin{enumerate} \item Construct the graph $G_\ell = (A\cup B, E_\ell)$ and find a maximum matching $M$ in $G_\ell-F$. \item If $M$ is a perfect matching, then return $M$. \item For each object $b \in B$ left unmatched in $M$ do: $\ell(b) = \ell(b) + 1$. \end{enumerate} \item Return ``$G$ has no popular assignment with forbidden set $F$''. \end{enumerate} \fi \begin{theorem} \label{thm:edge-restrictions-algo} The above algorithm outputs a popular assignment avoiding $F$, if such an assignment exists in $G$. \end{theorem} \begin{proof} Recall that any perfect matching in $G_\ell$ is a popular assignment in $G$ by Lemma~\ref{lem:G-ell}. It is therefore immediate that if the above algorithm outputs a matching $M$, then $M$ is a popular assignment in $G$ that avoids~$F$. Let us now prove that if there exists a popular assignment $M^\star$ avoiding $F$, then our algorithm outputs such an assignment. Let $\vec{\alpha}$ be a dual certificate for $M^\star$. Let $\ell_i$ denote the level function at the beginning of iteration~$i$ of the algorithm. As in the proof of Theorem~\ref{thm:pop2}, we show by induction that $\ell_i(b) \leq |\alpha_b|$ for all $b \in B$ for any iteration $i$. This is clearly true initially with $\ell_1(b) = 0$ for all $b \in B$. To complete the induction, it suffices to show that $\ell_i(b_0) < |\alpha_{b_0}|$ for all $b_0 \in B$ that are unmatched by any maximum matching $M$ in~$G_{\ell_i}$. Since $M^\star$ is a perfect matching, the symmetric difference $M \oplus M^\star$ contains an $M$-augmenting path~$P$ starting at $b_0$. However, because $M$ has maximum size in $G_{\ell_i} - F$, the path $P$ must contain an edge $e \notin E_{\ell_i} \setminus F$. We have $(M \cup M^\star) \cap F = \emptyset$, thus we obtain $e \notin F$ and therefore $e \notin E_{\ell_i}$. Note that Lemma~\ref{lem:G-ell} implies $M^\star \subseteq E_{\ell_{\vec\alpha}}$ (recall that $\ell_{\vec\alpha}(b) = |\alpha_b|$ for all $b \in B$). Furthermore, $\ell_i(b) \leq \ell_{\vec\alpha}(b)$ for all $b \in B$ by our induction hypothesis. We can thus apply Lemma~\ref{lem:alpha-vs-ell-general} with $M' = M^\star$ and $\ell' = \ell_{\vec\alpha}$ to obtain $\ell_i(b_0) < \ell_{\vec\alpha}(b_0) = |\alpha_{b_0}|$, which completes the induction step. \qed \end{proof} \section{Finding an assignment with minimum unpopularity margin} \label{sec:min-unpopular} In this section we consider the \myproblem{$k$-\sf unpopularity-margin} problem in $G$. Section~\ref{algo:k-unpop-margin} has our algorithmic result and Section~\ref{hardness:k-unpop-margin} and Section~\ref{app:weak-rankings} contain our hardness results. \subsection{Our algorithm} \label{algo:k-unpop-margin} For any assignment $M$, recall that the optimal value of \ref{LP1} is $\max_N \Delta(N,M)=\mu(M)$, where the maximum is taken over all assignments $N$ in $G$. Consequently, $\mu(M)$ equals the optimal value of the dual linear program \ref{LP2} as well. Therefore, $\mu(M) = k$ if and only if there exists an optimal solution $\vec{\alpha}$ to \ref{LP2} for which $\sum_{u \in A \cup B} \alpha_u=k$. This leads us to a characterization of assignments with a bounded unpopularity margin that is a direct analog of Theorem~\ref{thm:certificate}. \begin{theorem} \label{thm:dual-cert-unpopular} $M$ is an assignment with $\mu(M) \leq k$ if and only if there exists a solution $\vec{\alpha}$ to~\ref{LP2} such that $\alpha_a \in \{0,1, \dots, n\}$ for all $a \in A$, $\alpha_b \in \{0,-1,\dots, -(n-1)\}$ for all $b\in B$, and $\sum_{u \in A \cup B} \alpha_u \leq k$. \end{theorem} \begin{proof}[of Theorems~\ref{thm:certificate} and \ref{thm:dual-cert-unpopular}] If there is an optimal solution~$\vec{\alpha}$ to \ref{LP2} such that $\sum_{u\in A\cup B}\alpha_u = 0$, then the optimal value of \ref{LP2} is 0 and hence, by LP-duality, the optimal value of \ref{LP1} is also~0. Thus~$\Delta(N,M) \le 0$ for any perfect matching $N$; in other words, $M$ is a popular assignment. Similarly, if there is an optimal solution~$\vec{\alpha}$ to \ref{LP2} such that $\sum_{u\in A\cup B}\alpha_u \leq k$, then~$\Delta(N,M) \le k$ for any perfect matching~$N$, so $\mu(M) \leq k$. We will now show the converse. Let $M$ be a perfect matching with $\mu(M) = k$; there exists a dual optimal solution $\vec{\alpha}$ such that $\sum_{u\in A\cup B}\alpha_u = k$. Moreover, we can assume $\vec{\alpha}\in\mathbb{Z}^{2n}$ due to the total unimodularity of the constraint matrix. We can also assume $\alpha_b \leq 0$ for all $b\in B$, because feasibility and optimality are preserved if we decrease $\alpha_b$ for all $b\in B$ and increase $\alpha_a$ for all $a\in A$ by the same amount. Let us choose $\vec{\alpha}$ such that $\sum_{b\in B} \alpha_b$ is maximal subject to the above assumptions. We claim that if there is no $b\in B$ with $\alpha_b = -r$ for some $r\in \mathbb{N}$, then there is no $b \in B$ with $\alpha_b \leq -(r+1)$. Suppose the contrary, and let $B'=\{b\in B: \alpha_b<-r\}$ and $A'=\{M(b): b \in B'\}$. Since $\alpha_a+\alpha_b\geq 0$ for every $(a,b)\in M$, we have $\alpha_a\geq r+1$ for every $a \in A'$. Let $\vec{\alpha}'$ be obtained by decreasing $\alpha_a$ by 1 for all $a\in A'$ and increasing $\alpha_b$ by 1 for all $b\in B'$. The dual feasibility constraints $\alpha'_a + \alpha'_b \ge \mathsf{wt}_M(a,b)$ can only be violated if $a \in A'$, $b \notin B'$, and $\alpha_a + \alpha_b = \mathsf{wt}_M(a,b)$. But this would imply $\alpha_a\geq r+1$, $\alpha_b\geq -r+1$ (since $b \notin B'$ and $\alpha_b$ cannot be $-r$), and $\alpha_a + \alpha_b = \mathsf{wt}_M(a,b)\leq 1$, a contradiction. Thus, $\vec{\alpha}'$ is also an optimal dual solution, and $\sum_{b\in B} \alpha'_b> \sum_{b\in B} \alpha_b$, contradicting the choice of~$\vec{\alpha}$. We have shown that the values that $\vec{\alpha}$ takes on $B$ are consecutive integers, so we obtain that $\alpha_b \in \{0,-1,-2,$ $\ldots,-(n-1)\}$ for all $b \in B$. Since $\alpha_a+\alpha_b\geq 0$ for every $(a,b)\in M$, we have $\alpha_a\geq 0$ for every $a \in A'$. To conclude the proof of Theorem \ref{thm:certificate}, observe that $M$ is an optimal primal solution when $k=0$, so $\alpha_a+\alpha_b=0$ for every $(a,b)\in M$. This implies that $\alpha_a \in \{0,1,2, \ldots,n-1\}$ for all $a \in A$. As for Theorem \ref{thm:dual-cert-unpopular}, let $N$ be a perfect matching that is optimal for~\ref{LP1}; then $\alpha_a+\alpha_b=\mathsf{wt}_M(a,b)\leq 1$ for every $(a,b)\in N$ by complementary slackness, and therefore $\alpha_a \leq n$ for all $a \in A$. \qed \end{proof} Generalizing the notion that we already used for popular assignments, we define a \emph{dual certificate} for an assignment $M$ with unpopularity margin $k$ as a solution $\vec{\alpha}$ to \ref{LP2} with properties as described in Theorem~\ref{thm:dual-cert-unpopular}. So let us suppose that $M$ is an assignment with $\mu(M) = k$ and $\vec{\alpha}$ is a dual certificate for $M$. We define the \emph{load} of~$(a,b) \in M$ as $\alpha_a+\alpha_b$, and we will say that an edge $(a,b) \in M$ is \emph{overloaded} (with respect to $\vec{\alpha}$), if it has a positive load, that is, $\alpha_a+\alpha_b>0$. Clearly, the total load of all edges in $M$ is at most $k$, moreover $\alpha_a + \alpha_b \ge \mathsf{wt}_M(a,b) = 0$ for every $(a,b) \in M$, so there are at most $k$ overloaded edges in $M$. Given a level function $\ell: B \rightarrow \mathbb{N}$ and an integer $\lambda \in \mathbb{N}$, we say that edge $(a,b)$ is \emph{$\lambda$-feasible}, if \begin{itemize}[leftmargin=25pt] \item[(i)] $b$ has level at least $\ell^*(a)-\lambda+1$ where $\ell^*(a)=\max_{b \in \mathsf{Nbr}(a)} \ell(b)$, or \item[(ii)] $b$ has level $\ell^*(a)-\lambda$ and $a$ has no neighbor in level $\ell^*(a)$ that she prefers to $b$, or \item[(iii)] $b$ has level $\ell^*(a)-\lambda-1$, $a$ prefers $b$ to each of her neighbors in level $\ell^*(a)$, and moreover, $a$ prefers none of her neighbors in level $\ell^*(a)-1$ to $b$. \end{itemize} Note that $0$-feasible edges are exactly those contained in the graph $G_\ell$ induced by levels $\ell(\cdot)$, as defined in Section~\ref{sec:algo}. The following observation follows directly from the constraints of \ref{LP2}. \begin{proposition} \label{prop:load+feasibility} Consider the level function $\ell_{\vec{\alpha}}$ where the level of any $b \in B$ is $\ell_{\vec{\alpha}}(b)=-\alpha_b$. Then any edge $e \in M$ with load $\lambda$ is $\lambda$-feasible. \end{proposition} Given a level function $\ell: B \rightarrow \mathbb{N}$ and a load capacity function $\lambda: E \rightarrow \mathbb{N}$, we define the graph \emph{induced by levels $\ell(\cdot)$ and load capacities $\lambda(\cdot)$} as $G_{\ell,\lambda}=(A \cup B, E_{\ell,\lambda})$ where an edge~$e$ is contained in~$E_{\ell,\lambda}$ if and only if $e$ is $\lambda(e)$-feasible. We are now ready to describe an algorithm for finding an assignment $M$ with $\mu(M) \leq k$ if such an assignment exists. Algorithm~\ref{alg:popassignmargin} starts by guessing the load $\lambda(e)$ for each edge $e$ of $E$. Then we use a variant of the algorithm for Theorem~\ref{thm:edge-restrictions-algo} that enables each edge $e$ with $\lambda(e) > 0$ to have positive load (so $G_{\ell,\lambda}$ will be used instead of $G_{\ell}$), and treats the overloaded edges as forced edges. \begin{algorithm}[h] \caption{Finding a popular assignment with unpopularity margin at most $k$}\label{alg:popassignmargin} \begin{algorithmic}[1] \ForAll{functions $\lambda:E \rightarrow \mathbb{N}$ with $\sum_{e \in E} \lambda(e) \leq k$} \State Set $K= \{e \in E: \lambda(e)>0\}$ as the edges which we will overload. \State Set $F=\{(a,b') \in E: (a,b) \in K, b' \neq b \}$ as the set of forbidden edges. \ForAll{$b \in B$} $\ell(b) = 0$. \EndFor \While{ $\ell(b) < n$ for all $b \in B$} \State Construct the graph $G_{\ell,\lambda}$ and find a maximum matching $M$ in $G_{\ell,\lambda} - F$. \If{$M$ is a perfect matching} \textbf{return} $M$. \EndIf \ForAll{$b \in B$ unmatched in $M$} $\ell(b) = \ell(b) + 1$. \EndFor \EndWhile \EndFor \State \textbf{return} ``$G$ has no assignment $M$ with $\mu(M) \leq k$''. \end{algorithmic} \end{algorithm} \iffalse \begin{itemize} \item[$-$] For each function $\lambda:E \rightarrow \mathbb{N}$ with $\sum_{e \in E} \lambda(e) \leq k$ do: \begin{itemize} \item[1.] Set $K=\{e \in E: \lambda(e)>0\}$ as the edges which we will overload. \item[2.] Set $F=\{(a,b') \in E: (a,b) \in K, b' \neq b \}$ as the set of forbidden edges. \item[3.] Initialize $\ell(b) = 0$ for all $b \in B$. \item[4.] While $\ell(b) < n$ for all $b \in B$ do \begin{enumerate} \item[(a)] Construct the graph $G_{\ell,\lambda}$ and find a maximum matching $M$ in $G_{\ell,\lambda} - F$. \item[(b)] If $M$ is a perfect matching, then return $M$. \item[(c)] For each $b \in B$ that is unmatched in $M$ do: $\ell(b) = \ell(b) + 1$. \end{enumerate} \end{itemize} \item[$-$] Return ``$G$ has no assignment $M$ with $\mu(M) \leq k$''. \end{itemize} \fi Observe that there are at most $m^k$ ways to choose the load capacity function $\lambda$, where $m=|E|$, by the bound $\sum_{e \in E} \lambda(e) \leq k$. Each iteration of the while-loop takes $O(m \sqrt{n})$ time and there are at most $m^k \cdot n^2$ such iterations. Thus the running time of the above algorithm is $O(m^{k+1} \cdot n^{5/2})$. \medskip \noindent{\bf Proof of Theorem~\ref{thm:unpopmargin-algo-xp}.} First, suppose that Algorithm~\ref{alg:popassignmargin} outputs an assignment $M$. Consider the values of $\lambda(\cdot)$ and $\ell(\cdot)$ at the moment the algorithm outputs $M$. Set $\alpha_b=-\ell(b)$ for each object, and $\alpha_a=-\alpha_b+\lambda(a,b)$ for each edge $(a,b) \in M$. From the definition of $G_{\ell,\lambda}$ and $\lambda$-feasibility, such a vector $\vec{\alpha}$ fulfills all constraints in \ref{LP2}. Hence, by $\sum_{u \in A \cup B} \alpha_u = \sum_{(a,b)\in M}\lambda(a,b) \leq k$, we obtain that~$\mu(M) \leq k$. Second, assume that $G$ admits an assignment $M^\star$ with $\mu(M^\star) \leq k$, and let $\vec{\alpha}$ be a dual certificate for~$M^\star$. We need to show that our algorithm will produce an output. Consider those iterations where~$\lambda(e)$ equals the load of each edge $e \in M^\star$; we call this the \emph{significant branch} of the algorithm. We claim that $|\alpha_b| \geq \ell(b)$ holds throughout the run of the significant branch. To prove our claim, we use the same approach as in the proof of Theorem~\ref{thm:edge-restrictions-algo}, based on induction. Clearly, the claim holds at the beginning of the branch; we need to show that $\ell(b)$ is increased only if $|\alpha_b| > \ell(b)$. So let $|\alpha_b| \geq \ell(b)$ for each $b \in B$ at the beginning of an iteration (steps~(6)--(8)), and consider an object $b$ whose value is increased at the end of the iteration. First, assume that $b$ is incident to some overloaded edge $(a,b)$ of $M^\star$ with load $\lambda(a,b)$. Since~$b$ is not matched in a maximum matching in $G_{\ell,\lambda}-F$, we know that the edge $(a,b) \in K$ is not $\lambda$-feasible with respect to $\ell(\cdot)$. However, by Proposition~\ref{prop:load+feasibility}, $(a,b)$ is $\lambda(a,b)$-feasible with respect to the level function $\ell_{\vec{\alpha}}$ where $\ell_{\vec{\alpha}}(b)=|\alpha_b|$. Recall that by our induction hypothesis, the $\ell_{\vec{\alpha}}$-level of any object is at least its $\ell$-level. Moreover, increasing the level of any object other than $b$ cannot result in making the edge $(a,b)$ a $\lambda(a,b)$-feasible edge. It follows that $\ell_{\vec{\alpha}}(b)=|\alpha_b|> \ell(b)$ must hold. Second, assume that $b$ is not incident to any overloaded edge. Consider the path $P$ in $M \oplus M^\star$ on which $b$ lies. Notice that, since the edges of $F$ are treated as forbidden edges, $M$ assigns each agent incident to some edge in $K$ either the object assigned to it by $M^\star$, or does not assign any object to it. Therefore, no such agent lies on the path~$P$. Consequently, we can apply Lemma~\ref{lem:alpha-vs-ell-general} to the matchings $M \cap P \subseteq E_{\ell}$ and $M^\star \cap P \subseteq E_{\ell_{\vec \alpha}}$. This yields $|\alpha_b| = \ell_{\vec \alpha}(b) > \ell(b)$, proving our claim. Finally, note that in the significant branch, no object may have $\ell$-level higher than $n-1$, as implied by the properties of $\vec{\alpha}$ stated in Theorem~\ref{thm:dual-cert-unpopular}. \qed \medskip \subsection{Hardness results} \label{hardness:k-unpop-margin} We now contrast Theorem~\ref{thm:unpopmargin-algo-xp} with Theorem~\ref{thm:unpopmargin-hardness} which states that finding an assignment with minimum unpopularity margin is $\mathsf{NP}$-hard and $\mathsf{W}_l[1]$-hard with respect to the parameter $k$, our bound on the unpopularity margin. A parameterized problem $Q$ is $\mathsf{W}_l[1]$-hard if there exists a linear FPT-reduction from the \myproblem{weighted antimonotone cnf 2-sat} (or \myproblem{wcnf 2sat$^-$}) problem\footnote{ The input to this problem is a propositional formula $\varphi$ in conjunctive normal form with only negative literals and clauses of size two, together with an integer parameter~$k$; the question is whether the formula can be satisfied by a variable assignment that sets exactly~$k$ variables to true.} to~$Q$~\cite{chen-w1-vs-eth-stronger}. Since \myproblem{wcnf 2sat$^-$} is a $\mathsf{W}[1]$-complete problem~\cite{downey-fellows-book}, $\mathsf{W}_l[1]$-hardness implies $\mathsf{W}[1]$-hardness. While the $\mathsf{W}[1]$-hardness of \myproblem{$k$-unpopularity margin} shows that it cannot be solved in $f(k)|I|^{O(1)}$ time for any computable function~$f$ unless $W[1]=FPT$ (where $|I|$ denotes the input length), the results of Chen et al.~\cite{chen-w1-vs-eth-stronger} enable us to obtain a tighter lower bound: the $\mathsf{W}_l[1]$-hardness of \myproblem{$k$-unpopularity margin} implies that it cannot even be solved in $f(k) |I|^{o(k)}$ time for any computable function~$f$, unless all problems in $\mathsf{SNP}$ are solvable in subexponential time -- a possibility widely considered unlikely. Therefore, Theorem~\ref{thm:unpopmargin-hardness} shows that our algorithm for Theorem~\ref{thm:unpopmargin-algo-xp} is essentially optimal. Note that the unpopularity margin of any assignment $M$ can be computed efficiently by determining the optimal value of \ref{LP1}, so the \myproblem{$k$-unpopularity margin} problem is in $\mathsf{NP}$. In the remainder of this section, we present a linear FPT-reduction from the \myproblem{Clique} problem to the \myproblem{$k$-unpopularity margin} problem where agents' preferences are weak rankings. By the work of Chen et al.~\cite{chen-w1-vs-eth-stronger}, the $\mathsf{W}_l[1]$-hardness of \myproblem{$k$-unpopularity margin} follows. Our reduction is a polynomial-time reduction as well, implying $\mathsf{NP}$-hardness for the case of weak rankings; note that this also follows easily from the $\mathsf{NP}$-hardness of finding a matching (not necessarily an assignment) with minimum unpopularity margin~\cite{McC08}, using our reduction from the \myproblem{popular matching} problem to the \myproblem{popular assignment} problem. Both the reduction presented in this section and the reduction from \myproblem{popular matching} in Section~\ref{app:pop-matching-reduction} use weak rankings. However, we prove the $\mathsf{NP}$-hardness of \myproblem{$k$-unpopularity margin} for strict rankings by reducing the problem with weak rankings to the case with strict rankings in Lemma~\ref{lem:reduction-weak-to-strict} in Section~\ref{app:weak-rankings}.\footnote{The reduction from weak to strict rankings increases the parameter $k$ by a non-constant term. Thus $\mathsf{W}_l[1]$-hardness does not carry over and the parameterized complexity of \myproblem{$k$-unpopularity margin} with strict rankings is still open; see the related open question in Section~\ref{sec:open-problems}.} Instead of giving a direct reduction from \myproblem{Clique}, we will use an intermediate problem that we call \myproblem{CliqueHog}. Given a graph $H$, we define a \emph{cliquehog} of size $k$ as a pair $(C,F)$ such that $C \subseteq V(H)$ is a clique of size $k$, and $F \subseteq E(H)$ is a set of edges that contains exactly two edges connecting $c$ to $V(H) \setminus C$, for each $c \in C$. The input of the \myproblem{CliqueHog} problem is a graph $H$ and an integer $k$, and it asks whether $H$ contains a \emph{cliquehog} of size $k$. \begin{lemma} The \myproblem{CliqueHog} problem is $\mathsf{NP}$-hard and $\mathsf{W}_l[1]$-hard with parameter $k$. \end{lemma} \begin{proof} We reduce from the \myproblem{Clique} problem. Given a graph $H=(V,E)$ and an integer $k$, we construct a graph $H'$ by adding $2|V|$ edges and $2|V|$ vertices to $H$ as follows: for each vertex $v$ of $H$ we introduce two new vertices $v'$ and $v''$, together with the edges $(v,v')$ and $(v,v'')$. It is then easy to see that $H$ contains a clique of size $k$ if and only if $H'$ contains a cliquehog of size $k$. The reduction is a linear FPT-reduction with parameter $k$, as well as a polynomial-time reduction. \qed \end{proof} Let us now prove Theorem~\ref{thm:unpopmargin-hardness} by presenting a reduction from the \myproblem{CliqueHog} problem. \smallskip \noindent {\bf Construction.} Let $H=(V,E)$ and $k$ be our input for \myproblem{CliqueHog}. We construct an instance~$G$ of the \myproblem{$k$-unpopularity margin} problem, with a set $A$ of agents and a set $B$ of objects as follows. For each $v \in V$, we define a vertex gadget $G_v$ containing agents $a_v^0$ and $a_v^1$ and objects~$b_v^0$ and~$b_v^1$. For each $e \in E$, we define an agent $a_e$ and an object $b_e$. Furthermore, we will use a set $A_D$ of~$|E|-\binom{k}{2}-2k$ dummy agents, and a set $B_D$ of~$|E|-\binom{k}{2}-2k$ artificial objects. We define the sets $A_V=\{a_v^i: v \in V, i \in \{0,1\}\}$, $B_V=\{b_v^i: v \in V, i \in \{0,1\}\}$, $A_E=\{A_e: e \in E\}$, and $B_E=\{b_e: e \in E\}$. We set $A=A_V \cup A_E \cup A_D$ and $B=B_V \cup B_E \cup B_D$. The preferences of the agents in $G$ are as follows (ties are simply indicated by including them as a set in the preference list): \medskip \begin{tabular}{lll} $a_v^i:$ & $\{b_e : e \textrm{ is incident to $v$ in $H$} \} \succ b_v^0 \succ b_v^1 \qquad$ & for each $v \in V$ and $i \in \{0,1\}$; \\ $a_e:$ & $b_e \succ B_D \cup \{b_x^0,b_y^0\} \succ \{b_x^1,b_y^1\}$ \qquad \qquad & for each $e=(x,y) \in E$; \\ $a_d:$ & $B_E$ & for each $a_d \in A_D$. \\ \end{tabular} \medskip We finish the construction by setting the bound for the unpopularity margin of the desired assignment as $k$. Clearly, this is a polynomial-time reduction, and also a linear FPT-reduction with parameter $k$, so it remains to prove that $H$ contains a cliquehog of size $k$ if and only if $G$ admits an assignment $M$ with unpopularity margin at most $k$. \begin{lemma} \label{lem:unpopmargin-reduction-dir1} If $(C,F)$ is a cliquehog in $H$ of size $k$, then $G$ admits an assignment $M$ with unpopularity margin at most $k$. \end{lemma} \begin{proof} Let $f_c^0$ and $f_c^1$ denote the two edges of $F$ connecting $c$ to $V \setminus C$ in $H$ (in any fixed order), and we set $F^i=\{f_c^i: c \in C\}$ for $i \in \{0,1\}$. \begin{figure}[h] \begin{center} \includegraphics[scale=1]{margin-w1hardness-gadgets.pdf} \caption{Illustration for the construction in the proof of Theorem~\ref{thm:unpopmargin-hardness}. The assignment $M$ defined in Lemma~\ref{lem:unpopmargin-reduction-dir1} is indicated by bold lines. Red, black, and blue edges have weight $+1$, $0$, and $-1$, respectively, according to $\mathsf{wt}_M(\cdot)$. The values of the dual certificate $\vec{\alpha}$ for $M$ are indicated by numbers within the circle (square) corresponding to the given agent (object, respectively). For some edges $(a_e,b_e)$ in $G$ we indicate only the corresponding edge $e$ of $H$ (see $(u,v)$, $(v,x)$ and $(v,y)$). The figure assumes $v \in C$ but $x,y \notin C$; note that the edge $(a_{(v,y)},b_v^1)$ is overloaded in~$M$. } \label{fig:margin-gadgets} \end{center} \end{figure} We define an assignment $M$ as follows; see Figure~\ref{fig:margin-gadgets} for an illustration. First, we arbitrarily assign the $|E|-\binom{k}{2}-2k$ objects in $\{b_e: e \notin E[C] \cup F\}$ to the dummy agents (where $E[C]$ denotes the set of those edges of $E$ whose both endpoints are in $C$). Second, we arbitrarily assign the artificial objects to the $|E|-\binom{k}{2}-2k$ agents in $\{a_e: e \notin E[C] \cup F\}$. To define $M$ on the remaining objects and agents, let \medskip \begin{tabular}{ll} $M(a_v^i)=b_v^i$ & for each $v \in V \setminus C$ and $i \in \{0,1\}$; \\ $M(a_v^i)=b_{f_v^i}$ \qquad \qquad & for each $v \in C$ and $i \in \{0,1\}$; \\ $M(a_e)=b_e$ & for each $e \in E[C]$; \\ $M(a_f)=b_v^i$ & for each $f \in F$ where $f=f_v^i$. \end{tabular} \medskip Observe that $M$ indeed assigns exactly one object to each agent. To show that $\mu(M) \leq k$, we define a dual certificate $\vec{\alpha}$ for $M$: \medskip \begin{tabular}{llll} $\alpha_{a_d}=0$ & for each $a_d \in A_D$; & $\alpha_{b_d}=-1$ & for each $b_d \in B_D$; \\ $\alpha_{a_v^0}=1$ \qquad \qquad & for each $v \in V \setminus C$; & $\alpha_{b_v^0}=-1$ \qquad \qquad & for each $v \in V \setminus C$; \\ $\alpha_{a_v^1}=2$ & for each $v \in V \setminus C$; & $\alpha_{b_v^1}=-2$ & for each $v \in V \setminus C$; \\ $\alpha_{a_v^i}=0$ & for each $v \in C$ and $i \in \{0,1\}$; \qquad \qquad & $\alpha_{b_v^i}=-1$ & for each $v \in C$ and $i \in \{0,1\}$; \\ $\alpha_{a_e}=1$ & for each $e \in E \setminus (F^1 \cup E[C])$; & $\alpha_{b_e}=0$ & for each $e \in E$; \\ $\alpha_{a_e}=2$ & for each $e \in F^1$; & \\ $\alpha_{a_e}=0$ & for each $e \in E[C]$. \end{tabular} \medskip It is straightforward to check that $\vec{\alpha}$ is indeed a dual certificate, that is, it satisfies the constraints of \ref{LP2}. Since $\sum_{u \in A \cup B} \alpha_u=k$, assignment $M$ indeed has unpopularity margin at most $k$. \qed \end{proof} We now show that any assignment in $G$ with unpopularity margin at most $k$ implies the existence of a cliquehog of size $k$ in $H$. We first establish a useful assumption that we will show is without loss of generality. We say that an assignment $M$ has a \emph{nice structure}, if for each $e \in E$ one of the following cases holds true: \begin{itemize} \item[$\bullet$] $M(a_e) = b_e$, or \item[$\bullet$] $M(a_e) = b^i_x$ and $M(a^i_x) = b_e$ for some endpoint $x$ of edge $e$ in $H$ and $i \in \{0, 1\}$, or \item[$\bullet$] $M(a_e) \in B_D$ and $M(b_e) \in A_D$. \end{itemize} \begin{lemma} If there exists an assignment in $G$ with unpopularity margin at most $k$, then there exists an assignment in $G$ with unpopularity margin at most $k$ that has a nice structure. \end{lemma} \begin{proof} Let $M'$ be any assignment in $G$. By switching the names of the identical agents $a^0_x$ and $a^1_x$ wherever necessary, we can assume that $M'(a^i_x) \in \{b^i_x\} \cup B_E$ for all $x \in V$ and $i \in \{0, 1\}$. We construct a new assignment~$M$ as follows: For each $e \in E$, let $M(a_e) = M'(a_e)$. For each $x \in V$ and each $i \in \{0, 1\}$, if $M'(b^i_x) = a_e$ for some $e \in E$, then let $M(a^i_x) = b_e$; otherwise let $M(a^i_x) = b^i_x$. Assign the unmatched objects in $B_E$ arbitrarily to the dummy agents in $A_D$. Note that for every agent $a \in A$, we have $M(a) = M'(a)$ or $M(a)$ and $M'(a)$ are both in $B_E$. Since every agent is indifferent between all her neighbors in $B_E$, the assignment $M$ has the same unpopularity margin as $M'$. \qed \end{proof} In what follows, let $M$ be an assignment in $G$ with unpopularity margin at most $k$ and a nice structure, and let $\vec{\alpha}$ be a dual certificate for $M$. We will construct a cliquehog of size $k$ in $H$. We define a partition $(E_0,E_1,E_2)$ of those edges $e$ in $E$ for which $M(a_e) \notin B_D$. For any edge~$e \in E$, we decide which set of the partition $e$ belongs to using the following procedure. \begin{enumerate} \item If $M(a_e) = b_e$ and $\alpha_{a_e}+\alpha_{b_e} > 0$, then we put $e$ into $E_0$. \item If $M(a_e) = b_e$ and $\alpha_{a_e}+\alpha_{b_e}=0$, then we put $e$ into $E_1$. \item If $M(a_e)$ is an object in $G_x$ or $G_y$ where $e=(x,y)$, then we put $e$ into $E_2$. \end{enumerate} We also define $S$ as the set of those vertices $v \in V$ for which the vertex gadget $G_v$ contains an agent or object that is incident to an overloaded edge of $M$. Note that since no agent in a vertex gadget is connected to an object in another vertex gadget, and moreover, the overloaded edges of~$M$ corresponding to edges in~$E_0$ are not incident to any vertex gadget, we know that \begin{equation} \label{eq:overloaded-edges} |S|+ |E_0|\leq \mu(M) \leq k. \end{equation} We will show that $(S, E_2)$ is a cliquehog of size $k$. To do so, we first establish two helpful lemmas. The first shows that $S$ contains all nodes $x \in V$ for which at least one of the objects $b^0_x$ and $b^1_x$ is matched to an edge agent. This implies that every edge in $E_2$ is incident to a node in $S$. The second lemma shows that all endpoints of edges in $E_1$ are contained in $S$. \begin{lemma} \label{lem:E2} Let $x \in V$. If $M(b^0_x) \in A_E$ or $M(b^1_x) \in A_E$, then $x \in S$. \end{lemma} \begin{proof} We distinguish two cases. First, suppose that $M(b_x^0) = a_e$ for some $e \in E$. Recall that this implies $M(a^0_x) = b_e$, because $M$ has a nice structure. From the preferences of agents and the feasibility of~$\vec{\alpha}$, we get the three inequalities $\alpha_{a^0_x} + \alpha_{b^1_x} \geq -1$ and $\alpha_{M(b^1_x)} + \alpha_{b^0_x} \geq 1$ and $\alpha_{a_e} + \alpha_{b_e} \geq 1$. Adding these inequalities, we observe that at least one of the sums $\alpha_{a^0_x} + \alpha_{b_e}$ or~$\alpha_{b^1_x} + \alpha_{M(b^1_x)}$ or~$\alpha_{a_e} + \alpha_{b^0_x}$ must be positive, and thus the corresponding edge in $M$ must be overloaded. Second, suppose that $M(b^0_x) \notin A_E$ but $M(b^1_x) = a_e$ for some $e \in E$. Recall that this implies $M(a^0_x) = b^0_x$ and $M(a^1_x) = b_e$, because $M$ has a nice structure. Again from the preferences of agents and the feasibility of $\vec{\alpha}$, we obtain the three inequalities $\alpha_{a_e} + \alpha_{b_x^0} \geq 1$ and $\alpha_{a_x^0} + \alpha_{b_e} \geq 1$ and $\alpha_{a_x^1} + \alpha_{b_x^1} \geq -1$. Adding these inequalities, we see that at least one of the sums $\alpha_{a_e} + \alpha_{b_x^1}$ or $\alpha_{a_x^0} + \alpha_{b_x^0}$ or $\alpha_{a_x^1} + \alpha_{b_e}$ must be positive, and so the corresponding edge in $M$ must be overloaded. \qed \end{proof} \begin{lemma} \label{cor:E1} If $e = (x,y) \in E_1$, then $\{x,y\} \subseteq S$. \end{lemma} \begin{proof} We only show that $x \in S$. The proof for $y \in S$ follows by symmetry. If $M(b^0_x) \in A_E$ or~$M(b^1_x) \in A_E$, Lemma~\ref{lem:E2} implies that $x \in S$. So we can assume that $M(b^0_x) = a^0_x$ and $M(b^1_x) = a^1_x$ by the nice structure of $M$. By the preferences of agents and feasibility of $\vec{\alpha}$, we obtain the three inequalities $\alpha_{a^0_x} + \alpha_{b_e} \geq 1$ and $\alpha_{a^1_x} + \alpha_{b^0_x} \geq 1$ and $\alpha_{a_e} + \alpha_{b^1_x} \geq -1$. Adding up these inequalities, we observe that at least one of the sums $\alpha_{a^0_x} + \alpha_{b^0_x}$ or $\alpha_{a^1_x} + \alpha_{b^1_x}$ or $\alpha_{a_e} + \alpha_{b_e}$ must be positive. By~$e \in E_1$, the third expression is equal to $0$, and so one of the former two has to be positive. This implies that at least one of the two corresponding edges of $M$ in $G_x$ is overloaded. \qed \end{proof} We are now ready to prove Lemma~\ref{lem:unpopmargin-reduction-dir2}, which together with Lemma~\ref{lem:unpopmargin-reduction-dir1} proves Theorem~\ref{thm:unpopmargin-hardness}. \begin{lemma} \label{lem:unpopmargin-reduction-dir2} If the constructed instance~$G$ admits an assignment $M$ with unpopularity margin at most $k$, then $H$ contains a cliquehog of size $k$. \end{lemma} \begin{proof} By Lemma~\ref{cor:E1} we know that any edge $e \in E_1$ must have both of its endpoints in $S$, yielding \begin{equation} \label{eq:E1+E5} |E_1| \leq \binom{|S|}{2}. \end{equation} By Lemma~\ref{lem:E2}, each edge $e \in E_2$ must have its agent~$a_e$ assigned to an object in a vertex gadget~$G_v$ for some~$v \in S$. By~Inequality~(\ref{eq:overloaded-edges}) there are at most $2|S|$ such objects, so we obtain \begin{equation} \label{eq:E2} |E_2| \leq 2|S|. \end{equation} Recall that by construction of $G$ and the definition of the partition $(E_0,E_1,E_2)$, we know \begin{align*} \binom{k}{2}+2k = |E|-|B_D|= |E_1| + |E_2| + |E_0| \leq \binom{|S|}{2} + |S| + k \end{align*} where the inequality follows from combining Inequalities~(\ref{eq:overloaded-edges}), (\ref{eq:E1+E5}), and (\ref{eq:E2}). Hence, by $|S| \leq k$ we obtain $|S|=k$. Moreover, every inequality we used must hold with equality. In particular, this implies $|E_1|=\binom{k}{2}$, which can only happen if there are $\binom{k}{2}$ edges in $H$ (namely, those in $E_1$) with both of their endpoints in $S$. In other words, $S$ forms a clique in $H$. Additionally, (\ref{eq:E2}) must also hold with equality, so $|E_2|=2|S|=2k$. Since every edge in $E_2$ is incident to a vertex of $S$ by Lemma~\ref{lem:E2}, but is not contained in $E[S]$ (because $E[S]=E_1 \subseteq E \setminus E_2$), and any $x \in S$ is incident to at most two edges of $E_2$ (by the definition of $E_2$), we can conclude that $(S,E_2)$ is a cliquehog of size~$k$. \qed \end{proof} \subsection{A reduction from weak rankings to strict for the \myproblem{$k$-unpopularity margin} problem} \label{app:weak-rankings} \begin{lemma} \label{lem:reduction-weak-to-strict} Let $G$ be an instance with weak rankings and $n$ agents. Then we can compute in polynomial time an instance $G'$ with strict rankings and an integer $q \in \mathcal{O}(n)$ such that $G$ admits an assignment with unpopularity margin $k$ if and only if $G'$ admits an assignment with unpopularity margin $k+q$ for any $k \in [n]$. \end{lemma} \begin{proof} Let $G$ be an instance with weak rankings. We divide the proof into two parts. In the first part we show that we can assume without loss of generality that the set of agents in $G$ can be partitioned into two groups, $A_{\succ}$ and $A_{\sim}$, where agents in $A_{\succ}$ have strict preferences over the objects in their neighborhood and agents in $A_{\sim}$ are indifferent among all their neighboring objects. Starting from such an instance, we then prove the lemma. \medskip \textbf{Part I.} Starting from a graph $G$ with weak rankings, we create a graph $\hat{G}$ and preferences as follows: For every agent $v$ in $G$, let $B_v^{(1)} \succ \dots \succ B_v^{(r_v)}, r_v \in \{1,\dots,m\}$ be the weak ranking over its neighboring objects. We add agent~$v$ to~$\hat{G}$, and for each $i \in \{1,\dots,r_v\}$ we further add a new agent~$a_{v}^{(i)}$ and a new object~$b_{v}^{(i)}$ to $\hat{G}$. The new agent~$a_{v}^{(i)}$ is connected to---and defined to be indifferent among---all objects in $B_v^{(i)} \cup \{b_{v}^{(i)}\}$. Lastly, we introduce edges from~$v$ to all objects in~$\bigcup_{i=1}^{r_v} b_v^{(i)}$, with preferences $b_{v}^{(1)} \succ b_{v}^{(2)} \succ \dots \succ b_{v}^{(r_v)}$. In $\hat{G}$ we can partition the set of nodes into~$A_{\succ}$, containing copies of agents in $G$, and $A_{\sim}$, containing the newly introduced agents. Agents in~$A_{\succ}$ have strict preferences and all agents in $A_{\sim}$ are indifferent among all their neighbors. Below, we show that the two instances are essentially equivalent. \begin{figure} \centering \begin{tikzpicture} \draw[fill=black!10,draw=none] (0.3,-1.1) ellipse (1cm and .5cm); \draw[fill=black!10,draw=none] (1.2,.7) ellipse (.7cm and .6cm); \node[circle,fill=black,label=left:$v$,inner sep = 2pt] (v) at (0,0){}; \node[rectangle, fill=black,inner sep = 2pt] (b1) at (1,1){}; \node[rectangle, fill=black,inner sep = 2pt] (b2) at (1.5,.5){}; \node[rectangle, fill=black,inner sep = 2pt] (b3) at (-.2,-1.2){}; \node[rectangle, fill=black,inner sep = 2pt] (b4) at (.3,-1.2){}; \node[rectangle, fill=black,inner sep = 2pt] (b5) at (.9,-1){}; \draw (v) -- (b1) node [near start, above] {\scriptsize $1$}; \draw (v) -- (b2) node [shift={(190:0.95)}] {\scriptsize $1$}; \draw (v) -- (b3) node [midway, left] {\scriptsize $2$}; \draw (v) -- (b4) node [shift={(110:0.7)}, right] {\scriptsize $2$}; \draw (v) -- (b5) node [near start, right] {\scriptsize $2$}; \node at (-1.1,-1.4) {$B_v^{(2)}$}; \node at (1.2,1.7) {$B_v^{(1)}$}; \draw (3,-1.6) -- (3,2); \node at (-1.2,1.5) {$G$}; \end{tikzpicture} \begin{tikzpicture}\hspace{.7cm} \draw[fill=black!10,draw=none] (1.8,-1.6) ellipse (1cm and .5cm); \draw[fill=black!10,draw=none] (2.7,.7) ellipse (.7cm and .6cm); \node[circle,fill=black,label=left:$v$,inner sep = 2pt] (v) at (0,0.2){}; \node[rectangle, fill=black,inner sep = 2pt,label=above:$b_v^{(1)}$] (c1) at (.7,.75){}; \node[circle, fill=black,inner sep = 2pt,label=above:$a_v^{(1)}$] (d1) at (1.5,.77){}; \node[rectangle,label=left:$b_v^{(2)}$, fill=black,inner sep = 2pt] (c2) at (0,-.7){}; \node[circle, fill=black,label=left:$a_v^{(2)}$, inner sep = 2pt] (d2) at (0.5,-1.2){}; \node[rectangle, fill=black,inner sep = 2pt] (b1) at (2.5,1){}; \node[rectangle, fill=black,inner sep = 2pt] (b2) at (3,.5){}; \node[rectangle, fill=black,inner sep = 2pt] (b3) at (1.3,-1.7){}; \node[rectangle, fill=black,inner sep = 2pt] (b4) at (1.8,-1.7){}; \node[rectangle, fill=black,inner sep = 2pt] (b5) at (2.4,-1.5){}; \draw (v) -- (c1) node [shift={(235:0.5)}] {\scriptsize $1$}; \draw (v) -- (c2) node [shift={(75:0.5)}] {\scriptsize $2$}; \draw (c1) -- (d1) \draw (c2) -- (d2) \draw (d1) -- (b1) \draw (d1) -- (b2) \draw (d2) -- (b3) \draw (d2) -- (b4) \draw (d2) -- (b5) \node at (-.5,1.2) {$\hat{G}$}; \end{tikzpicture} \caption{Illustration of the first part of the proof of Lemma \ref{lem:reduction-weak-to-strict}. The left side illustrates the neighborhood of a fixed node $v$ within the original graph $G$. The right side illustrates the corresponding situation within the graph~$\hat{G}$. Agents are depicted by circles and objects by squares. Labels of the edges indicate the rank of the edge within the ranking of the incident agent. Agents $a_{v}^{(1)}$ and $a_{v}^{(2)}$ are indifferent among all their neighbors, hence, their labels are omitted. } \label{fig:reduction-weak-to-structuredWeak} \end{figure} More precisely, we show that there exists a bijection $f$ mapping assignments in $G$ to assignments in $\hat{G}$ such that $\Delta(N,M) = \Delta(f(N),f(M))$ for any two assignments $M$ and $N$ in $G$. Let $M$ be an assignment in $G$. We start with $f(M) = \emptyset$. For every edge $(v,w) \in M$ we do the following: Let the preferences of~$v$ be~$B_v^{(1)} \succ \dots \succ B_v^{(r_v)}$, and let $i \in \{1,\dots,r_v\}$ be such that $w \in B_v^{(i)}$. Then, we add the edges $(v,b_v^{(i)})$ and $(a_v^{(i)}, w )$ to $f(M)$ (see Figure~\ref{fig:reduction-weak-to-structuredWeak}). Moreover, for all indices $j \in \{1, \dots, r_v\} \setminus \{i\}$ we add the edge $(a_v^{(j)},b_v^{(j)})$ to $f(M)$. It is easy to see that this is a bijection. Since for every agent in $A_{\succ}$ the rank of its partner in~$M$ equals the rank of its partner in~$f(M)$ and agents in~$A_{\sim}$ are indifferent among all their neighbors, we get $\Delta(N,M) = \Delta(f(N),f(M))$. \medskip \textbf{Part II.} Due to part I, we can assume that the agents in $G$ are partitioned into sets~$A_{\succ}$ and~$A_{\sim}$ such that agents in $A_{\succ}$ have strict preferences over objects and the agents in $A_{\sim}$ are indifferent among all their neighboring objects. Starting from the graph~$G$, we create a graph~$G'$ with strict rankings as follows. We first copy all agents and objects to $G'$. Then for each $a \in A_{\sim}$ we introduce two new agents $a'$ and $a''$ and two new objects $b'_a$ and~$b''_a$. We add all possible edges from $\{a,a',a''\}$ to $\mathsf{Nbr}_{G}(a) \cup \{b'_{a},b''_{a}\}$ (see Figure~\ref{fig:my_label}). The preferences of agents $a,a'$, and $a''$ are identical, namely, $b'_{a}$ is their first choice, $b''_{a}$ their second choice, followed by all objects in $\mathsf{Nbr}_G(a)$ in arbitrary order. We define a function $f$ which maps assignments in $G'$ to assignments in $G$. Let $M'$ be an assignment in $G'$. For each $(a,b) \in M'$ where $a \in A_{\succ}$, we add the edge $(a,b)$ to $f(M')$. Now, observe that for every $a \in A_{\sim}$, exactly one of the nodes $a,a',a''$ is matched to a node of the original neighborhood, i.e., $\mathsf{Nbr}_{G}(a)$. Let $b$ be the assigned object. Then we add $(a,b)$ to $f(M')$. It is easy to see that $f(M')$ is then an assignment in $G$. We continue by observing that \begin{enumerate}[label=(\roman*),leftmargin=25pt] \item $f$ is surjective\label{item:fsurjective}, and \item for all $ a \in A_{\succ}$ and two assignment $M'$, $N'$ in $G'$: $M' \succ_a N'$ if and only if $f(M') \succ_a f(N')$. \label{item:equalvotes} \end{enumerate} For \ref{item:fsurjective}, note that for every assignment $M$ in $G$ we can create an assignment $M'$ in $G$ such that $f(M')=M$ holds, as follows: Copy all edges from $M$ to $M'$ and then add for every $a \in A_{\sim}$ the edges $(a',b_a')$ and $(a'',b_a'')$. Clearly, $f(M') = M$. For \ref{item:equalvotes} observe that for all assignments $M'$ in $G'$, agents in $A_{\succ}$ have the same assigned object in $M'$ as in $f(M')$. We define $q= |A_{\sim}|$ and show that $G$ admits an assignment with unpopularity margin at most~$k$ if and only if $G'$ admits an assignment with unpopularity margin at most~$k+q$, for any $k \in \mathbb{N}$. \smallskip \begin{figure} \centering \begin{tikzpicture} \draw[fill=black!10,draw=none] (1.1,.2) ellipse (.7cm and 1.2cm); \node at (1.7,1.8) {$\mathsf{Nbr}_G(a)$}; \node[circle,fill=black,label=left:$a$,inner sep = 2pt] (a) at (0,.3){}; \node[rectangle, fill=black,inner sep = 2pt] (b1) at (1,1){}; \node[rectangle, fill=black,inner sep = 2pt] (b2) at (1.5,.5){}; \node[rectangle, fill=black,inner sep = 2pt] (b3) at (1.3,-.3){}; \node[rectangle, fill=black,inner sep = 2pt] (b4) at (.7,-.5){}; \draw (a) -- (b1) node [near start, above] {\scriptsize $1$}; \draw (a) -- (b2) node [shift={(180:0.95)}] {\scriptsize $1$}; \draw (a) -- (b3) node [shift={(145:0.8)}] {\scriptsize $1$}; \draw (a) -- (b4) node [near start, below] {\scriptsize $1$}; \draw (3.5,-1.2) -- (3.5,2.1); \node at (-.7,1.7){$G$}; \end{tikzpicture} \begin{tikzpicture}\hspace*{.4cm} \node at (-2.5,1.2){$G'$}; \draw[fill=black!10,draw=none] (1.5,0) ellipse (.5cm and 1.7cm); \node[circle,fill=black,label=above:$a$,inner sep = 2pt] (a) at (0,1){}; \node[circle, fill=black,label=above:$a'$,inner sep = 2pt] (ap) at (0,0){}; \node[circle, fill=black,label=above:$a''$,inner sep = 2pt] (app) at (0,-1){}; \node[rectangle, fill=black,label=left:$b'_a$,inner sep = 2pt] (bp) at (-1.5,.5){}; \node[rectangle, fill=black,label=left:$b''_a$,inner sep = 2pt] (bpp) at (-1.5,-.5){}; \node[rectangle, fill=black,inner sep = 2pt] (b1) at (1.5,1.5){}; \node[rectangle, fill=black,inner sep = 2pt] (b2) at (1.5,.5){}; \node[rectangle, fill=black,inner sep = 2pt] (b3) at (1.5,-.5){}; \node[rectangle, fill=black,inner sep = 2pt] (b4) at (1.5,-1.5){}; \draw (a) -- (bp) node [near start, above] {\scriptsize $1$}; \draw (bp) -- (ap) node [shift={(140:0.45)}] {\scriptsize $1$}; \draw (bp) -- (app) node [shift={(147:0.55)}] {\scriptsize $1$}; \draw (bpp) -- (a) node [shift={(212:0.55)}] {\scriptsize $2$}; \draw (bpp) -- (ap) node [shift={(180:0.45)}] {\scriptsize $2$}; \draw (bpp) -- (app) node [shift={(180:0.55)}] {\scriptsize $2$}; \draw (a) -- (b1); \draw (a) -- (b2); \draw (a) -- (b3); \draw (a) -- (b4); \draw (ap) -- (b1); \draw (ap) -- (b2); \draw (ap) -- (b3); \draw (ap) -- (b4); \draw (app) -- (b1); \draw (app) -- (b2); \draw (app) -- (b3); \draw (app) -- (b4); \end{tikzpicture} \caption{Illustration of the second part of the proof of Lemma \ref{lem:reduction-weak-to-strict}. The left side illustrates the neighborhood of an agent~$a$, indifferent among all its neighbors, within the graph~$G$. The right side captures the corresponding gadget in the graph~$G'$. Labels on the edges indicate the preferences of agents. The ranks of edges between $\{a,a',a''\}$ and $\mathsf{Nbr}_G(a)$ can be chosen arbitrarily (but need to be larger than $2$), hence, these labels are omitted.} \label{fig:my_label} \end{figure} \smallskip \noindent {\bf Direction ``$\Rightarrow$''.} Assume that $G$ admits an assignment~$M$ with unpopularity margin at most~$k$. Choose an assignment~$M'$ from~$G'$ such that $f(M')=M$ holds (such an $M'$ is guaranteed to exist by \ref{item:fsurjective}). Let $N'$ be an assignment in~$G'$ maximizing $\Delta(N',M')$, so $\mu(M')=\Delta(N',M')$. Since $\Delta(f(N'),f(M')) \leq \max_N \Delta(N,M) = k$, we know by \ref{item:equalvotes} that agents in $A_{\succ}$ contribute at most~$k$ to $\Delta(N',M')$. Moreover, we claim that agents not in $A_{\succ}$ contribute at most $q$ to $\Delta(N',M')$. To see this, consider the gadget for some agent~$a \in A_{\sim}$. We distinguish two cases. First, assume that the agent from $\{a,a',a''\}$ which is assigned an object in $\mathsf{Nbr}_G(a)$ is the same in assignments $M'$ and~$N'$; w.l.o.g. we assume it is agent~$a$. Then $a'$ and $a''$ together contribute $0$, and $a$ at most~$1$ to~$\Delta(N',M')$. Second, assume w.l.o.g. that $a$ is assigned some object in $\mathsf{Nbr}_G(a)$ by~$M'$, while $a'$ is assigned some object in~$\mathsf{Nbr}_G(a)$ by~$N'$. Then $a$ and $a'$ together contribute~$0$,and $a''$ at most~$1$. As this holds for every gadget belonging to agents in $A_{\sim}$, this proves $\Delta(N',M') \leq k+q$. \medskip \noindent {\bf Direction ``$\Leftarrow$''.} For the other direction, assume that $G'$ admits an assignment $M'$ with unpopularity margin at most $k+q$. We claim that $f(M')$ has unpopularity at most $k$. Assume for contradiction that there exists some assignment $N$ in $G$ with $\Delta(N,f(M')) > k$. We construct $N'$ as follows. For every agent~$a \in A_{\succ}$, we let $N'(a)=N(a)$. Next, for every agent~$a \in A_{\sim}$, let $b_{M}$ be its assigned object in $f(M')$ and $b_N$ be its assigned object in $N$. We can assume w.l.o.g. that $a$ is matched to~$b_M$ in~$M'$, $a'$ is matched to~$b'_a$, and $a''$ is matched to~$b''_a$. In~$N'$ we match $a'$ to~$b_N$, $a''$ to~$b'_a$, and $a$ to~$b''_a$. Then $a$, $a'$, and $a''$ together contribute exactly~$1$ to~$\Delta(N',M')$. Using the same argument for all $a \in A_{\sim}$ and \ref{item:equalvotes} yields that $\mu(M') \geq \Delta(N',M') > k + q$, a contradiction. \qed \end{proof} \section{The minimum-cost popular assignment problem} \label{sec:mincost} \paragraph{The \myproblem{minimum-cost popular assignment} problem.} Given a bipartite graph $G = (A \cup B, E)$ where every agent has preferences in partial order over her adjacent objects, together with a cost function $c:E \rightarrow \mathbb{R}$ on the edges and a budget $\beta \in \mathbb{R}$, does $G$ admit a popular assignment of total cost at most $\beta$? First we prove Theorem~\ref{thm:mincost-nphard} which shows the \myproblem{minimum-cost popular assignment} problem is $\mathsf{NP}$-hard when edge costs are in $\{0,1,+\infty\}$. This is weaker than Theorem~\ref{thm:mincost-nphard-01} which says this problem is $\mathsf{NP}$-hard even when edge costs are in $\{0,1\}$. The proof of Theorem~\ref{thm:mincost-nphard} presents the main ideas used in the proof of Theorem~\ref{thm:mincost-nphard-01}. \begin{theorem} \label{thm:mincost-nphard} The \myproblem{minimum-cost popular assignment} problem is $\mathsf{NP}$-complete, even if each edge cost is in $\{0,1,+\infty\}$ and agents have strict preferences. \end{theorem} \begin{proof} Since we can check for any assignment of objects to agents, whether it is popular and its cost is within the budget, the problem is clearly in $\mathsf{NP}$. We now present a reduction from the \myproblem{Vertex Cover} problem, whose input is a graph $H=(V,E)$ and an integer $k$, and asks whether there exists a set $S$ of at most $k$ vertices in $H$ such that each edge of $E$ has one of its endpoints in $S$. \paragraph{Construction.} Let us construct our instance for the \myproblem{minimum-cost popular assignment} problem; see Figure~\ref{fig:mincost-gadgets}. We define the set $A$ of agents and the set $B$ of objects by introducing the following: \begin{itemize} \item two \emph{level-setting gadgets} $G_\ell^0$ and $G_\ell^1$, with $G_\ell^i$ consisting of a single edge connecting agent $a_{\ell}^i$ and object $b_{\ell}^i$, for each $i \in \{0,1\}$; \item a \emph{vertex gadget} for each $x \in V$, consisting of a cycle of length~$4$, containing agents $a_x^0$ and $a_x^1$, and objects $b_x^0$ and $b_x^1$; \item an \emph{edge gadget} for each $e \in E$, consisting of a cycle of length~$8$ containing agents $a_e^0, \dots a_e^3$ and objects $b_e^0, \dots, b_e^3$. \end{itemize} We let $A_V$ and $A_E$ contain agents of all vertex and edge gadgets, respectively, and we define the sets $B_V$ and $B_E$ of objects analogously. Additionally, we introduce a set $F$ of \emph{inter-gadget edges}. First, we add edges of $$F_{\ell}=\{(a_\ell^1,b_\ell^0),(a_\ell^0,b_\ell^1)\}$$ to the level-setting gadgets. Second, in order to enforce certain lower bounds on the dual certificate, we connect some agents and objects in the level-setting gadgets with those in the vertex and edge gadgets, by adding the edges of \begin{equation} \label{eqn-Fbnd-def} F_{\textup{bnd}}=\{(a_x^0,b_\ell^0):x \in V \} \cup \{(a_e^0,b_\ell^1),(a_e^3,b_\ell^1),(a_\ell^1,b_e^1): e \in E\}. \end{equation} Third, we encode the incidence relation in $H$ into our instance by adding the edges of \begin{equation} \label{eqn-Finc-def} F_{\textup{inc}} = \{ (a_e^0,b_y^1), (a_e^3,b_x^1) :e= (x,y) \} \end{equation} between edge and vertex gadgets. We define the set of all inter-gadget edges as $F=F_{\ell} \cup F_{\textup{bnd}} \cup F_{\textup{inc}}$. Note that the edges of $F$ indeed run between different gadgets. \begin{figure}[t] \begin{center} \includegraphics[scale=1]{np-hardness-gadgets.pdf} \caption{An illustration of the instance constructed in the proof of Theorem~\ref{thm:mincost-nphard}, showing the level-setting gadgets together with two vertex gadgets corresponding to vertices $x$ and $y$ in $H$ and an edge gadget corresponding to edge~\mbox{$e=(x,y)$}. Agents' preferences are indicated by numbers on the edges. Dashed lines represent inter-gadget edges with cost~$\infty$, zigzagged lines represent edges with cost~$1$, and normal lines represent edges with cost~$0$. The assignment~$M$ defined in direction ``$\Leftarrow$'' of the proof is indicated by bold lines, assuming a vertex cover $S$ that contains~$x$ but not~$y$. Red, black, and blue edges have weight $+1$, $0$, and~$-1$, respectively, according to $\mathsf{wt}_M(\cdot)$. The values of the dual certificate $\vec{\alpha}$ for~$M$ are indicated by numbers within the circle (square) corresponding to the given agent (object, respectively). } \label{fig:mincost-gadgets} \end{center} \end{figure} For a set $X$ of objects, we will write $[X]$ in an agent's preference list to denote an arbitrarily ordered list containing objects in $X$. Then the preferences of the agents are as follows: \medskip \begin{tabular}{lll} $a_{\ell}^0:$ & $b_\ell^0 \succ b_\ell^1$; \\ $a_{\ell}^1:$ & $b_\ell^0 \succ b_\ell^1 \succ [\{b_e^1:e \in E\}]$; $ \quad$ \\ $a_x^0:$ & $b_\ell^0 \succ b_x^0 \succ b_x^1$ & for each $x \in V$; \\ $a_x^1:$ & $b_x^0 \succ b_x^1$ & for each $x \in V$; \\ $a_e^0:$ & $b_e^3 \succ b_e^0 \succ b_\ell^1 \succ b_y^1$ \qquad \qquad & for each $e=(x,y) \in E$; \\ $a_e^1:$ & $b_e^0 \succ b_e^1$ & for each $e \in E$; \\ $a_e^2:$ & $b_e^2 \succ b_e^1$ & for each $e \in E$; \\ $a_e^3:$ & $b_e^3 \succ b_e^2 \succ b_\ell^1 \succ b_x^1$ & for each $e=(x,y) \in E$; \end{tabular} \medskip Finally, we define the cost function: edges of $F$ have cost $+\infty$, the edge $(a_x^0,b_x^1)$ has cost~$1$ for each $x \in V$, and all remaining edges have cost~$0$. We set our budget to be $k$. We claim that the constructed instance admits a popular assignment of cost at most $k$ if and only if $H$ contains a vertex cover of size at most $k$. \paragraph{Direction ``$\Rightarrow$''.} Let $M$ be a popular matching of cost at most $k$. Since inter-gadget edges have infinite cost, $M(a)$ must be an object in the gadget that contains $a$, for any agent $a$. Thus, for any~$x \in V$, the cost of the edges of $M$ within the vertex gadget corresponding to $x$ is either~$1$ (in case $M$ contains the edge $(a_x^0,b_x^1)$), or~$0$ (in case $M$ does not contain $(a_x^0,b_x^1)$). Let $S$ be the set of those vertices $x \in V$ for which the former holds, i.e., $S=\{x \in V:M(a_x^0) = b_x^1 \}$; clearly, our budget implies $|S| \leq k$. Let $M$ admit a dual certificate $\vec{\alpha}$. Note that w.l.o.g. we can assume that $\alpha_{a_\ell^0}=0$, as otherwise we can decrease the value of $\alpha_a$ for all agents $a$ by~$\alpha_{a_\ell^0}$ and increase $\alpha_b$ by the same amount for each object $b$. Recall also that for each $(a,b) \in M$ complementary slackness for \ref{LP2} implies $\alpha_a+\alpha_b=0$; hence $\alpha_{b_\ell^0}=-\alpha_{a_\ell^0}=0$. Since $a_\ell^1$ prefers $b_\ell^0$ to $M(a_\ell^1)=b_\ell^1$, we know that $\mathsf{wt}_M(a_\ell^1,b_\ell^0)=1$ and thus $\alpha_{a_\ell^1}\geq 1$ and $\alpha_{b_\ell^1} \leq -1$. Using that $\mathsf{wt}_M(a_\ell^0,b_\ell^1)=-1$, we obtain $\alpha_{a_\ell^1}=1$ and $\alpha_{b_\ell^1}=-1$. Consider now the edges in $F_{\textup{bnd}}$. Observe that $\mathsf{wt}_M(a_e^0,b_\ell^1)=-1$, $\mathsf{wt}_M(a_e^3,b_\ell^1)=-1$ and $\mathsf{wt}_M(a_\ell^1,b_e^1)=-1$ for any $e \in E$. Furthermore, we also have $\mathsf{wt}_M(a_x^0,b_\ell^0)=1$ for any $x \in V$. These observations imply the following bounds: \begin{eqnarray} \label{eqn-alphabnd-A_E} \min(\alpha_{a_e^0},\alpha_{a_e^3}) \geq & 0 & \textrm{\qquad for each $e \in E$}; \\ \label{eqn-alphabnd-B_E} \alpha_{b_e^1} \geq & -2 & \textrm{\qquad for each $e \in E$}; \\ \label{eqn-alphabnd-ax0} \alpha_{a_x^0} \geq & 1 & \textrm{\qquad for each $x \in V$}. \end{eqnarray} For some $v \in V \setminus S$, since $a_v^1$ prefers $b_v^0$ to $M(a_v^1)=b_v^1$, we know that $\mathsf{wt}_M(a_v^1,b_v^0)=1$, implying \begin{equation} \label{eqn-notinS} \alpha_{b_v^1} =-\alpha_{a_v^1} \leq \alpha_{b_v^0}-1 = -\alpha_{a_v^0} -1 \leq -2, \end{equation} where the last inequality follows from our bound (\ref{eqn-alphabnd-ax0}). Let us fix some edge $e = (x,y) \in E$. Let us define two matchings $M_x^e = \{(a_e^i,b_e^i): i \in \{0,\dots,3\}\}$ and $M_y^e = \{(a_e^i,b_e^{(i-1)\! \! \! \mod 4} ): i \in \{0,\dots,3\}\}$. Since $M$ does not contain any inter-gadget edges, we know that $M$ contains either $M_x^e$ or $M_y^e$. Assume first that $M$ contains $M_x^e$; we claim that $\alpha_{a_e^3} =0$. For the sake of contradiction, assume otherwise; by (\ref{eqn-alphabnd-A_E}) this implies $\alpha_{a_e^3} \geq 1$. From the preferences of agents $a_e^1$ and $a_e^0$, we know $\mathsf{wt}_M(a_e^1,b_e^0) = 1$ and $\mathsf{wt}_M(a_e^0,b_e^3) = 1$. This implies \begin{equation} \alpha_{b_e^1}=-\alpha_{a_e^1} \leq \alpha_{b_e^0}-1 = -\alpha_{a_e^0}-1 \leq \alpha_{b_e^3}-1-1 = -\alpha_{a_e^3} -2 \leq -3, \end{equation} which contradicts our bound (\ref{eqn-alphabnd-B_E}). Hence, $\alpha_{a_e^3} =0$. By the preferences of agent $a_e^3$, we know $\mathsf{wt}_M(a_e^3,b_x^1) =-1$, from which we get $\alpha_{b_x^1} \geq -1$. Since (\ref{eqn-notinS}) holds for every $v \in V\setminus S$, this implies $x \in S$. Assume now that $M$ contains $M_y^e$; we claim that $\alpha_{a_e^0} =0$. For the sake of contradiction, assume otherwise; by (\ref{eqn-alphabnd-A_E}) this implies $\alpha_{a_e^0} \geq 1$. From the preferences of agents $a_e^2$ and $a_e^3$, we know $\mathsf{wt}_M(a_e^2,b_e^2) = 1$ and $\mathsf{wt}_M(a_e^3,b_e^3) = 1$. This implies \begin{equation} \alpha_{b_e^1}=-\alpha_{a_e^2} \leq \alpha_{b_e^2}-1 = -\alpha_{a_e^3}-1 \leq \alpha_{b_e^3}-1-1 = -\alpha_{a_e^0} -2 \leq -3, \end{equation} which contradicts our bound (\ref{eqn-alphabnd-B_E}). Hence, $\alpha_{a_e^0} =0$. By the preferences of agent $a_e^0$, we know $\mathsf{wt}_M(a_e^0,b_y^1) =-1$, from which we get $\alpha_{b_y^1} \geq -1$. Therefore, the bound (\ref{eqn-notinS}) implies $y \in S$. Thus, we have proved that $x \in S$ or $y \in S$ holds for any edge $(x,y) \in E$, that is, $S$ is a vertex cover of size at most $k$ in $H$. \paragraph{Direction ``$\Leftarrow$''.} For the other direction, given a vertex cover $S \subseteq V$ of size at most $k$ in $H$, we will show that a popular assignment $M$ of total cost exactly $k$ exists. For each edge $e \in E$, let us fix one of its endpoints in $S$, and denote it by $\tau(e)$. We may define $M$ as follows: \medskip \begin{tabular}{ll} $M(a_\ell^i)=b_\ell^i$ & for any $i \in \{0,1\}$, \\ $M(a_x^i)= b_x^i$ & for any $x \in V \setminus S$ and $i \in \{0,1\}$, \\ $M(a_x^i)= b_x^{1-i}$ & for any $x \in S$ and $i \in \{0,1\}$, \\ $M(a_e^i)= M_{\tau(e)}^e(a_e^i)$ \qquad \qquad & for any $e\in E$ and $i \in \{0,\dots,3\}$. \end{tabular} \medskip It is clear that $M$ indeed has total cost $k$. To show that $M$ is popular, we define a dual certificate for $M$ by defining $\alpha_b$ for each object $b \in B$ as follows; we set $\alpha_a = - \alpha_{M(a)}$ for each agent $a \in A$. \medskip \begin{tabular}{llll} $\alpha_{b_\ell^0}=0$; & & $\alpha_{b_\ell^1}=-1$; \\ $\alpha_{b_x^0}=0$ & for each $x \in S$; & $\alpha_{b_e^0}=-1$ & for each $e \in E$; \\ $\alpha_{b_x^0}=-1$ \quad & for each $x \in V \setminus S$; \qquad \qquad & $\alpha_{b_e^1}=-2$ & for each $e \in E$; \\ $\alpha_{b_x^1}=-1$ & for each $x \in S$; & $\alpha_{b_e^2}=-1$ & for each $e \in E$; \\ $\alpha_{b_x^1}=-2$ & for each $x \in V \setminus S$; & $\alpha_{b_e^3}=0$ & for each $e \in E$. \\ \end{tabular} \medskip This finishes the proof of the theorem. \qed \end{proof} We are now ready to present the proof of Theorem~\ref{thm:mincost-nphard-01}. \medskip \begin{proof}[of Theorem~\ref{thm:mincost-nphard-01}.] We will modify the reduction presented in the proof of Theorem~\ref{thm:mincost-nphard}. Given the instance~$G$ constructed there, we obtain a modified instance~$G'$ as follows; see Figure~\ref{fig:mincost-gadgets-01} for an illustration. \paragraph{Construction.} We keep each vertex and edge gadget of $G$, but instead of the two level-setting gadgets in $G$, we define a single level-setting gadget in $G'$, consisting of a cycle of length $4k'$ where~$k'$ is the smallest integer with $2k'-1 > k$. This gadget will contain agents $a_{\ell}^i$ for $i \in \{0,\dots, 2k'-1\} $ together with objects $b_{\ell}^i$ for~$i \in \{0,\dots, 2k'-1\}$. We define the set $F$ of inter-gadget edges by keeping those inter-gadget edges defined in $G$ that run between different gadgets in $G'$. Hence, we let $F=F_{\textup{bnd}} \cup F_{\textup{inc}}$ where $F_{\textup{bnd}}$ and $F_{\textup{inc}}$ are defined as in~(\ref{eqn-Fbnd-def}) and~(\ref{eqn-Finc-def}), respectively. The preferences of any agent in a vertex or edge gadget of $G'$ are the same as in $G$. We define the preferences of the agents in the level-setting gadget as follows: \medskip \begin{tabular}{lll} $a_{\ell}^0:$ & $b_\ell^0 \succ b_\ell^{2k'-1}$; \\ $a_{\ell}^1:$ & $b_\ell^0 \succ b_\ell^1 \succ \{b_e^1:e \in E\}$; \\ $a_{\ell}^i:$ & $b_\ell^{i-1} \succ b_\ell^i$ & for each $i \in \{2,\dots, k'\}$; \\ $a_{\ell}^i:$ & $b_\ell^i \succ b_\ell^{i-1}$ & for each $i \in \{k'+1,\dots, 2k'-1\}$. \end{tabular} \medskip We set the cost of edge $(a_\ell^i,b_\ell^{i-1})$ for each $i \in \{0,\dots, 2k'-1\}$ as~$1$; we interpret superscripts of objects belonging to the level-setting gadget modulo $2k'$ (here and later). We also set the cost of the edge $(a_x^0,b_x^1)$ for each $x \in V$ as~$1$. All remaining edges have cost~$0$, and we set $k$ as our budget. \paragraph{Direction ``$\Rightarrow$''.} To prove the correctness of our reduction, first we will show that the existence of a popular assignment $M$ of cost at most $k$ in $G'$ implies a vertex cover of size at most $k$ in $H$. \paragraph{Excluding inter-gadget edges.} We claim that $M$ does not contain any inter-gadget edges. To prove this, we first show that $(a_\ell^0,b_\ell^0) \in M$. Observe that for any $i \in \{0\} \cup \{2, \dots, 2k'-1\}$, agent $a_\ell^i$ can be assigned either~$b_\ell^i$ or~$b_\ell^{i-1}$. Using that $M$ assigns an object to every agent, we immediately get that $(a_\ell^0,b_\ell^0) \notin M$ implies that $M$ must contain all of the edges $(a_\ell^i, b_\ell^{i-1})$ for $i \in \{0\} \cup \{2, \dots, 2k'-1\}$. However, these edges have total cost $2k'-1>k$ which exceeds our budget. Hence, $M$ contains $(a_\ell^0,b_\ell^0)$ as well as every edge $(a_\ell^i, b_\ell^{i})$ for $i \in \{2, \dots, 2k'-1\}$. Consider now the two agents in some vertex gadget: since neither of them can obtain object $b_\ell^0$, they must be assigned the two objects within their gadget. It remains to show that $(a_\ell^1, b_\ell^1) \in M$. The only other possibility is that $M(a_\ell^1)=b_e^1$ for some edge~$e \in E$. This immediately implies $M(a_e^1)=b_e^0$ and $M(a_e^2)=b_e^2$. Let $e=(x,y)$, and let us define $M_x^e = \{(a_e^i,b_e^i): i \in \{0,\dots,3\}\}$ and $M_y^e = \{(a_e^i,b_e^{i-i}): i \in \{0,\dots,3\}\}$. Note that the objects available for the agents $a_e^0$ and $a_e^3$ are $b_e^3$ and $b_\ell^1$ (since all objects of a vertex gadget are assigned within their gadget). Therefore, we have two cases: \begin{itemize} \item[a)] $(a_e^0,b_\ell^1) \in M$, implying $M(a_e^3)=b_e^3$. Then the assignment which uses the edges of $M_x^e$ and the edge $(a_\ell^1, b_\ell^1)$ and otherwise coincides with $M$ is more popular than $M$, a contradiction. \item[b)] $(a_e^3,b_\ell^1) \in M$, implying $M(a_e^0)=b_e^3$. Then the assignment which uses the edges of $M_y^e$ and the edge $(a_\ell^1, b_\ell^1)$ and otherwise coincides with $M$ is more popular than $M$, a contradiction. \end{itemize} Thus, we have proved $(a_\ell^1, b_\ell^1) \in M$, showing that $M$ indeed avoids all inter-gadget edges. \begin{figure}[t] \begin{center} \makebox[\textwidth][c]{ \includegraphics[scale=1]{np-hardness-gadgets-01.pdf} } \caption{An illustration of the instance constructed in the proof of Theorem~\ref{thm:mincost-nphard-01}. As before, agents' preferences are indicated by numbers on the edges. Zigzagged lines represent edges with cost~$1$, all other edges have cost~$0$. Dashed lines represent inter-gadget edges. The assignment $M$ defined in direction ``$\Leftarrow$'' of the proof is indicated by bold lines, assuming a vertex cover $S$ that contains $x$ but not $y$. Red, black, and blue edges have weight $+1$, $0$, and~$-1$, respectively, according to $\mathsf{wt}_M(\cdot)$. The values of the dual certificate $\vec{\alpha}$ for~$M$ are indicated by numbers within the circle (square) corresponding to the given agent (object, respectively). } \label{fig:mincost-gadgets-01} \end{center} \end{figure} \paragraph{Defining a vertex cover.} We are going to define a set $S$ the same way as we did for the instance~$G$, and show that $S$ is a vertex cover in $H$. Hence, consider any $x \in V$. The cost of the edges of $M$ within the vertex gadget corresponding to $x$ is either $1$ (in case $M$ contains the edge $(a_x^0,b_x^1)$), or~$0$ (in case $M$ does not contain $(a_x^0,b_x^1)$). Let $S$ be the set of those vertices $x \in V$ for which the former holds, i.e., $S=\{x \in V:M(a_x^0) = b_x^1 \}$; our budget implies $|S| \leq k$. Let $M$ admit a dual certificate $\vec{\alpha}$. Note that w.l.o.g. we can assume that $\alpha_{a_\ell^0}=0$, as otherwise we can decrease the value of~$\alpha_a$ for all agents $a$ by~$\alpha_{a_\ell^0}$ and increase $\alpha_b$ by the same amount for each object~$b$. Recall also that $M(a_\ell^i)=b_\ell^i$ for each $i \in \{0, \dots, 2k'-1\}$. For each $(a,b) \in M$ complementary slackness for \ref{LP2} implies $\alpha_a+\alpha_b=0$, so~$\alpha_{b_\ell^i}=-\alpha_{a_\ell^is}$. Since $a_\ell^i$ prefers $b_\ell^{i-1}$ to $M(a_\ell^i)=b_\ell^i$ for any $i \in \{1, \dots, k'\}$, we know $\mathsf{wt}_M(a_\ell^i,b_\ell^{i-1})=1$. Using this iteratively for $i=1, 2, \dots, k'$ we get that $\alpha_{a_\ell^i}\geq i$ and $\alpha_{b_\ell^i} \leq -i$ for any $i \in \{1, \dots, k'\}$. Similarly, using iteratively that $\mathsf{wt}_M(a_\ell^{2k'-i+1},b_\ell^{2k'-i})=-1$ for $i=1, 2, \dots, k'$, we obtain that $\alpha_{b_\ell^{2k'-i}} \geq -i$ and $\alpha_{a_\ell^{2k'-i}} \leq i$. Now, considering the above two observations regarding $\alpha_{a_\ell^{k'}}$ we can conclude that only $\alpha_{a_\ell^{k'}}=k'$ is possible. Moreover, this implies that each of the above inequalities must hold with equality, that is, \begin{equation} \label{eqn-levelsetting} \alpha_{a_\ell^i}=\left\{ \begin{array}{ll} i & \textrm{ if $0 \leq i \leq k'$,} \\ 2k'-i \qquad \qquad &\textrm{ if $k' \leq i \leq 2k'-1$.} \\ \end{array} \right. \end{equation} Consider now the edges in $F_{\textup{bnd}}$. Observe that $\mathsf{wt}_M(a_e^0,b_\ell^1)=-1$, $\mathsf{wt}_M(a_e^3,b_\ell^1)=-1$ and $\mathsf{wt}_M(a_\ell^1,b_e^1)=-1$ for any $e \in E$. Furthermore, we also have $\mathsf{wt}_M(a_x^0,b_\ell^0)=1$ for any $x \in V$. Taking into account~(\ref{eqn-levelsetting}), these observations yield the following bounds: \begin{eqnarray} \label{eqn:alphabnd-A_E} \min(\alpha_{a_e^0},\alpha_{a_e^3}) \geq & 0 & \textrm{\qquad for each $e \in E$}; \\ \label{eqn:alphabnd-B_E} \alpha_{b_e^1} \geq & -2 & \textrm{\qquad for each $e \in E$}; \\ \label{eqn:alphabnd-ax0} \alpha_{a_x^0} \geq & 1 & \textrm{\qquad for each $x \in V$}. \end{eqnarray} Notice that these are exactly the same bounds we obtained for the instance~$I$ in the proof of Theorem~\ref{thm:mincost-nphard} in Inequalities (\ref{eqn-alphabnd-A_E}), (\ref{eqn-alphabnd-B_E}), and (\ref{eqn-alphabnd-ax0}). Therefore, using the same arguments again, we obtain that $S$ is a vertex cover of size at most $k$. \paragraph{Direction ``$\Leftarrow$''.} For the other direction, given a vertex cover $S \subseteq V$ of size at most $k$ in $H$, we will show that a popular assignment $M$ of total cost exactly $k$ exists in $G'$. For each edge $e \in E$, let us fix one of its endpoints in $S$, and denote it by $\tau(e)$. We may define $M$ as follows: \medskip \begin{tabular}{ll} $M(a_\ell^i)=b_\ell^i$ & for any $i \in \{0,1, \dots, 2k'-1\}$, \\ $M(a_x^i)= b_x^i$ & for any $x \in V \setminus S$ and $i \in \{0,1\}$, \\ $M(a_x^i)= b_x^{1-i}$ & for any $x \in S$ and $i \in \{0,1\}$, \\ $M(a_e^i)= M_{\tau(e)}^e(a_e^i)$ \qquad \qquad & for any $e\in E$ and $i \in \{0,\dots,3\}$. \end{tabular} \medskip It is clear that $M$ indeed has total cost $k$. To show that $M$ is popular, we define a dual certificate for $M$ by defining $\alpha_b$ for each object $b \in B$ as follows; we set $\alpha_a = - \alpha_{M(a)}$ for each agent $a \in A$. \medskip \begin{tabular}{llll} $\alpha_{b_\ell^i}=-i$ & for each $i \in \{0,1,\dots, k'\}$; \qquad \qquad & $\alpha_{b_\ell^{2k'-i}}=-i \phantom{aa}$ & for each $i \in \{1,\dots, k'-1\}$; \\ $\alpha_{b_x^0}=0$ & for each $x \in S$; & $\alpha_{b_e^0}=-1$ & for each $e \in E$; \\ $\alpha_{b_x^0}=-1$ \quad & for each $x \in V \setminus S$; & $\alpha_{b_e^1}=-2$ & for each $e \in E$; \\ $\alpha_{b_x^1}=-1$ & for each $x \in S$; & $\alpha_{b_e^2}=-1$ & for each $e \in E$; \\ $\alpha_{b_x^1}=-2 \phantom{aa}$ & for each $x \in V \setminus S$; & $\alpha_{b_e^3}=0$ & for each $e \in E$. \\ \end{tabular} \medskip This finishes the proof of the theorem. \qed \end{proof} \paragraph{Minimum-cost popular assignment vs.\ popular assignment with forbidden edges.} The \myproblem{popular assignment with forbidden edges} problem can be seen as the special case of \myproblem{minimum-cost popular assignment} in which the popular assignment may only contain edges of cost $0$, excluding all edges of non-zero cost. In the general version of \myproblem{minimum-cost popular assignment}, however, there is a degree of freedom as to which non-zero cost edges are included in the assignment. Our proof of Theorem~\ref{thm:mincost-nphard} shows that this degree of freedom introduces an additional complexity to the problem. Indeed, in our reduction from \myproblem{Vertex Cover}, a set of vertices chosen as a vertex cover is encoded via the set of cost~$1$ edges chosen to be included in the allocation, and explicitly forbidding all cost~$1$ edges would turn the constructed \myproblem{popular assignment with forbidden edges} instance into a trivial `no'-instance. \section{Popular allocations in housing markets} \label{sec:housing} A housing market, as introduced by Shapley and Scarf in their seminal paper~\cite{SS74}, models a situation where agents are initially endowed with one unit of an indivisible good, called a house, and agents may trade their houses according to their preferences without using monetary transfers. In such markets, trading results in a reallocation of houses in a way that each agent ends up with exactly one house. Let $A$ denote the set of agents, and let $\omega(a)$ denote the house of agent~$a \in A$; note that agents do not share houses, so $\omega(a) \neq \omega(a')$ whenever $a \neq a'$. The classic representation of a \emph{housing market} over $A$ is a directed graph~$D=(A,F)$ where each agent~$a \in A$ has preferences over the arcs leaving~$a$ in $D$. In this model, an arc $(a,a') \in F$ means that $a$ prefers $\omega(a')$ over her own house (i.e.,~$\omega(a)$), and is therefore willing to participate in a trade where she obtains $\omega(a')$. Thus, preferences over the arcs leaving~$a$ describe her preferences of the houses she finds acceptable (i.e., prefers to her own). An \emph{allocation} in a housing market~$D=(A,F)$ is a set $S \subseteq F$ of edges that form disjoint cycles in~$D$ called \emph{trading cycles}. An agent \emph{trades} in~$S$ if it is covered by a trading cycle of~$S$. The solution concept used by Shapley and Scarf is the so-called \emph{core}~\cite{SS74}, but there have been several other stability notions studied in the literature on housing markets. We may consider popularity as an alternative concept, with a straightforward interpretation as follows. Given allocations~$S$ and~$S'$ in $D$, some agent~$a \in A$ \emph{prefers}~$S$ to~$S'$, if either $S$ covers $a$ but $S'$ does not, or $(a,a_1) \in S$, $(a,a_2) \in S'$ and $a$ prefers~$\omega(a_1)$ to~$\omega(a_2)$. We say that $S$ is \emph{more popular than~$S'$}, if the number of agents preferring~$S$ to~$S'$ is more than the number of agents preferring~$S'$ to~$S$. An allocation~$S$ is \emph{popular} in~$D$, if there is no allocation in~$D$ that is more popular than~$S$. A natural question is the following: can we find a popular allocation in a given housing market efficiently? \paragraph{Popular allocations in a housing market: reduction to \myproblem{popular assignment}.} We propose a reduction from the problem of finding a popular allocation in a housing market to the problem of finding a popular assignment in a bipartite graph. The main idea of the reduction is to associate a bipartite graph $G_D$ with a given housing market~$D=(A,F)$ as follows. We let $G_D = (A \cup B, E)$ where objects are houses, i.e., $B=\{\omega(a) : a \in A\}$, and $E=\{(a,\omega(a')):(a,a') \in F)\} \cup \{(a,\omega(a)):a \in A\}$. Thus, each arc $(a,a') \in F$ corresponds to an edge $(a, \omega(a'))$ in~$E$, and we also add an edge~$(a,\omega(a))$ for each agent~$a \in A$, corresponding to the possibility of~$a$ staying in her own house. Preferences of an agent~$a$ over her outgoing arcs in~$D$ naturally yield her preferences in $G_D$ over objects in~$\mathsf{Nbr}_{G_D}(a) \setminus \{\omega(a)\}$, while $\omega(a)$ is the unique worst-choice object of~$a$. Observe that there is a one-to-one correspondence between allocations in~$D$ and assignments in~$G_D$ that preserves the preferences of any agent: an allocation~$S$ in $D$ corresponds to an assignment $M_S=\{(a,\omega(a')):(a,a') \in S\} \cup \{(a,\omega(a)): a$ does not trade in $S\}$; note that this indeed yields a bijection. It is easy to see that an allocation~$S$ is popular in~$D$ if and only if $M_S$ is a popular assignment in~$G_D$. Hence, we can find a popular allocation in a housing market~$D$ by using Algorithm~\ref{alg:popassign} to find a popular assignment in~$G_D$. \begin{proposition} \label{prop:pop_allocation} For any housing market $D=(A,F)$ on $n$ nodes and $m$ arcs where each agent has preferences over her outgoing arcs, we can decide in time~$O((m+n) \cdot n^{5/2})$ whether $D$ admits a popular allocation or not, and if so, find one. \end{proposition} \paragraph{Maximum-size popular allocation in a housing market.} Given Proposition~\ref{prop:pop_allocation}, an interesting question is whether it is possible to find a maximum-size popular allocation in a housing market $D=(A,F)$, where the \emph{size} of an allocation~$S$ in~$D$ is~$|S|$, that is, the number of agents trading in~$S$. A natural approach for finding a maximum-size popular allocation in~$D$ would be to assign cost~$1$ to the edge~$(a,\omega(a))$ for each $a \in A$ in~$G_D$, assign cost~$0$ to all remaining edges of~$G_D$, and ask for a minimum-cost popular assignment in $G_D$. Theorem~\ref{thm:mincost-nphard-01} tells us that this method leads to intractability. Nevertheless, Theorem~\ref{thm:mincost-nphard-01} does not imply that finding a maximum-size popular allocation in a housing market is $\mathsf{NP}$-hard, since the reduction proving Theorem~\ref{thm:mincost-nphard-01} constructs an instance that does not correspond to any housing market (e.g., because worst-choice objects coincide for certain agents). We now present a strengthening of Theorem~\ref{thm:mincost-nphard-01} proving that finding a popular allocation of maximum size in a housing market is $\mathsf{NP}$-hard. \begin{theorem} \label{thm:housealloc-nphard} The \myproblem{minimum-cost popular assignment} problem is $\mathsf{NP}$-hard, even if agents' preferences are strict, the input graph~$G_D$ corresponds to a housing market~$D=(A,F)$, and the cost function is such that edges in~$\{(a,\omega(a)) : a \in A\}$, corresponding to initial endowments in~$D$, have cost~1, while all remaining edges have cost~0. \end{theorem} \begin{proof} We present a reduction from the \myproblem{Vertex Cover} problem, using ideas from the proofs of Theorems~\ref{thm:mincost-nphard} and~\ref{thm:mincost-nphard-01}. Let our input for \myproblem{Vertex Cover} be a graph~$H=(V,E)$ and an integer~$k$. We will construct an equivalent instance of the \myproblem{minimum-cost popular assignment} problem. We assume an arbitrary, fixed ordering on the vertices of $H$, which allows us to represent each edge in $E$ as an ordered pair $(x,y) \in E$; this implicit ordering will be relevant in our construction. \smallskip \paragraph{Gadgets.} We begin by defining two types of gadgets. A \emph{gadget} $G_\gamma$ of size $s \in \mathbb{N}$ contains agents~$a_{\gamma}^i$ and objects~$b_{\gamma}^i$ for each $i \in \{0,1,\dots, 6s-1\}$. Superscripts of these agents and objects are always taken modulo $6s$. We let $A_\gamma=\{a_\gamma^i:i \in [6s]\}$ and $B_\gamma=\{b_\gamma^i:i \in [6s]\}$. Preferences of agents in $A_\gamma$ depend on the type of the gadget; see Figure~\ref{fig:HA-gadget}. If $G_\gamma$ is a \emph{type-0 gadget}, then agents in~$A_\gamma$ have preferences as follows. \medskip \begin{tabular}{lll} $a_{\gamma}^i:$ & $b_\gamma^i \succ b_\gamma^{i+1}$ & for each $i \in \{0,1, \dots, 3s-1\}$; \\ $a_{\gamma}^i:$ & $b_\gamma^{i+1} \succ b_\gamma^i$ & for each $i \in [6s-1] \setminus [3s-1]$ where $i \not \equiv 0 \mod 3$; \\ $a_{\gamma}^i:$ & $b_\gamma^{i+1} \succ b_\gamma^i \succ b_\gamma^{i+3} \qquad \quad$ & for each $i \in [6s-1] \setminus [3s-1]$ where $i \equiv 0 \mod 3$. \end{tabular} \medskip \begin{figure}[t] \begin{center} \includegraphics[scale=0.9]{HA-gadgets.pdf} \caption{An illustration of type-0 and type-1 gadgets constructed in the proof of Theorem~\ref{thm:housealloc-nphard}. Edges leading from an agent to its worst-choice object are shown in red. } \label{fig:HA-gadget} \end{center} \end{figure} By contrast, if $G_\gamma$ is a \emph{type-1 gadget}, then its agents have the following preferences. \medskip \begin{tabular}{lll} $a_{\gamma}^i:$ & $b_\gamma^i \succ b_\gamma^{i+1}$ & for each $i \in \{0,1, \dots, 3s-1\}$ where $i \not \equiv 2 \mod 3$; \\ $a_{\gamma}^i:$ & $b_\gamma^i \succ b_\gamma^{i+1} \succ b_\gamma^{i-2} \qquad \quad$ & for each $i \in \{0,1, \dots, 3s-1\}$ where $i \equiv 2 \mod 3$; \\ $a_{\gamma}^i:$ & $b_\gamma^{i+1} \succ b_\gamma^i$ & for each $i \in [6s-1] \setminus [3s-1]$. \end{tabular} \medskip Furthermore, we define two disjoint matchings in gadget $G_\gamma$, namely $M_\gamma^0=\{(a_\gamma^i,b_\gamma^i):i \in [6s]\}$ and $M_\gamma^1=\{(a_\gamma^i,b_\gamma^{i+1}):i \in [6s]\}$. Notice that the edge set~$\{(a,\omega(a)):a \in A_\gamma \}$ leading from the agents to their worst-choice objects forms a perfect matching within the gadget. In our contruction, we will assign a cost of~1 for such edges, setting all remaining edge costs as~0. This gives rise to the following important difference between type-0 and type-1 gadgets: for a type-0 gadget~$G_\gamma$ of size~$s$, the cost of~$M_\gamma^0$ is~$2s$, while the cost of~$M_\gamma^1$ is~$3s$. By contrast, for a type-1 gadget~$G_\gamma$ of size~$s$, the matching~$M_\gamma^0$ has cost~$3s$, while $M_\gamma^1$ has cost~$2s$. In fact, the sole purpose of the differences between the two types of gadgets is to make $M_\gamma^0$ ``cheap'' and $M_\gamma^1$ ``expensive'' in a type-0 gadget, and the other way around in a type-1 gadget. \smallskip \paragraph{Construction.} Let us set $n_v=3|E|+1$ and $n_\ell=(3|V|+1)n_v$; it will be sufficient for the reader to keep $n_\ell \gg n_v \gg |E|$ in mind. We are now ready to define the set~$A$ of agents and the set~$B$ of objects by creating the following: \begin{itemize} \item a type-0 gadget~$G_\ell$ of size~$n_\ell$ called the \emph{level-setting gadget}, \item for each $e \in E$ a type-0 gadget~$G_e$ of size $1$ called an \emph{edge gadget}, and \item for each $x \in V$ a type-1 gadget~$G_x$ of size $n_v$ called a \emph{vertex gadget}. \end{itemize} Additionally, we introduce a set $F$ of \emph{inter-gadget edges}; see Figure~\ref{fig:HA-consruction} for an illustration. First, in order to enforce certain lower bounds on the dual certificate, we connect some agents and objects in the level-setting gadget with those in the vertex and edge gadgets, by adding the edges of \begin{equation} \label{eqn-HA-Fbnd-def} F_{\textup{bnd}}=\{(a_x^{-3},b_\ell^{-2}):x \in V \} \cup \{(a_e^2,b_\ell^{-3}),(a_e^4,b_\ell^{-2}),(a_\ell^{-3},b_e^4): e \in E\}. \end{equation} Second, we encode the incidence relation in $H$ into our instance by adding the edges of \begin{equation} \label{eqn-HA-Finc-def} F_{\textup{inc}} = \{ (a_e^2,b_x^{-3}), (a_e^3,b_y^{-3}) : e= (x,y) \in E\} \end{equation} between edge and vertex gadgets. We define the set of all inter-gadget edges as $F= F_{\textup{bnd}} \cup F_{\textup{inc}}$. Note that the edges of $F$ indeed run between different gadgets. Preferences of agents incident to inter-gadget edges are given below; all remaining agents have preferences as given in the definition of a type-0 or type-1 gadget. Again, for a set $X$ of objects, we write $[X]$ in an agent's preference list to denote an arbitrarily ordered list containing objects in~$X$. \medskip \begin{tabular}{lll} $a_{\ell}^{-3}:$ & $b_\ell^{-2} \succ b_\ell^{-3} \succ [\{b_e^4:e \in E\}] \succ b_\ell^0$; $\qquad \quad$ & \\ $a_e^2:$ & $b_\ell^{-3} \succ b_x^{-3} \succ b_e^2 \succ b_e^3$ & for each $e=(x,y) \in E$; \\ $a_e^3:$ & $ b_y^{-3} \succ b_e^4 \succ b_e^3 \succ b_e^0$ & for each $e=(x,y) \in E$; \\ $a_e^4:$ & $b_\ell^{-2} \succ b_e^5 \succ b_e^4$ & for each $e=(x,y) \in E$; \\ $a_x^{-3}:$ & $b_\ell^{-2} \succ b_x^{-2} \succ b_x^{-3}$ & for each $x \in V$. \end{tabular} \medskip Note that the introduction of inter-gadget edges did not change the worst-choice object of any agent. As a consequence, the edge set $\{(a,\omega(a)):a \in A\}$ forms a perfect matching in the resulting graph~$G$, and therefore $G$ indeed corresponds to a housing market as promised. \begin{figure}[t] \begin{center} \includegraphics[scale=1]{HA-construction.pdf} \caption{An illustration of the construction in the proof of Theorem~\ref{thm:housealloc-nphard}. The figure assumes $e=(x,y) \in E$. Again, worst-choice edges are shown in red, while inter-gadget edges are depicted in blue. } \label{fig:HA-consruction} \end{center} \end{figure} We set the cost of all edges in $\{(a,\omega(a)):a \in A\}$ as~$1$. All remaining edges have cost~$0$, and we set $\beta=2n_\ell+3kn_v+(|V|-k)2n_v+3|E|$ as our budget. This finishes the definition of our instance. \smallskip \paragraph{Direction ``$\Rightarrow$''.} To prove the correctness of our reduction, first we will show that the existence of a popular assignment $M$ of cost at most $\beta$ in $G$ implies a vertex cover of size at most $k$ in $H$. Let us make some basic observations about the structure of $M$. \smallskip \paragraph{Excluding inter-gadget edges.} We claim that $M$ does not contain any inter-gadget edges. To prove this, we first show that $(a_\ell^{-2},b_\ell^{-2}) \in M$. For any $i \in \{-2,-1, 0, \dots, 3n_\ell-1\}$, agent~$a_\ell^i$ can be assigned either~$b_\ell^i$ or~$b_\ell^{i+1}$. Using that $M$ assigns an object to every agent, we immediately get that if $(a_\ell^{-2},b_\ell^{-2}) \notin M$, then $M$ must contain all edges $(a_\ell^i, b_\ell^{i+1})$ for $i \in \{-2,-1,0,1, \dots, 3n_\ell-1\}$. However, these edges have total cost $3n_\ell$ which by our choice of $n_\ell$ exceeds the budget~$\beta$. Hence, $M$ contains $(a_\ell^{-2},b_\ell^{-2})$. In particular, this shows that agents in a vertex gadget~$G_x$ can only be assigned by $M$ an object within the same gadget. Thus, all objects within vertex gadgets must be assigned to agents within vertex gadgets, implying that no edge of $F$ incident to a vertex gadget may be contained in $M$. To prove our claim, it remains to show that $M$ does not contain any edge connecting the level-setting gadget with an edge gadget. Assume otherwise for the sake of contradiction. Recall that only $a_\ell^{-3}$ and $b_\ell^{-3}$ may be incident to an edge of $M \cap F$ among all agents and objects in~$G_\ell$. Thus, it follows that $M$ must contain both $(a_\ell^{-3},b_e^4)$ and $(a_e^2,b_\ell^{-3})$ for some $e \in E$. (Observe that here we used the fact that no edge leaving a vertex gadget may be in $M$.) From this we also get $(a_e^3,b_e^3) \in M$. We can then define a matching $M'$ by replacing these three edges with the edges $(a_\ell^{-3},b_\ell^{-3})$, $(a_e^2,b_e^3)$ and $(a_e^3,b_e^4)$. Observe that $M'$ is more popular than $M$, since both $a_e^3$ and $a_\ell^{-3}$ prefer $M'$ to $M$; a contradiction to the popularity of $M$. Hence, we have established that $M \cap F=\emptyset$. \smallskip \paragraph{Assignment~$M$ on the level-setting gadget.} We now show that $M_\ell^0= \{(a_\ell^i,b_\ell^i):i \in [6n_\ell]\} \subseteq M$. To this end, we first prove that $M$ does not contain any of the edges~$(a_\ell^i,b_\ell^{i+3})$ where $i \in [6n_\ell]$ and $i \equiv 0 \mod 3$. Suppose $(a_\ell^i,b_\ell^{i+3}) \in M$ for the sake of contradiction. Then $(a_\ell^{i+2},b_\ell^{i+2}) \in M$ and~$(a_\ell^{i+1},b_\ell^{i+1}) \in M$ follows. However, we can now define an assignment~$M'$ by deleting these three edges from $M$ and adding the edges $(a_\ell^{i},b_\ell^{i+1})$, $(a_\ell^{i+1},b_\ell^{i+2})$, and~$(a_\ell^{i+2},b_\ell^{i+3})$ instead. Notice that all three agents $a_\ell^i$, $a_\ell^{i+1}$, and $a_\ell^{i+2}$ prefer~$M'$ over~$M$, contradicting our assumption that $M$ is popular. Together with $M \cap F=\emptyset$, this implies that $M(a_\ell^i) \in \{ b_\ell^i,b_\ell^{i+1}\}$ for each $i \in [6n_\ell]$. Recall that we already know $(a_\ell^{-2},b_\ell^{-2}) \in M$, which yields $M_\ell^0 \subseteq M$. \smallskip \paragraph{Edge and vertex gadget: a binary choice for $M$.} Consider some edge gadget $G_e$. Since $M$ does not contain any inter-gadget edges, we can argue that $M$ does not contain the edge~$(a_e^3,b_e^0)$: indeed, supposing $(a_e^3,b_e^0) \in M$ would imply $\{(a_e^4,b_e^4),(a_e^5,b_e^5)\} \subseteq M$; however, replacing these edges by the edges $\{(a_e^i,b_e^{i+1}):i =3,4,5\}$ yields a matching more popular than~$M$, a contradiction. Hence, $M$ contains either $M_e^0$ or $M_e^1$. Analogously, we can show that $M$ contains no edge of the form~$(a_x^i,a_x^{i-2})$ in a vertex gadget~$G_x$: indeed, $(a_x^i,b_x^{i-2}) \in M$ would imply $\{(a_x^{i-2},b_x^{i-1}),(a_x^{i-1},b_x^i)\} \subseteq M$; however, replacing these edges by $\{(a_e^j,b_e^j):j =i-2,i-1,i\}$ yields a matching more popular than~$M$, a contradiction. Hence, $M$ contains either $M_x^0$ or $M_x^1$. \smallskip \paragraph{Properties of a dual certificate.} Let $M$ admit a dual certificate $\vec{\alpha}$, and consider some gadget~$G_\gamma$ in~$G$ of size~$s$. Recall that for each $(a,b) \in M$ complementary slackness for \ref{LP2} implies that $\alpha_a+\alpha_b=\mathsf{wt}_M(a,b)=0$. Thus, either $\alpha_{a_\gamma^i}=-\alpha_{b_\gamma^i}$ for each $i \in [s]$, or $\alpha_{a_\gamma^i}=-\alpha_{b_\gamma^{i+1}}$ for each $i \in [s]$. Furthermore, let $\overline{M}_\gamma$ denote the matching $(M_\gamma^0 \cup M_\gamma^1) \setminus M$ (that is, $\overline{M}_\gamma=M_\gamma^1$ if $M_\gamma^0 \subseteq M$, and $\overline{M}_\gamma=M_\gamma^0$ otherwise). Observe that half of the edges in $\overline{M}_\gamma$ have weight $+1$ and half of them have weight $-1$ according to $\mathsf{wt}_M(\cdot)$, since exactly half of the agents in $G_\gamma$ prefer $M_\gamma^0$ to $M_\gamma^1$, while the other half prefer $M_\gamma^1$ to $M_\gamma^0$. Hence, using the feasibility of the dual certificate $\vec{\alpha}$, we get \[ 0=\sum_{a \in A_\gamma} \alpha_a + \alpha_{M(a)} = \sum_{a \in A_\gamma} \alpha_a + \sum_{b \in B_\gamma} \alpha_b = \sum_{a \in A_\gamma} \alpha_a + \alpha_{\overline{M}_\gamma(a)}\geq |A_\gamma|/2 \cdot 1+|A_\gamma|/2 \cdot (-1)=0 \] where the first equality holds because $\alpha_a+\alpha_b=0$ for each edge $(a,b) \in M$. Thus, it follows that $\alpha_a+\alpha_b=\mathsf{wt}_M(a,b)$ must hold for each edge $(a,b) \in \overline{M}_\gamma$ as well. From this we get \begin{eqnarray} \label{eqn-HA-dualvalues} \notag \alpha_{b_\gamma^{i+1}}&=&\alpha_{b_\gamma^{i+1}}+\alpha_{a_\gamma^i}-\alpha_{a_\gamma^i}-\alpha_{b_\gamma^i}+\alpha_{b_\gamma^i}= \mathsf{wt}_{M}(a_\gamma^i,b_\gamma^{i+1})-\mathsf{wt}_{M}(a_\gamma^i,b_\gamma^i)+\alpha_{b_\gamma^i} \\ &=& \left\{ \begin{array}{ll} \alpha_{b_\gamma^i} -1, & \textrm{\hspace{20pt}if $i \in \{0,1, \dots, 3s-1\}$,} \\ \alpha_{b_\gamma^i} +1, & \textrm{\hspace{20pt}if $i \in [6s-1] \setminus [3s-1]$,} \\ \end{array} \right. \end{eqnarray} irrespectively of the type of gadget~$G_\gamma$. In particular, this implies \begin{equation} \label{eqn-HA-opposite-dualvalues} \alpha_{b_\gamma^i}=\alpha_{b_\gamma^{-i}} \end{equation} for each $i \in [3s]$. Note that w.l.o.g. we can assume that $\alpha_{b_\ell^0}=0$, as otherwise we can decrease the value of~$\alpha_b$ for all objects $b$ by~$\alpha_{b_\ell^0}$ and increase $\alpha_a$ by the same amount for each agent~$a$. Therefore, (\ref{eqn-HA-dualvalues}) yields \begin{equation} \label{eqn-HA-levelgadget-values} \alpha_{b_\ell^{-3}}=-3, \quad \alpha_{b_\ell^{-2}}=-2, \quad \alpha_{a_\ell^{-3}}=3 \end{equation} where the last equality follows from $(a_\ell^{-3},b_\ell^{-3}) \in M$. \smallskip \paragraph{Defining a vertex cover.} We are going to define a set $S \subseteq V$, and show that $S$ is a vertex cover in~$H$ of size at most~$k$. Namely, let $S$ contain exactly those vertices~$x \in V$ for which \mbox{$M_x^0 \subseteq M$}. Note that since $G_x$ is a type-1 gadget of size~$n_v$ for each $x \in V$, the cost of all edges of~$M$ within~$G_x$ is either~$3n_v$ (if $x \in S$) or~$2n_v$ (if $x \notin S$). Since the cost of $M_\ell^0 \subseteq M$ is $2n_\ell$, and by our choice of~$n_v$ we have $\beta+n_v-3|E|=2n_\ell+(k+1)3n_v+(|V|-k-1)2n_v<\beta$, our budget implies $|S| \leq k$. It remains to show that $S$ is indeed a vertex cover. To this end, consider now the edges in $F_{\textup{bnd}}$. Observe that $\mathsf{wt}_M(a_e^2,b_\ell^{-3})=1$, $\mathsf{wt}_M(a_e^4,b_\ell^{-2})=1$ and $\mathsf{wt}_M(a_\ell^{-3},b_e^4)=-1$ for any $e \in E$. Using (\ref{eqn-HA-levelgadget-values}) this implies \begin{equation} \label{eqn-HA-edgegadget-bounds} \alpha_{a_e^2} \geq 4, \quad \alpha_{a_e^4} \geq 3, \quad \alpha_{b_e^4} \geq -4. \end{equation} By~(\ref{eqn-HA-opposite-dualvalues}) we also have $\alpha_{b_e^2}=\alpha_{b_e^4}$. Let us distinguish between two cases: (i) first, if $M_e^0 \subseteq M$, then $\alpha_{a_e^2}+\alpha_{b_e^2} = \mathsf{wt}_M(a_e^2,b_e^2)=0$, which by (\ref{eqn-HA-edgegadget-bounds}) implies $\alpha_{b_e^2}\leq -4$; (ii) second, if $M_e^1 \subseteq M$, then $\alpha_{a_e^4}+\alpha_{b_e^4} = \mathsf{wt}_M(a_e^4,b_e^4)=-1$, which by (\ref{eqn-HA-edgegadget-bounds}) implies $\alpha_{b_e^4}\leq -4$. Hence, in either case we obtain $\alpha_{b_e^2}=\alpha_{b_e^4}=-4$ by~(\ref{eqn-HA-edgegadget-bounds}). This leads us to the following important facts: \begin{eqnarray} \label{eqn-HA-edgegadget-value-M0} \textrm{if $M_e^0 \subseteq M$, then }&& \!\! \alpha_{a_e^2}=4; \\ \label{eqn-HA-edgegadget-value-M1} \textrm{if $M_e^1 \subseteq M$, then }&& \!\! \alpha_{a_e^3}=4. \end{eqnarray} Now, consider the edges incident to some vertex gadget $G_x$. First, $\mathsf{wt}_M(a_x^{-3},b_\ell^{-2})=1$ implies $\alpha_{a_x^{-3}} \geq 3$ by the equations in (\ref{eqn-HA-levelgadget-values}). From (\ref{eqn-HA-dualvalues}) it follows that \begin{equation} \label{eqn-HA-vertexgadget-value-M1} \textrm{if $M_x^1 \subseteq M$, then } \alpha_{b_x^{-3}} = \alpha_{b_x^{-2}}-1 = \alpha_{M(a_x^{-3})}-1 = -\alpha_{a_x^{-3}}-1 \leq -4. \end{equation} We are now ready to show that $S$ is indeed a vertex cover in~$H$. Let $e=(x,y) \in E$ be an edge in~$H$. First, if $M_e^0 \subseteq M$, then $\mathsf{wt}_M(a_e^2,b_x^{-3})=1$ together with~(\ref{eqn-HA-edgegadget-value-M0}) implies $\alpha_{b_x^{-3}} \geq -3$. Hence, by~(\ref{eqn-HA-vertexgadget-value-M1}) we must have $M_x^1 \not\subseteq M$, yielding $x \in S$. Second, if $M_e^1 \subseteq M$, then $\mathsf{wt}_M(a_e^3,b_y^{-3})=1$ together with~(\ref{eqn-HA-edgegadget-value-M1}) implies $\alpha_{b_y^{-3}} \geq -3$. By (\ref{eqn-HA-vertexgadget-value-M1}) applied to gadget~$G_y$ we obtain $M_y^1 \not\subseteq M$, yielding $y \in S$. Thus, we can conclude that either $x \in S$ or $y \in S$, proving our claim. \smallskip \paragraph{Direction ``$\Leftarrow$''.} For the other direction, given a vertex cover $S \subseteq V$ of size at most $k$ in $H$, we will show that a popular assignment $M$ of total cost at most~$\beta$ exists in $G$. For each edge $e \in E$, let us fix one of its endpoints in $S$, and denote it by $\tau(e)$. We may define $M$ as follows: \[ M=M_\ell^0 \cup \left( \bigcup_{x \in S} M_x^0 \right) \cup \left(\bigcup_{x \in V \setminus S} M_x^1 \right) \cup \left( \bigcup_{\substack{e=(x,y) \in E, \\ \tau(e)=x}} M_e^0 \right) \cup \left( \bigcup_{\substack{e=(x,y) \in E, \\ \tau(e)=y}} M_e^1 \right). \] \begin{figure}[t] \begin{center} \includegraphics[scale=1]{HA-allocation.pdf} \caption{An illustration of a popular assignment for the instance $G$ constructed in the proof of Theorem~\ref{thm:housealloc-nphard}, given a vertex cover $S$. The figure assumes $e=(x,y) \in E$ with $x \notin S$ and $y \in S$. Edges contained in $M$ are depicted in bold. The values of a dual certificate $\vec{\alpha}$ for $M$ are indicated within the corresponding agent or object. } \label{fig:HA-allocation} \end{center} \end{figure} It is clear that $M$ indeed has total cost at most~$\beta$: the cost of $M_\ell^0$ is $2n_\ell$, the cost of $\bigcup_{x \in S} M_x^0$ is~$3kn_v$, the cost of $\bigcup_{x \in V\setminus S} M_x^1$ is $2(|V|-k)n_v$, while the cost of all edges of $M$ within edge gadgets is at most $3|E|$. To show that $M$ is popular, we define a dual certificate~$\vec{\alpha}$ for~$M$ by defining $\alpha_b$ for each object $b \in B$ as follows; we set $\alpha_a = - \alpha_{M(a)}$ for each agent~$a \in A$. See Figure~\ref{fig:HA-allocation} for an illustration. \medskip \begin{tabular}{ll} $\alpha_{b_\ell^i}=-|i|$ & for each $i \in \{-3n_\ell+1, \dots, -1, 0,1,\dots, 3n_\ell\}$; \\ $\alpha_{b_x^i}=-|i|$ & for each $x \in S$ and $i \in \{-3n_v+1, \dots, -1, 0,1,\dots, 3n_v\}$; \\ $\alpha_{b_x^i}=-|i|-1$ & for each $x \in V \setminus S$ and $i \in \{-3n_v+1, \dots, -1, 0,1,\dots, 3n_v\}$; \\ $\alpha_{b_e^i}=-|i|-2 \qquad \quad$ & for each $e \in E$ and $i \in \{-2,-1,0,1,2, 3\}$; \end{tabular} \medskip This finishes the proof of the theorem. \qed \end{proof} \section{Open problems}\label{sec:open-problems} We proposed a polynomial-time algorithm for computing a popular assignment in an instance $G = (A\cup B,E)$ with one-sided preferences, if one exists. The running time of our algorithm is $O(m\cdot n^{5/2})$ where $|A| = |B| = n$ and $|E| = m$. Our algorithm solves $O(n^2)$ instances of the maximum matching problem in certain subgraphs of~$G$. It is easy to show instances where our algorithm indeed solves $\Theta(n^2)$ instances of the maximum matching problem. Can we do this more efficiently? Is there a faster algorithm for the \myproblem{popular assignment} problem? Another open problem is to show a short {\em witness} that a given instance $G$ does not admit a popular assignment. Rather than run our algorithm and discover that $G$ has no popular assignment, is there a forbidden structure that causes $G$ not to admit a popular assignment? Can we characterize instances that admit popular assignments? Interestingly, such a result is known for the stable roommates problem~\cite{Tan91}; recall our discussion in Section~\ref{sec:intro} on the similarity between results for the \myproblem{popular assignment} problem and the \myproblem{stable roommates} problem. Our $\mathsf{W}_l[1]$-hardness proof for the \myproblem{$k$-unpopularity margin} problem with parameter~$k$ needs weak rankings. We are able to show that this problem remains $\mathsf{NP}$-hard for strict rankings (see Lemma~\ref{lem:reduction-weak-to-strict} in Section~\ref{app:weak-rankings}). However, the parameterized complexity of this case is still open: is the \myproblem{$k$-unpopularity margin} problem in FPT with parameter~$k$, if agents' preferences are strict rankings? \section*{Acknowledgments} Telikepalli Kavitha is supported by the DAE, Government of India, under project no. RTI4001. Tam\'{a}s Kir\'{a}ly is supported by the National Research, Development and Innovation Fund of Hungary, grant no.~K120254 and Application Domain Specific Highly Reliable IT Solutions project under Thematic Excellence Programme TKP2020-NKA-06. Jannik Matuschke is supported by internal funds of KU Leuven. Ildik\'{o} Schlotter was supported by the Hungarian Academy of Sciences under its Momentum Programme (LP2016-3/2018), and by the Hungarian Scientific Research Fund through NFKIH grants no. K128611 and K124171. Ulrike Schmidt-Kraepelin is supported by the Deutsche For\-schungs\-gemeinschaft (DFG) under grant BR~4744/2-1. \iffalse
{'timestamp': '2022-03-29T02:49:56', 'yymm': '2110', 'arxiv_id': '2110.10984', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.10984'}
arxiv
\section{0pt}{6pt}{5pt} \titleformat{\subsection}[block]{\large\bfseries}{\thesubsection}{1em}{} \titlespacing*\subsection{0pt}{6pt}{5pt} \titleformat{\subsubsection}[runin]{\normalsize\itshape}{\thesubsubsection}{1em}{} \titlespacing*\subsubsection{0pt}{6pt}{5pt} \usepackage{titling} \usepackage{hyperref} \newlength{\bibitemsep}\setlength{\bibitemsep}{.1\baselineskip plus .05\baselineskip minus .05\baselineskip} \newlength{\bibparskip}\setlength{\bibparskip}{0pt} \let\oldthebibliography\thebibliography \renewcommand\thebibliography[1]{% \oldthebibliography{#1}% \setlength{\parskip}{\bibitemsep}% \setlength{\itemsep}{\bibparskip}% } \setlength{\droptitle}{-5\baselineskip} \title{RL4RS : A Real-World Benchmark for Reinforcement Learning \\ based Recommender System} \author{% \textsc{Kai Wang} \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] \and \textsc{Zhene Zou} \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] \and \textsc{Yue Shang}\ \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] \and \textsc{Qilin Deng}\ \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] \and \textsc{Minghao Zhao}\ \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] \and \textsc{Yile Liang}\ \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] \and \textsc{Runze Wu}\ \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] \and \textsc{Jianrong Tao}\ \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] \and \textsc{Xudong Shen}\ \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] \and \textsc{Tangjie Lyu}\ \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] \and \textsc{Changjie Fan}\ \\ \normalsize Fuxi AI Lab, NetEase Games \\ \normalsize Hangzhou, Zhejiang, China \\ \normalsize [email protected] } \date{} \renewcommand{\maketitlehookd}{% } \begin{document} \maketitle \pagestyle{empty} \begin{abstract} \vspace*{-.9em} \noindent Reinforcement learning based recommender systems (RL-based RS) aim at learning a good policy from a batch of collected data, by casting sequential recommendations to multi-step decision-making tasks. However, current RL-based RS research commonly have a large reality gap, because they involve artificial RL datasets or semi-simulated RS datasets, and the trained policy is directly evaluated in the simulation environment. In real-world situations, not all recommendation problems are suitable to be transformed into reinforcement learning problems. Unlike previous academic RL research, RL-based RS suffers from extrapolation error and the difficulties of being well-validated before deployment. In this paper, we introduce the RL4RS (Reinforcement Learning for Recommender Systems) benchmark - a new resource fully collected from industrial applications to train and evaluate RL algorithms with special concerns on the above issues. It contains two datasets, tuned simulation environments, related advanced RL baselines, data understanding tools, and counterfactual policy evaluation algorithms. The RL4RS suite can be found at https://github.com/fuxiAIlab/RL4RS. In addition to the RL-based recommender systems, we expect the resource to contribute to research in reinforcement learning and neural combinatorial optimization. \end{abstract} \section{Introduction} In 2020, retail e-commerce sales worldwide amounted to 5.23 trillion US dollars and e-retail revenues are projected to grow to 6.54 trillion US dollars in 2022. Such rapid growth promises a great future for the worldwide e-commerce industry signifying a strong market and increased customer demand. Besides the huge increment of the traffic volume, there has been a rapid growth of various recommendation scenarios, including slate recommendation, bundle recommendation (a collection of items that should be purchased simultaneously), sequential item recommendation, and many others, as shown in Figure 1. It is worth exploring the various challenges that the modern e-commerce industry faces today. Most current e-commerce and retail companies build their recommender systems by implementing supervised learning based algorithms on their websites to maximize immediate user satisfaction in a greedy manner. However, the item-wise greedy recommendation strategy is an imperfect fitting to real recommendation systems. With more and more new upcoming recommendation scenarios, more and more challenges have to be solved. For instance, in sequential recommendation scenarios, traditional methods often consider different ranking steps in a session to be independent and fail to maximize the expected accumulative utilities in a recommendation session. In the slate recommendation or bundle recommendation, the conversion rate of an item does not solely depend on itself. If an item is surrounded by similar but expensive items, the conversion rate increases, known as the decoy effect~\cite{2020Validation}. However, the possible combinations of all the items can be billions, which is an NP-hard problem and less explored in traditional supervised learning. \begin{figure}[] \includegraphics[scale=0.24]{scenes.jpg} \caption{several novel Recommendation scenarios. \label{Fig:scenes}} \end{figure} To deal with these challenges, recent researches resort to adopt reinforcement learning for recommendations, in which the recommendation process is formulated as a sequential interaction between the user (environment) and the recommendation agent (RL agent). Reinforcement learning is a promising direction since the RL paradigm is inherently suitable for optimizing long-term user satisfaction directly, exploring the combination spaces efficiently, and tackling multi-step decision-making problems - but there remain two main problems in recent research. The first problem is the lack of real-world datasets for RL-based RS problems. There are mainly two alternatives, one is artificial datasets, such as RecoGym~\cite{Rohde2018RecoGymAR} and RECSIM~\cite{ie2019recsim}. The main disadvantage is that they are not the real feedback of users in real applications. Another one is semi-simulated RS datasets, i.e., transforming traditional datasets such as MovieLens to RL data format. Take MovieLens dataset as an example, to meet the requirements of RL data format, Adversarial User Model~\cite{chen2019adversarialgenerative} assumes the context of user's choice as the movies released within a month and the maximal size of each displayed set as 40. The main disadvantage of semi-simulated datasets is that most forced data transformations are not reasonable. The second problem is the lack of unbiased evaluation methods. In the current research, there are mainly two kinds of evaluation indicators: traditional recommendation indicators (recall rate, accuracy, etc.) and pure reinforcement learning indicators (e.g., cumulative rewards). However, the former ones are indirect evaluation indicators, and the latter ones highly depend on the accuracy of the simulation environment. The bias of policy evaluation mainly comes from "extrapolation error", which is a phenomenon in which unseen state-action pairs are erroneously estimated to have unrealistic values. In this paper, we further explore other two recently developed methods to tackle "extrapolation error", counterfactual policy evaluation and batch RL. With these in mind, we introduce RL4RS - an open-source benchmark for RL-based RS developed and deployed at Netease. RL4RS is built in Python and uses TensorFlow for modeling and training. It aims to fill the rapidly-growing need for RL systems that are tailored to work on novel recommendation scenarios. It consists of (1) two large-scale raw logged data, reproducible simulation environments, and related RL baselines. (2) data understanding tools for testing the proper use of RL, and systematic evaluation process, including environment fitting evaluation, policy evaluation on the simulation environment, and counterfactual policy evaluation. (3) the separated data before and after reinforcement learning deployment for each dataset. Based on them, we are able to measure the extent of extrapolation error and evaluate the effectiveness of different RL algorithms, including batch RL algorithms. A new dataset for bundle recommendation with variable discounts, flexible recommendation trigger, and modifiable item content is also in preparation. \begin{table*}[] \small \caption{A comparison between RL4RS and other resources.} \label{tab:impact} \begin{tabular}{|l|c|c|c|c|c|c|c|c|} \hline & \multicolumn{3}{c|}{Dataset} & \multicolumn{3}{c|}{Opensource} & \multicolumn{2}{c|}{Others} \\ \hline & \begin{tabular}[c]{@{}c@{}}Artifical\\ dataset\end{tabular} & \begin{tabular}[c]{@{}c@{}}Semi-simulated\\ dataset\end{tabular} & \begin{tabular}[c]{@{}c@{}}Real \\ dataset\end{tabular} & Code & \begin{tabular}[c]{@{}c@{}}Raw logged\\ data\end{tabular} & \begin{tabular}[c]{@{}c@{}}simulation\\ environment\end{tabular} & \begin{tabular}[c]{@{}c@{}}Offline policy\\ learning\end{tabular} & \begin{tabular}[c]{@{}c@{}}Offline policy\\ evaluation\end{tabular} \\ \hline RecoGym\cite{Rohde2018RecoGymAR} & \checkmark & $\times$ & $\times$ & \checkmark & $\times$ & \checkmark & $\times$ & $\times$ \\ \hline Recsim\cite{ie2019recsim} & \checkmark & $\times$ & $\times$ & \checkmark & $\times$ & \checkmark & $\times$ & $\times$ \\ \hline Top-k Off-policy\cite{chen2019topk} & \checkmark & $\times$ & $\times$ & \checkmark & $\times$ & $\times$ & \checkmark & $\times$ \\ \hline SlateQ\cite{Ie2019SlateQAT} & \checkmark & $\times$ & $\times$ & \checkmark & $\times$ & $\times$ & $\times$ & $\times$ \\ \hline Adversarial\cite{chen2019adversarialgenerative} & $\times$ & \checkmark & $\times$ & \checkmark & $\times$ & $\times$ & $\times$ & $\times$ \\ \hline List-wise\cite{zhao2017list} & $\times$ & \checkmark & $\times$ & \checkmark & $\times$ & $\times$ & $\times$ & $\times$ \\ \hline Virtual-Taobao\cite{Shi2019VirtualTaobaoVR} & $\times$ & $\times$ & \checkmark & \checkmark & $\times$ & \checkmark & $\times$ & $\times$ \\ \hline Model-based\cite{Bai2019ModelBasedRLnips} & \checkmark & \checkmark & $\times$ & \checkmark & $\times$ & $\times$ & \checkmark & $\times$ \\ \hline Ours & $\times$ & $\times$ & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark \\ \hline \end{tabular} \end{table*} \section{Impact} \label{impact} In this section, we assess the benefits of the RL4RS resource in relation to existing resources for evaluating RL-based RS. We collect all relevant works that have been open-sourced at present, including RecoGym\renewcommand{\thefootnote}{$1$}\footnote{https://github.com/criteo-research/reco-gym}\cite{Rohde2018RecoGymAR}, Recsim\renewcommand{\thefootnote}{$2$}\footnote{https://github.com/google-research/recsim}\cite{ie2019recsim}, Top-k off-policy\renewcommand{\thefootnote}{$3$}\footnote{https://github.com/awarebayes/RecNN}\cite{chen2019topk}, SlateQ\renewcommand{\thefootnote}{$4$}\footnote{https://github.com/ray-project/ray/blob/master/rllib/agents/slateq/}\cite{Ie2019SlateQAT}, Adversarial User Model\renewcommand{\thefootnote}{$5$}\footnote{https://github.com/xinshi-chen/GenerativeAdversarialUserModel}\cite{chen2019adversarialgenerative}, List-wise\renewcommand{\thefootnote}{$6$}\footnote{https://github.com/luozachary/drl-rec}\cite{zhao2017list}, Virtual Taobao\renewcommand{\thefootnote}{$7$}\footnote{https://github.com/eyounx/VirtualTaobao}\cite{Shi2019VirtualTaobaoVR}, and Model-Based RS\renewcommand{\thefootnote}{$8$}\footnote{https://github.com/XueyingBai/Model-Based-Reinforcement-Learning-for-Online-Recommendation}\cite{Bai2019ModelBasedRLnips}. We consider the following dimensions to evaluate the benefit of these related works: \begin{itemize} \item \textbf{Artificial Datasets}: RecoGym and Recsim are two representative artificial datasets, which are employed in the experiments of Top-K and SlateQ. \item \textbf{Semi-simulated Datasets}: Traditional RS datasets such as MovieLens are designed for item-wise supervised learning and are not suitable for RL-based RS experiments. As a suboptimal solution, Adversarial User Model, List-wise and Model-based RS make a lot of assumptions and manual transformations on these datasets to fit the RL requirements. \item \textbf{Real Industry Datasets Without Transformation}: Though many works build their online experiments on real industrial scenarios, there are few works providing the reproductive offline experiment result on real offline datasets. \item \textbf{Code Release}: We list the GitHub pages of each algorithm at the beginning of this section. Top-k off-policy and SlateQ are non-official implementations. \item \textbf{Dataset Release}: In addition to artificial datasets and semi-simulated RS datasets, virtual Taobao builds experiments on a real dataset but without open-sourcing the raw logged data. Raw logged data is necessary for the reproduction of the simulation environment and the implementation of offline policy learning and evaluation. \item \textbf{Simulation Environment Release}: Virtual Taobao has open-sourced a low-dimensional version of the pre-trained simulation environment, which is associated with 11-dimensional user features and 27-dimensional item features. \item \textbf{Offline policy learning}: Most current works firstly train the environmental model and then learn the policy through the interaction with the trained environment, except Top-k off-policy. In this paper, we further explore the extrapolation error and batch RL algorithms. \item \textbf{Offline policy evaluation}: Offline policy evaluation aims to predict the performance of a newly learned policy without having to deploy it online. Rather than test the policy in a simulation environment, in this paper, we further introduce the counterfactual policy evaluation (CPE) to RL-based RS. \end{itemize} In Table 1, we summarize the characteristics of existing works in terms of these dimensions. It can be seen that our RL4RS benchmark is the only one that meets all requirements. In addition to the contribution of open-sourcing two industrial datasets, we further explore the topics such as offline policy training, extrapolation error, and counterfactual policy evaluation, hoping to enhance the development of RL-based RS field. \section{Data Description} We collect the raw logged data from one of the most popular games released by \textit{NetEase Games}\renewcommand{\thefootnote}{$9$}\footnote{http://leihuo.163.com/en/index.html}. The item recommendation task in this scenario is characterized by its special interaction rules. In each second, the recommendation engine should respond to users' requests with 3 item lists (3 items per list), and the next item list is locked until the items of current list are sold out. Obviously, thanks to the special 'unlock' rule, the users' response to an item depends on not only that item but also the items of other lists. If users are not satisfied with the existing item slate, they can refresh the page (i.e. the item slate) through a refresh button up to 3 times per day. Here, we provide two benchmark datasets, RL4RS-A and RL4RS-B. Dataset A focuses on the slate recommendation. It regards the user's behavior on a single page as an MDP process. Dataset B focuses on the sequential slate recommendation. It not only considers how to recommend a single page but also considers the relationship between pages to maximize the total reward of pages. We will make data exploration in Section 4 to compare the MDP properties of our datasets and traditional RS datasets. A brief statistics of RL4RS datasets are shown in Table 2. \begin{figure}[tb] \includegraphics[scale=0.22]{dataset.jpg} \caption{A graphic description of RL4RS datasets. \label{Fig:dataset}} \end{figure} \begin{figure}[] \includegraphics[scale=0.48]{system.pdf} \caption{The architecture of recommender system. \label{Fig:RL_Ranking_System}} \end{figure} \subsection{Logged Data} Roughly speaking, the logs mainly record the recommendation context, the user's behavior sequence, and the deployed behavior policy at that time. The context includes the metadata of some users and items to form the features of users and items. The recorded behavior policy is used to reproduce the probability of each action at that time and to evaluate the counterfactual strategy. As shown in Figure \ref{Fig:RL_Ranking_System}, the recommendation engine contains five major components: an RS agent, an item pool, a logging center, a training component, and an online KV system. The workflow of our system mainly consists of two loops: the online planning loop and the online learning loop. As is shown in the left bottom of Figure \ref{Fig:RL_Ranking_System}, the online planning loop is the loop of the interactions between the recommendation agent and users. We will record the item information of each session and the user's behavior for each item. The second one is a learning loop (on the right in Figure \ref{Fig:RL_Ranking_System}) where the training process happens. Whenever the model is updated, it will be rewritten to the online KV system. We will record the network architecture and network parameters at that time. The two working loops are connected through the logging center and the online KV system. We will record the corresponding user and item features stored in the online KV system for each user log. After aligning the user log, real-time features and behavior policy, the format of raw logged data is: \begin{itemize} \item \textbf{Timestamp}: The timestamp when the event happens. \item \textbf{Session ID}: A unique number which uniquely identifies an user session. \item \textbf{Sequence ID}: A unique number representing the location of the state in the session (i.e., a page order). \item \textbf{Exposed items}: A nine-length space-delimited list representing the nine items exposed to users (left to right top to bottom). \item \textbf{User feedback}: A nine-length space-delimited list representing the user's reponses to the nine exposed items (left to right top to bottom). The user feedback (0/1) multiplied by the utility of each items will be used as the reward of this page (i.e., the item slate). \item \textbf{User Feature}: The anonymized user features including 42-dim user portrait and 64-dim user click history. \item \textbf{Item Feature}: The 360-dim item features that describe the context of exposed items in this page, such as item's id, item's category, item embedding, and historical CTR. \item \textbf{Behavior Policy ID}: A model file that records the network architecture and network parameters of the behavior policy (supervised learning strategy) at that time. \end{itemize} \subsection{Data Preprocessing} The raw logged data need to further be transformed into consecutive pairs of state/action tuples for RL models training. Besides, there are some differences for RL4RS datasets, such as the definition of observation, action embedding, action mask, action probability (used in counterfactual policy evaluation), and so on. For the sequential slate scenario, there is also a problem of when users leave. Most existing works directly predict the probability of users leaving at each step, which will lead to complex MDP state transitions~\cite{hubo}. In this paper, we use the session padding method instead to solve this problem. The user's exit behavior is been seen as a situation that the user will not have any action on any items next. So we can pad the user session to a certain length with zero paddings (zero feedback to a random item slate page) to replace the user's exit behavior. Specifically, we transforms the logged data collected in the following row format: \begin{itemize} \item \textbf{MDP ID}: A unique ID for the Markov Decision Process (MDP) chain that this training example is a part of. \item \textbf{Sequence ID}: A number representing the location of the state in the MDP (i.e. a timestamp). \item \textbf{State}: The features of current step that consists of user features and context features. \item \textbf{Observation}: The 256-dim hidden layer embedding of the pre-trained environment model with user features and context features of current step as input. Or we can use the raw state features as observation. \item \textbf{Action}: The item ID taken at the current step. Or we can use item embeddings can be used to represent item for continuous environment setting. \item \textbf{Action Features}: The features of item taken at the current step, including item embedding. \item \textbf{Action Probability}: The probability that the behavior policy took the action. \item \textbf{Action Mask}: An list of possible items at the current step. \item \textbf{Reward}: The reward of the current step. \item \textbf{Next State}: The state features after acting the logged action. \item \textbf{Next Observation}: The 256-dim hidden layer embedding of next state features. \item \textbf{Next Action}: The item ID recommended at the next step. \item \textbf{Next Action Features}: The features of item recommended at the next step. \item \textbf{Next Action Probability}: The probability of the item that is recommended at the next step. \item \textbf{Next Action Mask}: A list of items that are allowed to recommend at the next step. \item \textbf{Terminal}: A 0/1 number representing whether it is the last state. \end{itemize} \section{Data Understanding} One big challenge of applied RL is problem formulation. Traditional recommendation scenarios and datasets are not always suitable for modeling as MDP problems where some sort of long-term reward is optimized in a sequential setting. It is easy to accidentally prepare data that does not conform well to the MDP definition, and applying RL on ill-formulated problems is a costly process. Here, we develop a data understanding tool. Using a data-driven method together with heuristics, the tool checks whether the properties of RS datasets conform to the RL framework. \begin{table*}[] \centering \caption{RL4RS - Dataset Details} \label{tab:mlm_dataset} \begin{tabular}{lcccccc} \toprule Num. of & RL4RS-A & RL4RS-A-SL & RL4RS-A-RL & RL4RS-B & RL4RS-B-SL & RL4RS-B-RL \\ \hline Users & 149414 & 112221 & 77834 & 149414 & 112221 & 77834 \\ Items & 283 & 283 & 283 & 283 & 283 & 283 \\ Sessions & 1719316 & 937949 & 781367 & 958566 & 519435 & 439131 \\ Items per session & 9.0 & 9.0 & 9.0 & 16.1 & 16.3 & 16.0 \\ Purchases per session & 5.46 & 4.89 & 6.09 & 9.75 & 8.83 & 10.84 \\ Rewards per session & 91.7 & 83.2 & 102.0 & 164.5 & 150.3 & 181.5 \\ \bottomrule \end{tabular} \label{table:mlm_datasets} \vspace{-4mm} \end{table*} \subsection{Long-term Impact} An optimal policy should take into account the long-term impact of a recommendation on the user’s future choices. To maximize the accumulative rewards, we might suggest an item whose immediate reward is low but leads to more likely or more profitable rewards in the future. For example, when the products sold are books, by recommending a book for which there is a sequel, we may increase the likelihood that this sequel will be purchased later. Heuristically, the way to measure whether a recommendation problem should be modeled as an RL problem is to see whether a recommendation decision has a long-term impact. In terms of reinforcement learning formula, the recommendation of step $t$ is to maximize $r(s_{t},a_{t})+V^{*}(s_{t+1})$, where $r(s_{t},a_{t})$ is the expected reward when recommending item $a_{t}$ at state $s_{t}$, and $V^{*}(s_{t+1})$ represents the maximum reward of next state under current policy. Since there is always a large state value to represent users retention, we further denote $A(s_{t},a_{t})=V^{*}(s_{t+1})-V^{*}(s_{t}, \cdot)$ as the difference (advantage) between the future rewards of performing $a_{t}$ and the averaged future rewards, i.e., the long-term impact of performing $a_{t}$ at state $s_{t}$. When there is no long-term impact or the long-term impact is small, the RL problem degenerates into an ordinary sequential recommendation problem, which only maximizes the reward of the current step. Though we can estimate the long-term impact by training an RL model, it is too complex. Instead, we establish a data understanding tool to quantify the long-term impact without the requirement of establishing environment models or learning a value function. This tool is easy to use by simplifying RL as sequence modeling problems and expected rewards as decoded sequence scores. Similar ideas have been developed in Trajectory Transformer~\cite{transformer-rl} and Decision Transformer~\cite{transformer-decision}, in which states, actions, and returns are fed into a GPT~\cite{Radford2018ImprovingLU} architecture and actions are decoded autoregressively. First, the tool fits a Transformer-based sequence-to-sequence model~\cite{transformer} on each offline RS dataset. It encodes the user context features and decodes K items that users may click or buy, which means that the recommendation system will recommend these K items in turn in the next K steps (considering that most RS datasets do not provide a complete page context, here, only one item is recommended at a time, eliminating the slate effect between items within one page). We consider using the decode sequence generated by greedy search to represent greedy recommendation (SL-based strategy), and the sequence generated by beam search to represent the recommendation result generated by the optimal RL policy. We use beam-search width of 100. When there is a significant long-term item impact in the dataset, the items recommended in the previous steps may not have high immediate impacts, but their long-term impacts are large. That is, the immediate reward of the first k item in the best decode sequence may account for a small proportion in the final score of the sequence (experiment \uppercase\expandafter{\romannumeral1}). On the other hand, we can compare the sequences score of greedy strategy (even the sequence composed of only hot items which have high immediate reward) with the score of optimal sequence to check whether the greedy strategy is good enough (experiment \uppercase\expandafter{\romannumeral2}). \subsection{Experiment} We build experiments on the following datasets, MovieLens-25m, RecSys15 YooChoose, and RL4RS-A (has the same result as RL4RS-B under this experiment setting). More dataset details are in Appendix C. Without losing generality, we only consider the long-term impact within 5 steps. For each dataset, we choose 10000 users randomly as test set. For each user, we calculate the greedy search result and the top 100 item sequences (beam search width as 100). In the first experiment, we report the Pearson Correlation Coefficient and Spearman Rank Correlation Coefficient between the scores of the first k items (immediate reward) and the final sequence scores, denoted as k-Pearson and k-Spearman respectively. If the item's long-term impact is significant, the coefficients should be small, i.e., the immediate reward of the first item in the decode sequence accounts for a small proportion in the final score of the sequence. We report the results on the top 100 item sequences generated by beam search, as shown in Table 3. It can be seen that RecSys15 and MovieLens show positive correlations at the beginning. RL4RS dataset achieves a significantly lower spearman rank coefficient at the first one and two items than the other two datasets. It means, in RL4RS dataset, the first k items recommended do not have high immediate impacts, but have great long-term impacts. Although the first experiment can not absolutely indicate whether a dataset is suitable for reinforcement learning, it provides a tool for comparison of the degree of long-term impact characteristic between different datasets. In the second experiment, we aim to distinguish the dataset property by checking whether the greedy strategy is already good enough. We report the averaged score of the top 5 (5\% quantile) decode sequence, the top 20 (20\% quantile) sequence, and the score of sequence generated by greedy strategy. We also calculate the averaged score of the first 5\% quantile and 20\% quantile sequences when limiting the candidate items to hot items (100 items with the highest probability at the first decode step). All these scores are normalized by the averaged score of the top 5 sequence for each dataset. The results are shown in Table 4. It can be seen that there is a significant gap on the scores between the best 5\% item sequences and greedy strategy for RL4RS dataset, let alone the sequences composed of hot items. It shows that it is necessary to model the RL4RS dataset as an RL problem. For traditional RS datasets, on the contrary, the score of greedy strategy is very close to that of the best RL policy (top 5 decode sequence). It indicates that the greedy strategy (i.e., sequential RS methods) is well enough to model these scenarios. Although the data understanding tool is based on heuristics, in practice, it may help us understand the dataset in early stages, catch improperly defined RL problems, and lead to a better problem definition (e.g., reward definition). \begin{table}[tb] \centering \caption{The comparison of item's long-term impact between different datasets.} \label{tab:mdp} \begin{tabular}{lccc} \toprule Score. of & RecSys15 & MovieLens & RL4RS-A \\ \hline 1-Pearson & 0.11 & 0.13 & 0.03 \\ 1-Spearman & 0.10 & 0.11 & 0.02 \\ 2-Pearson & 0.16 & 0.17 & 0.06 \\ 2-Spearman & 0.15 & 0.16 & 0.03 \\ 3-Pearson & 0.24 & 0.25 & 0.14 \\ 3-Spearman & 0.23 & 0.23 & 0.08 \\ 4-Pearson & 0.39 & 0.38 & 0.36 \\ 4-Spearman & 0.39 & 0.36 & 0.33 \\ 5-Pearson & 1.00 & 1.00 & 1.00 \\ 5-Spearman & 1.00 & 1.00 & 1.00 \\ \bottomrule \end{tabular} \label{table:mdp} \vspace{-4mm} \end{table} \begin{table}[tb] \centering \caption{The comparison of decode sequence scores between different datasets.} \label{tab:mdp} \begin{tabular}{lccccc} \toprule Score. of & 5\% & 20\% & greedy. & hot 5\% & hot 20\%\\ \hline RecSys15 & 1.00 & 0.53 & 1.26 & 0.81 & 0.42 \\ MovieLens & 1.00 & 0.64 & 0.99 & 0.98 & 0.62 \\ RL4RS-A & 1.00 & 0.76 & 0.62 & 0.01 & 0.01 \\ \bottomrule \end{tabular} \label{table:mdp} \vspace{-4mm} \end{table} \section{Policy Learning} Unlike the academic environments which have perfect simulators, in real applications, RL has to learn from offline datasets considering the cost of online exploration. Given an offline dataset, we have two training methods. The first is training RL policies in the pre-trained simulation environment, which is the method adopted by most relevant works~\cite{Shi2019VirtualTaobaoVR, chen2019adversarialgenerative}. The second is batch RL, i.e., training policies from offline datasets directly. \subsection{Online Policy Learning} A straightforward way to train an RL policy is to interact with the pre-trained simulation environment. Most existing RL-based RS works follow this online training manner, but introduce a new problem of how to simulate the environment. \textbf{Simulation Environment Construction.} For recommendation systems, building a simulation environment is to build a perfect user behavior model. Different recommendation scenarios require different user behavior models. For RL4RS datasets, we predict the user's response to item slates, and measure the fitting effect of the model by predicting user purchase behavior. Specifically, we consider the following supervised learning baselines, including simple DNN, Wide\&Deep~\cite{cheng2016wide}, GRU4Rec~\cite{2015Session}, DIEN~\cite{zhou2019deep} and Adversarial User Model~\cite{chen2019adversarialgenerative}. The specific network designs are detailed in Appendix D. We consider three supervised learning tasks, namely slate-wise classification (multi-class classification), item-wise classification (binary classification), and item-wise rank (ranking task). The task description is detailed in Appendix D. From the results shown in Table \ref{tab:sl_training}, DIEN (attention-based model) achieves the best predictive performance, and all indicators of the three tasks are represented positive correlations. Note that due to the high purchase rate of this scenario (more than 5 items are purchased per session), the indicators such as item-wise classification accuracy and item-wise rank AUC are much higher than general RS scenarios. Because we pad each session to the same length with an all-zero label to simulate user's exit behavior, the indicators of RL4RS-B such as slate-wise classification accuracy and item-wise classification AUC become higher. Although the prediction of user behavior seems to be accurate enough, we can see from Table 6 that the estimated reward error is still very high (mean., abs., and std. represent the mean, absolute mean, and standard deviation of reward prediction error respectively). The prediction accuracy of random user behavior is usually low, which has always been a characteristic of recommendation systems. \begin{table*}[] \centering \caption{The experiment results of simulation environment construction.} \label{tab:sl_training} \begin{tabular}{|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{2}{|c|}{} & Slate-wise classification & \multicolumn{2}{c|}{Item-wise classification} & \multicolumn{4}{c|}{Item-wise rank} \\ \hline \multicolumn{2}{|c|}{} & Accuracy & {\quad AUC\quad} & Accuracy & {\quad AUC\quad} & Precision & Recall & F1 score \\ \hline \multirow{5}{*}{RL4RS-A} & DNN & 0.386 & 0.884 & 0.799 & 0.876 & 0.826 & 0.843 & 0.834 \\ \cline{2-9} & Wide\&Deep & 0.398 & 0.897 & 0.812 & 0.894 & 0.827 & \textbf{0.875} & 0.850 \\ \cline{2-9} & GRU4Rec & 0.429 & \textbf{0.913} & \textbf{0.827} & \textbf{0.907} & \textbf{0.862} & 0.846 & 0.854 \\ \cline{2-9} & DIEN & \textbf{0.430} & 0.911 & 0.826 & \textbf{0.907} & \textbf{0.862} & 0.848 & \textbf{0.855} \\ \cline{2-9} & Adver. & - & - & - & 0.880 & 0.830 & 0.838 & 0.834 \\ \hline \multirow{5}{*}{RL4RS-B} & DNN & 0.683 & 0.945 & 0.858 & 0.935 & 0.759 & 0.727 & 0.743 \\ \cline{2-9} & Wide\&Deep & 0.694 & 0.951 & 0.871 & 0.939 & 0.761 & 0.772 & 0.766 \\ \cline{2-9} & GRU4REC & 0.721 & \textbf{0.969} & 0.898 & \textbf{0.961} & \textbf{0.829} & 0.785 & \textbf{0.806} \\ \cline{2-9} & DIEN & \textbf{0.722} & 0.965 & \textbf{0.890} & 0.960 & 0.820 & \textbf{0.791} & 0.805 \\ \cline{2-9} & Adver. & - & - & - & 0.926 & 0.742 & 0.741 & 0.741 \\ \hline \end{tabular} \end{table*} \begin{table}[h] \centering \caption{Reward estimation performance comparison between different supervised learning methods for environment simulation (mean., abs., and std. represent the mean, absolute mean, and standard deviation of reward prediction error respectively).} \begin{tabular}{|c|clc|clc|} \hline \multirow{2}{*}{} & \multicolumn{3}{c|}{RL4RS-A} & \multicolumn{3}{c|}{RL4RS-B} \\ \cline{2-7} & \multicolumn{1}{c|}{mean.} & \multicolumn{1}{c|}{abs.} & std. & \multicolumn{1}{c|}{mean} & \multicolumn{1}{c|}{abs.} & std. \\ \hline DNN & \multicolumn{1}{c|}{0.87} & \multicolumn{1}{c|}{41.6} & 66.3 & \multicolumn{1}{c|}{5.4} & \multicolumn{1}{c|}{89.0} & 118.7 \\ \hline Wide\&Deep & \multicolumn{1}{c|}{1.03} & \multicolumn{1}{c|}{41.1} & 64.9 & \multicolumn{1}{c|}{6.8} & \multicolumn{1}{c|}{78.7} & 110.9 \\ \hline GRU4Rec & \multicolumn{1}{c|}{-1.2} & \multicolumn{1}{c|}{36.5} & 61.7 & \multicolumn{1}{c|}{3.3} & \multicolumn{1}{c|}{68.9} & \textbf{102.5} \\ \hline DIEN & \multicolumn{1}{c|}{0.5} & \multicolumn{1}{c|}{\textbf{36.2}} & \textbf{60.9} & \multicolumn{1}{c|}{-2.4} & \multicolumn{1}{c|}{\textbf{66.2}} & 102.8 \\ \hline \end{tabular} \label{table:simulator_eval} \vspace{-4mm} \end{table} \textbf{RL Model Training.} Given the simulation environment, we can employ any classical RL algorithms. When working on large discrete action spaces (more than thousands of possible actions), one alternative is to address it with a continuous-action RL algorithm and combine policy gradients with a K-NN search~\cite{2015Deep}. When only sorting a few candidate items, we can choose to create a variant of DQN called Parametric-Action DQN, in which we input concatenated state-action pairs and output the Q-value for each pair. The Parametric-Action DQN~\cite{Gauci2018HorizonFO} can make full use of rich item features, which is important for recommendation systems. Here, RL4RS suite provides both discrete-action baselines, includeing Exact-k~\cite{Gong2019ExactKRV}, PG~\cite{Sutton1999PG}, DQN~\cite{dqn}, A2C~\cite{Mnih2016A2C} and PPO~\cite{schulman2017proximal}, and continuous-action baselines combining policy gradients with a K-NN search, includeing PG, A2C, DDPG~\cite{ddpg} and PPO. All these algorithms except Exact-k are implemented based on the open-source reinforcement learning library RLlib~\cite{liang2018rllib}. The online evaluation results built on the learned DIEN-based simulation environment are shown in Table \ref{tab:online_training}. The results consistently show that, compared with the discrete RL model, the performances of RL baselines are greatly reduced when modeling the problem as a continuous control RL problem. Among all baselines, DDPG model for continuous environment, PG/PPO/A2C for discrete environment are the best. For the sequential slate recommendation problem which has more decision steps, the performance of PG is not dominant. Among all baselines, PPO model for both continuous environment and discrete environment is the best. It also can be found that all model-free RL methods achieve far more rewards than the logged behavior policy, even compared with the RL4RS-A-RL and RL4RS-B-RL dataset which are collected after RL deployed (although online rewards will be weakened by various business rules, such as diversity and the reduction of power of popular items). In the recommendation systems, the rewards brought by different items are often extremely unbalanced (e.g., a wide range of item prices). It means the rewards may be dominated by several high-price items. Besides, due to the characteristics of RL training and testing in the same environment, we also doubt that RL overfits the simulation environment. The related experimental results are reported in Section 6. \begin{table}[tb] \centering \caption{Performance comparison between model-free RL algorithms on the learned simulation environment.} \label{tab:online_training} \begin{tabular}{lcc} \toprule Rewards of & RL4RS-A & RL4RS-B \\ \hline PG & \textbf{161.1}($\pm$2.6) & 275.8($\pm$2.3) \\ DQN & 133.0($\pm$2.3) & 226.1($\pm$3.5) \\ A2C & 159.8($\pm$4.5) & 282.1($\pm$9.2) \\ PPO & 160.4($\pm$6.0) & \textbf{319.7}($\pm$10.8) \\ Exact-k & 136.8($\pm$3.1) & - \\ PG-conti & 116.1($\pm$1.2) & 102.8($\pm$3.1) \\ A2C-conti & 120.3($\pm$4.9) & 218.5($\pm$8.6) \\ PPO-conti & 127.5($\pm$3.3) & 261.9($\pm$4.8) \\ DDPG & 146.1($\pm$3.1) & 240.9($\pm$5.4) \\ \bottomrule \end{tabular} \label{table:env} \vspace{-4mm} \end{table} \subsection{Offline Policy Learning} Offline policy learning aims to learn a better policy from the offline experience pool collected by poor behavior policies. Corresponding to RL-based RS, we have the user feedback data collected by supervised learning as the offline dataset. RL4RS suite provides two kinds of baselines, imitation learning (behavioral cloning) and batch RL (BCQ~\cite{fujimoto2019off} and CQL~\cite{2020Conservative}) . Behavioral cloning trains a policy to mimic the behavior policy from the data. We treat behavioral cloning (BC) as a baseline of offline learning methods. BCQ learns a state-conditioned generative model to mimic the behavior policy of the dataset, and a perturbation network to generate actions. The learned policy is constrained near the original behavior policy. CQL penalizes the value function for states and actions that are not supported by the data to prevent overestimation of the training policy. All these algorithms are implemented based on the open-source batch RL library d3rlpy~\cite{seno2020d3rlpy}. The online evaluation results built on the learned DIEN-based simulation environment are shown in Table \ref{tab:offline_training}. It can be seen that the BC algorithm which imitates behavior policies achieves higher rewards than the averaged rewards per session in RL4RS-B dataset (sequential slate recommendation scenario). This may be due to BC taking the best item per step rather than sampling according to probability. In addition, BCQ and CQL achieve much better results than BC, which shows the effectiveness of offline policy learning. Compared with model-free RL baselines, batch RL methods achieve lower rewards. This is reasonable because model-free RL is trained in the test environment in an online manner. Besides online evaluation, more evaluation results are reported in Section 6. \begin{table}[h] \centering \caption{Performance comparison between batch RL algorithms on the learned simulation environment.} \label{tab:offline_training} \begin{tabular}{lcc} \toprule Rewards of & RL4RS-A & RL4RS-B \\ \hline BC & 94.1($\pm$1.6) & 223.9($\pm$4.5) \\ BCQ & \textbf{127.4}($\pm$3.6) & \textbf{262.4}($\pm$5.7) \\ CQL & 103.5($\pm$3.1) & 247.5($\pm$5.3) \\ \bottomrule \end{tabular} \label{table:offline_training} \end{table} \section{Policy Evaluation} In the previous section, we provide a simple performance comparison between model-free RL and batch RL. These results are collected following the traditional RL evaluation framework, that is, training and evaluating on the same environment. However, in real applications, it is usually rare to have access to a perfect simulator. A policy should be well evaluated before deployment because policy deployment affects the real world and can be costly. In applied settings, policy evaluation is not a simple task that can be quantified with only a single indicator (e.g., reward). As shown in Figure 4, in this paper, we attempt to propose a comprehensive evaluation framework for RL-based RS, including environment simulation evaluation (also discussed in Sec.5.1), counterfactual policy evaluation (offline policy evaluation), and evaluation on simulation environments built from test set (online policy evaluation). \begin{figure}[h] \includegraphics[scale=0.16]{eval.jpg} \caption{The evaluation framework for the RL-based RS task. \label{Fig:eval}} \end{figure} \subsection{Counterfactual Policy Evaluation} Counterfactual policy evaluation (CPE) is a set of methods used to predict the performance of a newly learned policy without having to deploy it online~\cite{is,dudik2011doubly,jiang2016doubly,thomas2016magic}. The RL4RS suite provides several well-known counterfactual policy evaluation (CPE) methods to score trained models offline, including direct method, importance sampling~\cite{is}, step-wise weighted importance sampling (SWIS), doubly-robust~\cite{dudik2011doubly}, and sequential doubly-robust~\cite{jiang2016doubly}. The direct method (DM) learns a regression-based reward function to estimate the expected rewards incur by the evaluated policy. To generalize, simulation environment evaluation can be viewed as a type of DM method. The importance sampling (IS) uses the action propensities of behavior and newly learned policies to scale the logged rewards, resulting in high variance when the action propensities of behavior policy are not logged. An improved step-wise IS version defines the t-step cumulative importance ratio and achieves lower variance. The doubly-robust (DR) combines the ideas of the previous two methods and is widely used in contextual bandits. The sequential doubly-Robust method is developed specifically for evaluating policies on longer horizons. We use four counterfactual policy evaluation methods (IS, SWIS, DR and sequential DR) to evaluate the trained strategies described in Section 5.1 and 5.2. The results are shown in Table \ref{tab:offline_evaluation}. The CPE results indicate the expected performance of the newly trained policy relative to the policy that generated the dataset. A score of 1.0 means that the RL and the logged policy match in performance. The DR score of DQN (1.43) means that the DQN policy should achieve roughly 1.43x as much cumulative reward as the behavior policy. The IS method is relatively unstable in value. After multiplying the action probabilities, it is easy to reach the upper and lower clipped limits. The DR-based method performs relatively well, thanks to the value function estimated by the simulation environment. From the overall results,, it seems that the counterfactual policy evaluation methods are not suitable for the evaluation of policies that deviate a lot from the logged behavior policy. We will explore more state-of-the-art CPE methods in the future. \begin{table}[tb] \small \centering \caption{Counterfactual policy evaluation on learned model-free RL and batch RL algorithms.} \label{tab:offline_evaluation} \begin{tabular}{lcccc} \toprule RL4RS-A & IS & SWIS & DR & Seq. DR \\ \hline BCQ & 9.1($\pm$0.61) & 1.0($\pm$0.01) & 1.55($\pm$0.03) & 1.59($\pm$0.06) \\ CQL & 130.6($\pm$6.32) & 1.0($\pm$0.01) & 2.2($\pm$0.02) & 2.95($\pm$0.04) \\ DQN & 9.2($\pm$0.97) & 1.0($\pm$0.01) & 1.43($\pm$0.02) & 1.66($\pm$0.08) \\ PPO & 9.15($\pm$1.23) & 1.0($\pm$0.01) & 1.24($\pm$0.03) & 1.45($\pm$0.07) \\ A2C & 9.6($\pm$1.12) & 1.0($\pm$0.01) & 0.77($\pm$0.02) & 0.93($\pm$0.03) \\ \bottomrule \end{tabular} \label{table:offline_training2} \end{table} \subsection{Evaluation On Simulation Environment} The second method is to establish an environment on the test set to evaluate the algorithm. Different from testing in the same environment, we emphasize the establishment of environment model on test set according to the evaluation framework of supervised learning. In many recommendation scenarios, the training set and test set need to be divided according to time, which makes this more important. Another popular evaluation method adopted by most current works is to divide users before policy training. Although the training and test data are not overlapped, they are sharing the same environment. This method still exists a risk of over-fitting, because the estimated reward of the test set will be affected by the train set through the shared environment. According to the method described in Section 5.2, we use DIEN algorithm to train the environment model on the training set and the test set respectively. We use the most strict dataset dividing setting, that is, RL4RS-SL as the train set and RL4RS-RL as the test set. Not only they are not overlapped on time, but also there are considerable differences in data distribution between them. For model-free RL and batch RL, we compare the performance of the following three settings: (1) constructing environment model on RL4RS-SL plus RL4RS-RL, training the policy on RL4RS-SL, evaluating on RL4RS-SL; (2) constructing environment model on RL4RS-SL, training the policy on RL4RS-SL, evaluating on RL4RS-RL; (3) constructing environment model on RL4RS-SL, training the policy on RL4RS-SL, evaluating on the environment model built from RL4RS-RL. For environment simulation, we provide the result of the following two setting: (1) constructing environment model on RL4RS-SL, and then evaluating on RL4RS-RL; and (2) constructing environment model on RL4RS-RL, and then evaluating on RL4RS-SL; The results of training on all dataset and evaluate on RL4RS-SL and RL4RS-RL are also provided as a baseline. The results are as follows. \begin{table}[tb] \centering \caption{Reward estimation performance comparison of DIEN-based environment simulator between different environment simulation settings (setting 1, 2, 3, and 4 represent the setting of training on all dataset then testing on RL4RS-SL, training on all dataset then testing on RL4RS-RL, training on RL4RS-RL then testing on RL4RS-SL, and training on RL4RS-SL then testing on RL4RS-RL respectively).} \begin{tabular}{|c|clc|clc|} \hline \multirow{2}{*}{} & \multicolumn{3}{c|}{RL4RS-A} & \multicolumn{3}{c|}{RL4RS-B} \\ \cline{2-7} & \multicolumn{1}{c|}{mean.} & \multicolumn{1}{c|}{abs.} & std. & \multicolumn{1}{c|}{mean} & \multicolumn{1}{c|}{abs.} & std. \\ \hline Setting 1 & \multicolumn{1}{c|}{-2.3} & \multicolumn{1}{c|}{38.1} & 66.5 & \multicolumn{1}{c|}{-13.3} & \multicolumn{1}{c|}{63.5} & 99.3 \\ \hline Setting 2 & \multicolumn{1}{c|}{-2.7} & \multicolumn{1}{c|}{36.3} & 61.4 & \multicolumn{1}{c|}{-6.8} & \multicolumn{1}{c|}{65.0} & 97.7 \\ \hline Setting 3 & \multicolumn{1}{c|}{1.2} & \multicolumn{1}{c|}{42.4} & 69.4 & \multicolumn{1}{c|}{2.4} & \multicolumn{1}{c|}{71.5} & 106.5 \\ \hline Setting 4 & \multicolumn{1}{c|}{4.5} & \multicolumn{1}{c|}{40.6} & 64.4 & \multicolumn{1}{c|}{23.3} & \multicolumn{1}{c|}{81.0} & 106.9 \\ \hline \end{tabular} \label{table:simulator_eval_2} \vspace{-4mm} \end{table} From Table 10, it can be found that, comparing setting 3/4 and setting 1/2, there is basically a 10\% increase in the absolute mean indicator and a 5\% increase on the standard deviation indicator on RL4RS-A dataset. On RL4RS-B dataset, the indicator difference widens further, especially with setting 4 versus setting 2. Since the initial error of environment construction is already large, the impact of dataset division is difficult to measure directly. It needs to be further revealed by the results of the RL algorithms. \begin{table}[tb] \centering \caption{Performance comparison between batch RL algorithms on different experiment settings (setting 1, 2, 3, and 4 represent the setting of building environment and training on all dataset then test on RL4RS-RL, building environment on all dataset and training on RL4RS-SL then test on RL4RS-RL, building environment and training on RL4RS-SL then test on RL4RS-RL, and building environment and training on RL4RS-SL then test on the environment built from RL4RS-RL respectively).} \begin{tabular}{|c|clc|clc|} \hline \multirow{2}{*}{} & \multicolumn{3}{c|}{RL4RS-A} & \multicolumn{3}{c|}{RL4RS-B} \\ \cline{2-7} & \multicolumn{1}{c|}{BC} & \multicolumn{1}{c|}{BCQ} & CQL & \multicolumn{1}{c|}{BC} & \multicolumn{1}{c|}{BCQ} & CQL \\ \hline Setting 1 & \multicolumn{1}{c|}{98.0} & \multicolumn{1}{c|}{132.9} & 107.2 & \multicolumn{1}{c|}{240.7} & \multicolumn{1}{c|}{277.2} & 259.4 \\ \hline Setting 2 & \multicolumn{1}{c|}{98.8} & \multicolumn{1}{c|}{133.4} & 98.8 & \multicolumn{1}{c|}{244.7} & \multicolumn{1}{c|}{273.7} & 268.3 \\ \hline Setting 3 & \multicolumn{1}{c|}{103.7} & \multicolumn{1}{c|}{200.7} & 109.3 & \multicolumn{1}{c|}{230.6} & \multicolumn{1}{c|}{288.9} & 274.2 \\ \hline Setting 4 & \multicolumn{1}{c|}{107.1} & \multicolumn{1}{c|}{133.6} & 108.6 & \multicolumn{1}{c|}{139.5} & \multicolumn{1}{c|}{196.6} & 174.6 \\ \hline \end{tabular} \label{table:offline_training_2} \vspace{-4mm} \end{table} Table 11 shows the results of the three batch RL algorithms under the three experimental settings mentioned above and the baseline experimental settings (setting 1). Because the experiments are time-consuming, only a few rounds of experiments have been done at present. We will provide the averaged results of more rounds in the future. From the comparison between setting 3/4 and setting 2, the choice of environment construction dataset has a great impact on the final result. Compared with setting 2 and setting 1, the results do not show much difference (except CQL algorithm). It may be because they both use all dataset to construct the environment model. Although setting 2 only trains on RL4RS-SL, it also learns a lot from RL4RS-RL. \section{Availability} An old version of RL4RS is available at \textbf{ \textit {\url{https://www.kaggle.com/c/bigdata2021-rl-recsys/data}}} for direct download and use. To support findability and sustainability, the RL4RS dataset is published as an online resource at \textbf{ \textit {\url{https://fuxi-up-research.gitbook.io/open-project/}}}. A separate page with detailed explanations and illustrations is available at \textbf{ \textit {\url{https://fuxi-up-research.gitbook.io/fuxi-up-challenges/}}} to promote ease-of-use. The project GitHub repository contains the complete source code for the system and generation script is available at \textbf{ \textit {\url{https:/github.com/fuxiAIlab/RL4RS}}}. Documentation includes all relevant metadata specified to the research community and users. It is freely accessible under the \textit{Creative Commons Attribution 4.0 International license}, making it reusable for almost any purpose. \subsection{Updating and Reusability} RL4RS is supported by a team of researchers from the Fuxi AI Lab, the Netease Inc. The resource is already in use for individual projects and as a contribution to the data challenge of BigData conference 2021. In addition to the steps above that make the resource available to the wider community, usage of RL4RS will be promoted to the network of researchers in this project. A new dataset for bundle recommendation with variable discounts, flexible recommendation trigger, and modifiable item content is in prepare. In future, we will add more datasets from other novel RS scenarios to support the research of RL-based RS. RL4RS benchmark will be supported and maintained for three years. \subsection{System Configuration} Pipelines for all tasks are trained for at most 100 epochs with an early stop on a single GeForce GTX 2080 Ti GPU, 8CPU, and 64GB memory. The code for the dataset splits is also available. For all tasks, consistent hyperparameter settings are maintained to enable comparative analysis of the results. The batch size is set at 256 with a learning rate of 0.001, a probability of 0.1 in dropout layers and the embedding size is 128. \section{Related Research} This benchmark is oriented to the reinforcement learning based recommender systems domain. In 2015, Shani et al.~\cite{shani2005mdp} proposes to model the recommendation system problem as an MDP process for the first time. In 2018, DRN~\cite{zheng2018drn} first apply deep RL into recommendation problems and inspire a series of subsequent works. SlateQ~\cite{Ie2019SlateQAT} is the first work to concern the novel slate recommendation scenario. Top-k off-policy~\cite{chen2019topk} learn the policy from the offline RS dataset directly for the first time. Adversarial User Model~\cite{chen2019adversarialgenerative} first popularizes semi-simulated RS datasets and simulates the environment using adversarial learning. Virtual-Taobao~\cite{Shi2019VirtualTaobaoVR} is the only work to open-source a pre-trained simulation environment (but without raw logged data) that comes from a real RS scenario. A detailed comparison is listed in Section 2. Outside of the RS domain, research on reinforcement learning for the online environment has an extensive history and we focus here on resources and benchmark tasks where samples are collected from real applications and present in batched offline data, such as DeepMind Control Suite~\cite{2018Control}, D4RL~\cite{2020D4RL} and RL unplugged~\cite{2020RLUnplugged}. All of these resources exclude recommendation scenarios. And most batched datasets of these resources are collected by mixed, nearly random policies, and usually equipped with a deterministic environment. However, these characteristics are inconsistent with the characteristics of RS data. RL-based RS can also be regarded as a neural combinatorial optimization (NCO) problem, especially for the slate recommendation scenario where the item are displayed as a matrix on the page. Several works~\cite{Gong2019ExactKRV} try to use reinforcement learning to generate item sets and avoid enumerating exponential possible combinations. Like the research of RL-based RS, current NCO works~\cite{Gasse2019ExactCO, Cappart2021CombinatorialOA} also lack attention to real datasets, offline policy evaluation, and extrapolation error. We expect RL4RS resources can also contribute to research in neural combinatorial optimization. \section{Conclusion and Future Work} In this paper, we present the RL4RS resource, a real-world benchmark for RL-based RS. Since RS datasets are lack of ground-truth environment and usually collected with deployed supervised learning policies, for real-world considerations, RL4RS focuses on simulation environment construction, extrapolation error, offline policy learning, and offline policy evaluation, which are ubiquitous and crucial in recommendation scenarios. So far, RL4RS has included two novel scenarios: slate recommendation, and sequential slate recommendation. The separated data before and after RL deployment are also available for each dataset. We benchmark some state-of-the-art online and batch RL algorithms in both online and offline policy evaluation. In addition, we further explore the quantitative analysis for extrapolation error and the use of counterfactual policy evaluation for RL-based RS problems. In the future, we will constantly provide new real-world RS datasets and step further towards real-world RS challenges. We also hope the RL4RS benchmark will shed some light on future research of applied reinforcement learning and neural combinatorial optimization. \bibliographystyle{plain} {\footnotesize
{'timestamp': '2022-02-22T02:25:50', 'yymm': '2110', 'arxiv_id': '2110.11073', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.11073'}
arxiv
\section{Introduction} One of the most fruitful and influential lines of research of Logic in Computer Science is the algebraic study of computation. After Moggi's seminal work \cite{moggi91monads} showed that notions of computation can be represented as monads, Plotkin and Power \cite{plotkinpower02} approached the problem using operations and equations, i.e., Lawvere theories. Since then, various extensions of the notion of Lawvere theory have been introduced in order to accommodate an ever increasing number of computational notions within this framework; see, e.g., \cite{plotkinpower03,hylandpower07,nishizawa2009lawvere}, and more recently \cite{bacci2018algebraic,bacci2020quantitative} for quantitative algebraic reasoning for probabilistic computations. Along this line of research, in this work we study algebraic reasoning on \emph{fuzzy sets}. Algebraic structures on fuzzy sets are well known since the seventies (see e.g., \cite{rosenfeld1971fuzzy,mashour1990normal,ajmal1994homomorphism, mordeson2012fuzzy}). Fuzzy sets are very important in computer science, with applications ranging from pattern recognition to decision making, from system modeling to artificial intelligence. So, it is natural to ask if it is possible to use an approach similar to above for \emph{fuzzy algebraic reasoning} In this paper we answer positively to this question. We propose a sequent calculus based on two kind of propositions, one expressing equality of terms and the other the existence of a term as a member of a fuzzy set. These sequents have a natural interpretation in categories of fuzzy sets endowed with operations. This calculus is sound and complete for such a semantics: a formula is satisfied by all the models of a given theory if and only if it is derivable from it. It is possible to go further. Both in the classical and in the quantitative settings there is a notion of free model for a theory; we show that is also true for theories in our formal system for fuzzy sets. In general the category of models of a given theory will not be equivalent to the category of Eilenberg-Moore algebras for the induced monad, but we will show that this equivalence holds for theories with sufficiently simple axioms. Finally we will use the techniques developed in \cite{milius2019equational} to prove two results analogous to Birkhoff's theorem. \smallskip \noindent\textit{Synopsis.} In \cref{sec:fuzzy} we recall the category $\fuz{H}$ of fuzzy sets over a frame $H$. \cref{sec:the} introduces the syntax and the rules of fuzzy theories. Then, in \cref{sec:al} we introduce the notions of algebras for a signature and of models for a theory; in this section we will also show that the calculus proposed is sound and complete. \cref{sec:fre} is devoted to free models and it is shown that if a theory is \emph{basic} then its category of models arose as the category of Eilenberg-Moore algebras for a monad on $\fuz{H}$. In \cref{sec:birk} we use the results of \cite{milius2019equational} to prove two HSP-like theorems for our calculus. Finally, \cref{sec:conc} draws some conclusions and directions for future work. \cref{sec:der} contains two detailed derivations used in the paper. \section{Fuzzy sets} \label{sec:fuzzy} In this section we will recall the definition and some well-known properties of the category of fuzzy sets over a frame $H$ (i.e. a complete Heyting algebra \cite{johnstone1982stone}). \begin{definition}[\cite{wyler1991lecture,wyler1995fuzzy}] Let $H$ be a frame. A \emph{$H$-fuzzy set} is a pair $(A, \mu_A)$ consisting in a set $A$ and a \emph{membership function} $\mu_A:A\rightarrow H$. The \emph{support of $\mu_A$} is the set $ \supp{A}$ of elements $x\in A$ such that $\mu_A(x)\neq \bot$. An arrow $f:(A, \mu_A)\rightarrow (B, \mu_B)$ is a function $f:A\rightarrow B$ such that $\mu_A(x)\leq \mu_B(f(x))$ for all $x\in A$. We denote by $\fuz{H}$ the category of $H$-fuzzy sets and their arrows. We will often drop the explicit reference to the frame $H$ when there is no danger of confusion. \end{definition} \begin{proposition}\label{adj}For any frame $H$, the forgetful functor $\mathscr{V}:\fuz{H}\rightarrow \catname{Set}$ has both a left and a right adjoint $\nabla$ and $\Delta$ endowing a set $X$ with the function constantly equal to the bottom and the top element of $H$, respectively. \end{proposition} \begin{proof} If $\nabla(X)$ and $\Delta(X)$ are, respectively $(X,c_\bot)$ and $(X, c_\top)$, where $c_\bot$ and $c_\top$ are the functions $X\rightarrow H$ constant in $\bot$ and $\top$, then for any $X\in \catname{Set}$, $ \id{X}:\mathscr{V}(\Delta(X))=X\rightarrow X=\mathscr{V}(\nabla(X))$ is the counit of $\mathscr{V}\dashv \Delta$ and the unit of $\nabla \dashv \mathscr{V}$. \end{proof} \begin{definition} Let $e:A\rightarrow B$ and $m:C\rightarrow D$ be two arrows in a category $\catname{C}$, we say that $m$ has \emph{the left lifting property with respect to $e$} if for any two arrows $f:A\rightarrow C$ and $g:B\rightarrow D$ such that $m\circ f=g\circ e$ there exists a unique $k:B\rightarrow C$ with $m\circ k= g$. A \emph{strong monomorphism} is an arrow $m$ which has the left lifting property with respect to all epimorphisms. \end{definition} \begin{proposition}\label{mono} Let $f:(A, \mu_A)\rightarrow (B, \mu_B)$ be an arrow of $\fuz{H}$, then: \begin{enumerate} \item $f$ is a monomorphism iff it is injective; $f$ is an epimorphism iff it is surjective; \item $f$ is a strong monomorphism iff it is injective and $\mu_B(f(x))=\mu_A(x)$ for all $x\in A$; \item $f$ is a split epimorphism iff for any $b\in B$ there exists $a_b\in f^{-1}(b)$ s.t.~$\mu_B(b)=\mu_A(a_b)$. \end{enumerate} \end{proposition} Let us start with the following observation. \begin{remark}\label{mon} In any category $\catname{C}$, if $m:A\rightarrow B$ is a strong monomorphism then it is a monomorphism. Suppose that $m\circ f = m\circ g$ for some $f$ and $g$, then we have the square \vspace{-0.5ex} \begin{center} \begin{tikzpicture} \node(A)at(0,0){$C$}; \node(B)at(0,-1.5){$C$}; \node(C)at(1.5,-1.5){$B$}; \node(D)at(1.5,0){$A$}; \draw[->](A)--(B)node[pos=0.5, left]{$\id{C}$}; \draw[->](B)--(C)node[pos=0.5, below]{$m\circ g$}; \draw[->](A)--(D)node[pos=0.5, above]{$f$}; \draw[<-](C)--(D)node[pos=0.5, right]{$m$}; \end{tikzpicture} \end{center} thus there exists a unique $k$ such that $m\circ k= m \circ g$ but both $f$ and $g$ satisfy this equation. \end{remark} \begin{remark} Notice that the previous remark implies that for any square as in the definition of strong monomorphism, $k\circ e=f$. \end{remark} \begin{proof}[Proof of \cref{mono}] \begin{enumerate} \item $\mathscr{V}:\fuz{H}\rightarrow \catname{Set}$ is faithful, so it reflects monomorphisms and epimorphisms, since it is both a left and a right adjoint it preserves them too, hence $1$ follows. \item Let us show the two implications. \begin{itemize} \item[$\Rightarrow$] Injectivity follows from \cref{mon}, let $(D, \mu_D)\coloneqq(f(A), {\mu_B}_{|f(A)})$ be the set-theoretic image of $f$ endowed with the restriction of $\mu_B$. We have a factorization of $f$ as $m\circ e$ where $m$ is a monomorphism and $e$ an epimorphism, so we have the square \begin{center} \begin{tikzpicture} \node(A)at(0,0){$(A, \mu_A)$}; \node(B)at(0,-1.5){$(D, {\mu_D})$}; \node(C)at(3,-1.5){$(B,\mu_B)$}; \node(D)at(3,0){$(A, \mu_A)$}; \draw[->](A)--(B)node[pos=0.5, left]{$e$}; \draw[->](B)--(C)node[pos=0.5, below]{$m$}; \draw[->](A)--(D)node[pos=0.5, above]{$\id{(A,\mu_A)}$}; \draw[<-](C)--(D)node[pos=0.5, right]{$f$}; \end{tikzpicture} \end{center} and its diagonal filling $k:(D, \mu_D)\rightarrow (A, \mu_A)$. For any $x\in A$: \begin{align*} \mu_B(f(x))=\mu_{B}(m(e(x)))=\mu_D(e(x))\geq \mu_A(k(e(x)))=\mu_A(x) \end{align*} and we get the thesis. \item[$\Leftarrow$] Any square \vspace{-1ex} \begin{center} \begin{tikzpicture} \node(A)at(0,0){$(C, \mu_C)$}; \node(B)at(0,-1.5){$(D, {\mu_D})$}; \node(C)at(2,-1.5){$(B,\mu_B)$}; \node(D)at(2,0){$(A, \mu_A)$}; \draw[->](A)--(B)node[pos=0.5, left]{$e$}; \draw[->](B)--(C)node[pos=0.5, below]{$m$}; \draw[->](A)--(D)node[pos=0.5, above]{$g$}; \draw[<-](C)--(D)node[pos=0.5, right]{$f$}; \end{tikzpicture} \end{center} induces the square \begin{center} \begin{tikzpicture} \node(A)at(0,0){$C$}; \node(B)at(0,-1.5){$D$}; \node(C)at(1.5,-1.5){$B$}; \node(D)at(1.5,0){$A$}; \draw[->](A)--(B)node[pos=0.5, left]{$e$}; \draw[->](B)--(C)node[pos=0.5, below]{$m$}; \draw[->](A)--(D)node[pos=0.5, above]{$g$}; \draw[<-](C)--(D)node[pos=0.5, right]{$f$}; \end{tikzpicture} \end{center} in $\catname{Set}$, which, by point $1$ and $2$, has a diagonal filling $k:D\rightarrow A$. Now: \begin{align*} \mu_D(x)\leq \mu_B(m(x))=\mu_B(f(k(x)))= \mu_A(k(x)) \end{align*} and we can conclude that $k$ is an arrow of $\fuz{H}$. \item If $f$ is split then there exists a right inverse $e:(B, \mu_B)\rightarrow (A, \mu_A)$ and we can put $a_b:=e(b)$. The other direction follows noticing that $b\mapsto a_b$ is a splitting of $f$.\qedhere \end{itemize} \end{enumerate} \end{proof} \begin{definition}[\cite{kelly1991note}] A \emph{proper factorization system} on a category $\catname{C}$ is a pair $(\mathscr{E}, \mathscr{M})$ given by two classes of arrows such that: \begin{itemize} \item $\mathscr{E}$ and $\mathscr{M}$ are closed under composition; \item every isomorphism belongs to both $\mathscr{E}$ and $\mathscr{M}$; \item every $e\in \mathscr{E}$ is an epimorphism and every $m\in \mathscr{M}$ is a monomorphism; \item every $m\in \mathscr{M}$ has the left lifting property with respect to every $e\in \mathscr{E}$; \item every arrow of $\catname{C}$ is equal to $m\circ e$ for some $m\in\mathscr{M}$ and $e\in \mathscr{E}$. \end{itemize} \end{definition} \begin{lemma}\label{prod} For any frame $H$, $\fuz{H}$ has all products. Moreover the classes of epimorphisms and strong monomorphisms form a proper factorization system on it. \end{lemma} \begin{proof} $\Delta(1)$ is the terminal object by \cref{adj}. Given a family $\qty{\qty(A_i, \mu_{i})}$ of fuzzy sets, their product is constructed taking their product in $\catname{Set}$ equipped with \begin{align*} \mu:\prod_{i\in I}A_i \rightarrow H\qquad \qty(a_i)_{i\in I} \mapsto \bigwedge_{i\in I}\mu_i(a_i) \end{align*} The last part of the thesis follows at once noticing that every arrow $f:(A,\mu_A)\rightarrow (B, \mu_B)$ factors as \begin{equation*} (A, \mu_A )\xrightarrow{e} (f(A), {\mu_{B}}_{|f(A)})\xrightarrow{m}(B, \mu_B) \end{equation*} and applying \cref{mono}. \end{proof} \begin{remark} Completeness and the existence of both adjoints to $\mathscr{V}$ can be deduced directly from the fact that $\fuz{H}$ is topological over $\catname{Set}$ \cite[Prop.~71.3]{wyler1991lecture}. \end{remark} \section{Fuzzy Theories}\label{sec:the} In this section we introduce the syntax and logical rules of fuzzy theories. The first step is to introduce an appropriate notion of signature. Differently from usual signatures, in fuzzy theories constants cannot be seen simply as 0-arity operations, because , as we will see in \cref{sec:al}, these are interpreted as fuzzy morphisms from the terminal object, and these correspond only to elements whose membership degree is $\top$. \begin{definition} A \emph{signature} $\Sigma=( O, \ar, C)$ is a set $O$ of \emph{operations} with an \emph{arity function} $\ar:O\rightarrow \mathbb{N}_+$ and a set $C$ of \emph{constants}. Signatures form a category $\catname{Sign}$ in which an arrow $\Sigma_1=(O_1, \ar_1, C_1)\rightarrow \Sigma_2=(O_2, \ar_2, C_2)$ is a pair $ \mathbf{F}=(F_1, F_2)$ of functions: $F_1:O_1\rightarrow O_2$ and $F_2:C_1\rightarrow C_2$ with the property that $\ar_2\circ F_1= \ar_1$. An \emph{algebraic language} $\mathcal{L}$ is a pair $(\Sigma, X)$ where $\Sigma $ is a signature and $X$ a set. The category $\catname{Lng}$ of algebraic languages is just $\catname{Sign}\times \catname{Set}$. \end{definition} \begin{example} The \emph{signature of semigroups} $\Sigma_S$ in which $O=\{\cdot\}$, $\ar(\cdot)=2$ and $C=\emptyset$. \end{example} \begin{example} The \emph{signature of groups} $\Sigma_G$ is equal to $\Sigma_S$ plus an operation $(-)^{-1}$ of arity $1$ and a constant $e$. \end{example} Given a language $\mathcal{L}$ we can inductively apply the operations to the set of variables to construct terms, and once terms are built we can introduce equations. \begin{definition} Given a language $\mathcal{L}=(\Sigma, X)$, the set $\terms{L}$ is the smallest set s.t. \begin{itemize} \item $X\sqcup C\subset \terms{L}$; \item if $f\in O$ and $t_1,\dots, t_{\ar(f)}\in \terms{L}$ then $f\qty(t_1,\dots, t_{\ar(f)})\in \terms{L}$. \end{itemize} \end{definition} \vspace{-0.5ex} \begin{proposition}\label{terms} There exists a functor $\mathsf{Terms}:\catname{Lng} \rightarrow \catname{Set}$ sending $\mathcal{L}$ to $\terms{L}$. \end{proposition} \begin{proof} For any $F=((F_1,F_2), h):(\Sigma_1, X)\rightarrow (\Sigma_2,Y)$ we can define $\trms{\mathbf{F}}$ by induction: \begin{itemize} \item for any $x\in X$, $\trms{F}(x)\coloneqq g(x)$; \item for any $c\in C_1$, $\trms{F}(c)\coloneqq F_2(c)$; \item for any $f\in O_1$ and $t_1,\dots, t_{\ar_1(f)}\in \terms{L}$ it is $\ar_2(F_1(f))=\ar_1(f)$, so we can define \begin{equation*} \trms{F}\qty(f\qty(t_1,\dots,t_{\ar(f)}))\coloneqq F_1(f)\qty(\trms{F}\qty(t_1),\dots,\trms{F}\qty(t_{\ar(f)}) ) \end{equation*} \end{itemize} Identities are preserved and an easy induction shows that composition is respected. \end{proof} \begin{definition}[Formulae] For any language $\mathcal{L}$ we define the sets $\eqt{L}$ of \emph{equations} as the product $\eqt{L} \coloneqq \terms{L}\times \terms{L}$ and the set $\mmb{L}$ of \emph{membership propositions} as $\mmb{L}\coloneqq H\times \terms{L}$. We will write $s\equiv t$ for $(s,t)\in \eqt{L}$ and $\ex{l}{t}$ for $(l,t)\in \mmb{L}$. The set $\stat{L}$ of {formulae} is then defined as $\eqt{L} \sqcup \mmb{L}$. \end{definition} Clearly, a proposition $s\equiv t$ means ``$s$ and $t$ are equivalent and hence interchangeable''; on the other hand, $\ex{l}{t}$ intuitively means ``the degree of existence of $t$ is at least $l$''. \begin{definition}[Sequent ant fuzzy theory] A \emph{sequent} $\Gamma \vdash \psi$ is an element $(\Gamma, \psi)$ of $\sqt{L}\coloneqq\mathcal{P}(\stat{L})\times\stat{L}$, where $\mathcal{P}$ is the (covariant) power set functor. A \emph{fuzzy theory in the language $\mathcal{L}$} is a subset $\Lambda\subset\sqt{L}$ and we will use $\thr{L}$ for the set $\mathcal{P}\qty(\sqt{L})$. \end{definition} \begin{notazione}\label{not} We will write $\vdash \phi$ for $\emptyset \vdash \phi$. For any function $\sigma: X \rightarrow \terms{L}$ and $t\in \terms{L}$ we denote $t[\sigma]$ the term obtained substituting $\sigma(x)$ to any occurence of $x$ in $t$. \iffalse Explicitly: \begin{itemize} \item $c[\sigma]:=c$ for any $c\in C$; \item $x[\sigma]:=\sigma(x)$ for any $x\in X$; \item For any $f\in O$ and $t_1,\dots,t_{\ar(f)}\in \terms{L}$: \begin{equation*} \qty(f\qty(t_1,\dots,t_{\ar(f)}))[\sigma]:=f\qty(t_1[\sigma],\dots,t_{\ar(f)}[\sigma]) \end{equation*} \end{itemize}\fi Moreover, for any formula $\phi\in \stat{L}$ we define $\phi[\sigma]$ as $t[\sigma]\equiv s[\sigma]$ if $\phi$ is $t\equiv s$ or as $\ex{l}{t[\sigma]}$ if $\phi$ is $\ex{l}{t}$. Finally, given $\Gamma \subset \mathcal{P}(\stat{L})$ we put $\Gamma[\sigma]\coloneqq\{\phi[\sigma]\mid \phi \in \Gamma\}$. \end{notazione} \begin{figure}[t] \[\begin{array}{ccc} \inferrule*[right=A]{ \phi \in \Gamma}{\Gamma \vdash \phi} \qquad \inferrule*[right=Weak]{\Gamma\vdash \phi}{\Gamma\cup \Delta \vdash \phi} & \inferrule*[right=Cut]{\qty{\Gamma\vdash\phi\mid \phi \in \Phi} \\ \Phi \vdash \psi}{\Gamma \vdash \psi} \\ \inferrule*[right=Refl]{\hspace{1pt}}{\Gamma \vdash s\equiv s} \qquad \inferrule*[right=Sym]{\Gamma \vdash s\equiv t}{\Gamma \vdash t\equiv s} & \inferrule*[right=Trans]{\Gamma \vdash s \equiv t \\ \Gamma \vdash t \equiv u }{\Gamma \vdash t \equiv u} \\ \inferrule*[right=Sub]{ \sigma:X \rightarrow \terms{L}\\ \Gamma \vdash \psi}{\Gamma[\sigma] \vdash \psi[\sigma] } & \inferrule*[right=Cong]{f\in O\\ \qty{\Gamma \vdash t_i \equiv s_i}_{i=1}^{\ar(f)}}{\Gamma \vdash f\qty(t_1,\dots,t_{\ar(f)}) \equiv f\qty(s_1,\dots,s_{\ar(f)}) } \\ \inferrule*[right=Inf]{\hspace{1pt}}{\Gamma \vdash \ex{\bot}{t}}\qquad \inferrule*[right=Mon]{\Gamma \vdash \ex{l}{t}}{\Gamma \vdash \ex{l\wedge l'}{t} } & \inferrule*[right=Exp]{\qty{\Gamma \vdash \ex{l_i}{t_i}}_{i=1}^{\ar(f)}} {\Gamma \vdash \ex{\inf\qty(\qty{l_i}_{i=1}^n)}{f\qty(t_1,\dots,t_{\ar(f)}) }} \\ \inferrule*[right=Sup]{S\subset H\\\qty{\Gamma \vdash \ex{l}{t}}_{l\in S}}{\Gamma \vdash \ex{\sup(S)}{t} } & \inferrule*[right=Fun]{\Gamma \vdash t \equiv s \\ \Gamma \vdash \ex{l}{t}}{\Gamma \vdash \ex{ l}{s}} \end{array}\] \caption{Derivation rules for the fuzzy sequent calculus.}\label{fig:scrules} \end{figure} \begin{definition} For any $\mathcal{L}$, the \emph{fuzzy sequent calculus} is given by the rules in \cref{fig:scrules}. Given a fuzzy theory $\Lambda$, its \emph{deductive closure} $\Lambda^\vdash$ is the smallest subset of $\sqt{L}$ which contains $\Lambda$ and it is closed under the rules of fuzzy sequent calculus. A sequent is \emph{derivable from $\Lambda$} (or simply derivable if $\Lambda=\emptyset$) if it belongs to ${\Lambda}^{\vdash}$. We will write $\vdash_ {\Lambda}\phi$ if $\vdash \phi \in \Lambda^{\vdash}$. Finally we say that two theories $\Lambda$ and $\Theta$ are \emph{deductively equivalent} if $\Lambda^\vdash=\Theta^{\vdash}$. \end{definition} The next result shows how maps between languages are lifted to theories. \begin{proposition} For any $\mathbf{F}:\mathcal{L}_1\rightarrow \mathcal{L}_2$ arrow of $\catname{Lng}$: \begin{enumerate} \item there exists a Galois connection $\mathbf{F}_*\dashv \mathbf{F}^*$ between $\qty(\mathsf{Th}\qty(\mathcal{L}_1), \subset)$ and $\qty(\mathsf{Th}\qty(\mathcal{L}_2), \subset)$; \item $ \mathbf{F}_*\qty(\Lambda_1^\vdash)\subset \qty(\mathbf{F}_*\qty(\Lambda_1))^\vdash$ and $\qty(\mathbf{F}^*\qty(\Lambda_2))^\vdash\subset \mathbf{F}^*\qty(\Lambda_2^\vdash)$ for any $\Lambda_1\in \mathbf{Th}(\mathcal{L}_1)$ and $\Lambda_2 \in \mathbf{Th}(\mathcal{L}_2)$. \end{enumerate} \end{proposition} \begin{proof} \begin{enumerate} \item For any formula $\psi$ we can define (using \cref{terms}): \begin{gather*} \stat{\mathbf{F}}(t\equiv s)\coloneqq\trms{\mathbf{F}}(t)\equiv\trms{\mathbf{F}}(s)\\\stat{\mathbf{F}}(\ex{l}{t})\coloneqq\ex{l}{\trms{\mathbf{F}}(t)} \end{gather*} getting a function $ \stat{\mathbf{F}}:\mathsf{Form}\qty(\mathcal{L}_1)\rightarrow \mathsf{Form}\qty(\mathcal{L}_2)$. We can extend it to sequents defining \begin{equation*} \sqt{\mathbf{F}}(\Phi \vdash \psi)\coloneqq\qty{\stat{\mathbf{F}}(\phi)\mid \phi \in \Phi }\vdash \stat{\mathbf{F}}(\psi) \end{equation*} Now it is enough to take $\mathbf{F}_*$ and $\mathbf{F}^*$ as the image and the preimage of $\sqt{\mathbf{F}}$ respectively. \item First of all notice that the two inequalities are equivalent because $\mathbf{F}_*\dashv \mathbf{F}^*$. Now, the first one holds since if a sequent $\Gamma \vdash \phi$ follows from the set of sequents $\qty{\Gamma_i\vdash \phi_i}_{i\in I}$ by the application of one of the rules of the fuzzy sequent calculus then the same rule can be applied to $\qty{\sqt{\mathbf{F}}\qty(\Gamma_i\vdash \phi_i)}_{i\in I}$ to get $\sqt{\mathbf{F}}\qty(\Gamma\vdash \psi)$. \qedhere \end{enumerate} \end{proof} Usually, logics enjoy the so-called ``deduction lemma'', which allows us to treat elements of a theory on a par with assumptions in sequents. In fuzzy theories, this holds in a slightly restricted form, as proved next. \begin{lemma}[Partial deduction lemma]\label{ext} Let $\Lambda$ be in $\thr{L}$ and $\Gamma\in \mathcal{P}\qty(\stat{L})$, let also $\Lambda[\Gamma]$ be the theory $\Lambda \cup \qty{\emptyset \vdash \phi \mid \phi \in \Gamma}$. Then the following are true: \begin{enumerate} \item $\Gamma \cup \Delta \vdash \psi$ in $\Lambda^{\vdash}$ implies $\Delta \vdash \psi$ in $\qty(\Lambda[\Gamma])^{\vdash}$; \item if $\Delta \vdash \psi$ is derivable from $\Lambda[\Gamma]$ without using rule \textsc{Sub} then $\Gamma\cup \Delta \vdash \psi $ is in $\Lambda^{\vdash}$.\qedhere \end{enumerate} \end{lemma} \begin{proof} \begin{enumerate} \item By hypothesis $\Gamma \cup \Delta \vdash \psi$ is in $\Lambda^\vdash$ then, since $\Lambda \subset \Lambda[\Gamma]$, it is also in $\qty(\Lambda[\Gamma])^\vdash$. Now, for any $\phi \in \Gamma$ and $\theta \in \Delta$ rules \textsc{Weak} and A give \begin{equation*} \inferrule*[right=Weak]{\vdash \phi }{\Delta \vdash \phi}\qquad \inferrule*[right=A]{\hspace{1pt} }{\Delta \vdash \theta} \end{equation*} so $\qty{\Delta \vdash \phi \mid \phi \in \Gamma \cup \Delta }$ is contained in $ \qty(\Lambda[\Gamma])^{\vdash}$ and we can apply \textsc{Cut} to get the thesis: \begin{equation*} \inferrule*[right=Cut]{\qty{\Delta \vdash \phi \mid \phi \in \Gamma \cup \Delta }\\ \Gamma \cup \Delta \vdash \psi }{\Delta \vdash \psi} \end{equation*} \item Let us proceed by induction on a derivation of $\Delta \vdash \psi$ from $\Lambda[\Gamma]$. \begin{itemize} \item If $\Delta \vdash \psi\in \Lambda[\Gamma]$ then or $\Delta \vdash \psi\in \Lambda$ and we are done, or $\psi\in \Gamma$ and we can conclude since $\Gamma \cup \Delta \vdash \phi_i$ is in $\Lambda^\vdash$ by rules A and \textsc{Weak} \item If $\Delta\vdash \psi$ follows from the application of one of the rules A, \textsc{Inf} or \textsc{Refl} then it belongs to the closure of any theory, by \textsc{Weak} this is true even for $\Gamma \cup \Delta\vdash \psi $ which, in particular, it belongs to $\Lambda^\vdash$. \item Suppose that $\Delta \vdash \psi$ comes from an application of \textsc{Weak}, then there exists $\Psi$ and $\Phi$ such that $\Psi \cup \Phi=\Delta$ and $\Psi\vdash \phi$ is in $(\Lambda[\Gamma])^\vdash$. By inductive hypothesis we have that \begin{equation*} \inferrule*[right=Weak]{\Gamma \cup \Psi \vdash \psi}{\Gamma \cup \Psi \cup \Phi \vdash \psi } \end{equation*} is a derivation of $\Gamma \cup \Delta \vdash \psi $ from $\Lambda$. \item If $\Delta \vdash \psi$ is derived with an application of \textsc{Cut} as last rule then there exists a set $\Theta$ such that $ \qty{\Delta \vdash \theta \mid \theta \in \Theta} \cup \qty{\Theta\vdash \psi} \subseteq \qty(\Lambda[\Gamma])^\vdash $, therefore, by the inductive hypothesis, we have that $\qty{\Gamma \cup \Delta \vdash \theta \mid \theta \in \Theta} \cup \qty{\Gamma \cup \Theta\vdash \psi}$ is conteined in $\Lambda^\vdash$. Now, by rule A we have that $\qty{\Gamma \cup \Delta \vdash \phi \mid \phi \in \Gamma\cup \Theta}$ is contained in $\Lambda^\vdash$ too and so we can apply \textsc{Cut}: \begin{equation*} \inferrule*[right=Cut]{\qty{\Gamma \cup \Delta\vdash \phi \mid \phi \in \Gamma\cup \Theta}\\ \Gamma \cup \Theta \vdash \psi}{\Gamma \cup \Delta \vdash \psi} \end{equation*} which gives us the thesis. \item Any other rule is of the form \begin{equation*} \inferrule*[right=R]{\qty{\Psi \vdash \xi_j}_{j\in J}}{\Psi \vdash \xi} \end{equation*} therefore, if $\Delta \vdash \psi$ is derived with an application of one of this rules then the set of its premises must be an element of $(\Lambda[\Gamma])^\vdash$ of type $\qty{\Delta \vdash \xi_j}_{j\in J}$, so by inductive hypothesis $\qty{\Gamma\cup \Delta \vdash \theta_j}_{j\in J}\subset \Lambda^\vdash$ and then \begin{equation*} \inferrule*[right=R]{\qty{\Gamma \cup \Delta \vdash \xi_j}_{j\in J}}{\Gamma \cup \Delta \vdash \psi} \end{equation*} witnesses the thesis.\qedhere \end{itemize} \end{enumerate} \end{proof} \begin{example}\label{ex:semig1} Our first set of running examples is inspired by \cite{mordeson2012fuzzy}. Let $\Sigma_{S}$ be the signature of semigroups and $X$ a countable set. The theory of \emph{fuzzy semigroups} $\Lambda_S$ is simply the usual theory of semigroups, i.e given by the sequent (using infix notation) \begin{gather*} \vdash (x\cdot y)\cdot z \equiv x\cdot (y \cdot z) \end{gather*} We get the theory of \emph{left ideal} $\Lambda_{LI}$ if we add the axioms (one for any $l\in L$): \begin{equation*} \ex{l}{y} \vdash \ex{l}{x\cdot y} \end{equation*} Similarly the theory $\Lambda_{RI}$ of \emph{right ideal} is obtained from the axioms: \begin{equation*} \ex{l}{x} \vdash \ex{l}{x\cdot y} \end{equation*} Finally we get the theory of \emph{(bilateral) ideal} $\Lambda_I$ taking the union of the above theories. \end{example} \begin{example}[\cite{rosenfeld1971fuzzy, ajmal1994homomorphism, ajmal1992fuzzy}]\label{ex:fuzzyg1} Let $\Sigma_{G}$ be the signature of groups and $X$ a countable set. The theory $\Lambda_G$ of \emph{fuzzy groups} is simply the usual theory of groups, i.e that given by the sequents \begin{gather*} \vdash x \cdot x^{-1} \equiv e \quad \vdash x^{-1} \cdot x \equiv e \quad \vdash e\cdot x \equiv x \quad \vdash x \cdot x \equiv x \quad \vdash (x\cdot y)\cdot z\equiv x\cdot (y \cdot z) \end{gather*} We get the theory $\Lambda_N$ of \emph{normal fuzzy groups} (\cite{mashour1990normal}) if we add the axioms: \begin{equation*} \ex{l}{x} \vdash \ex{l}{y\cdot (x \cdot y^{-1})} \end{equation*} \end{example} \vspace{-1ex} \begin{proposition}\label{equ} The sequent $\ex{l}{x} \vdash \ex{l}{e}$ is derivable from $\Lambda_G$ and $ \ex{l}{y\cdot (x \cdot y^{-1})}\vdash \ex{l}{x}$ is derivable from $\Lambda_N$. \end{proposition} \begin{proof} The two derivations are shown in \cref{sec:der}. In the second derivation we have used the fact that $\vdash y \equiv \qty(y^{-1})^{-1}$ and $\vdash x\equiv y \cdot\qty (\qty(y^{-1} \cdot (x\cdot y)) \cdot y^{-1})$ are derivable in the theory of groups (this can be shown as in the case of ordinary group theory) and we have substituted $y^{-1}\cdot (x \cdot y)$ for $x$ in the first application of \textsc{Sub} and $y^{-1}$ for $y$ in the second one. \end{proof} \section{Fuzzy algebras and semantics}\label{sec:al} In this section we provide a sound and complete semantics to the syntax and sequents introduced in \cref{sec:the}. The first step is to define the semantic counterpart of a signature. \begin{definition} Given a signature $\Sigma$, a $\Sigma$-\emph{fuzzy algebra} $\mathcal{A}\coloneqq((A, \mu_A), \Sigma^{\mathcal{A}})$ is a fuzzy set $(A, \mu_A)$ and a collection $\Sigma^{\mathcal{A}}=\{f^{\mathcal{A}}\mid f\in O\}\sqcup \{c^{\mathcal{A}}\mid c\in C\}$ of arrows: \begin{align*} f^{\mathcal{A}}:(A,\mu_A)^{\ar(f)}\rightarrow (A, \mu_A)\qquad c^{\mathcal{A}}:(1, c_\bot)\rightarrow (A, \mu_A) \end{align*} where $c_\bot$ is the constant function in $\bot$. A \emph{morphism of $\Sigma$-fuzzy algebras} $\mathcal{A} \rightarrow \mathcal{B}$ is an arrow $g:(A, \mu_A)\rightarrow (B, \mu_B)$ such that $g\circ c^{\mathcal{A}}=c^{\mathcal{B}}$ and $f^{\mathcal{B}}\circ g^{\ar(f)}=g\circ f^{\mathcal{A}}$ for every $c\in C$ and $f\in O$. We will write $\alg{\Sigma}$ for the resulting category of $\Sigma$-fuzzy algebras. \end{definition} \begin{remark} We will not distinguish between a function from the singleton and its value. \end{remark} \begin{definition} Let $\mathcal{L}=(\Sigma, X)$ be a language and $\mathcal{A}=\qty((A, \mu_A), \Sigma^{\mathcal{A}})$ be a $\Sigma$-algebra. An \emph{assignment} is simply a function $\iota:X\rightarrow A$. We define the \emph{evaluation in $\mathcal{A}$ with respect to $\iota$} as the function $\ext{A}{\iota}{(\text{-})}:\terms{L}\rightarrow A$ by induction: \begin{itemize} \item $\ext{A}{\iota}{x}\coloneqq\iota(x)$ if $x\in X$; \item $\ext{A}{\iota}{c}\coloneqq c^{\mathcal{A}}$ if $c\in C$; \item $\ext{A}{\iota}{(f(t_1,\dots,t_{\ar(f)}))}\coloneqq f^{\mathcal{A}}(\ext{A}{\iota}{t_1}, \dots, \ext{A}{\iota}{t_{\ar(f)}})$ if $f\in O$. \end{itemize} \end{definition} \begin{proposition}\label{su} Let $\mathcal{A}$ be a $\Sigma$-algebra. Given a function $\sigma :X\rightarrow \terms{L}$ and an assignment $\iota:X \rightarrow A$ define $ \iota_\sigma:X\rightarrow A$ as the assignment sending $x$ to $ \qty(\sigma\qty(x))^{\mathcal{A}, \iota}$. Then $\mathcal{A}\vDash_\iota \phi[\sigma]$ if and only if $\mathcal{A}\vDash_{\iota_\sigma} \phi$. \end{proposition} \begin{proof} This follows at once noticing that $\big{(}t\qty[\sigma]\big{)}^{\mathcal{A}, \iota}=t^{\mathcal{A}, \iota_\sigma}$ holds for every term $t$. \end{proof} \begin{definition} $\mathcal{A}$ \emph{satisfies $\phi\in \stat{L}$ with respect to $\iota$}, and we write $\mathcal{A}\vDash_{\iota} \phi$, if $\phi$ is $\ex{l}{ t}$ and $l \leq \mu_A(\ext{A}{\iota}{t})$ or if $\phi$ is $t \equiv s$ and $ \ext{A}{\iota}{t}=\ext{A}{\iota}{s}$. $\mathcal{A}$ \emph{satisfies $\phi$} if $\mathcal{A}\vDash_{\iota} \phi $ for all $\iota:X\rightarrow A$, and we write $\mathcal{A}\vDash \phi$. Given $\Gamma\subset \stat{L}$, $\mathcal{A}\vDash \Gamma$ ($\mathcal{A}\vDash_{\iota} \Gamma$) means $\mathcal{A}\vDash \phi$ ($\mathcal{A}\vDash_{\iota} \phi$) for any $\phi \in \Gamma$. Finally, given a sequent $\Gamma \vdash \phi$ we say that $\mathcal{A}$ \emph{satisfies it with respect to $\iota$} and we will write $\Gamma\vDash_{\mathcal{A}, \iota} \phi$ if $\mathcal{A}\vDash_{\iota} \phi$ whenever $\mathcal{A}\vDash_{\iota}\Gamma$; if this happens for all assignments $\iota$ we say that $\mathcal{A}$ \emph{satisfies} the sequent and we will write $\Gamma\vDash_{\mathcal{A}} \phi$. We say that a $\Sigma$-fuzzy algebra $\mathcal{A}$ is a \emph{model} of a fuzzy theory $\Lambda\in \thr{L}$ if it satisfies all the sequents in it. We will write $\mode{\Lambda}$ for the full subcategory of $\alg{\Sigma}$ given by the models of $\Lambda$. \end{definition} Clearly $\alg{\Sigma}=\mode{\emptyset}$. For any $\Lambda\in \thr{L}$ there exist two forgetful functors $\mathscr{U}_\Lambda:\mode{\Lambda}\rightarrow \fuz{L}$ and $\mathscr{V}_\Lambda:\mode{\Lambda}\rightarrow \catname{Set}$. We will write $\mathscr{U}_\Sigma$ and $\mathscr{V}_\Sigma$ for $\mathscr{U}_\emptyset$ and $\mathscr{V}_\emptyset$. \begin{proposition}\label{left} For any signature $\Sigma$, $\mathscr{V}_\Sigma$ has a left adjoint $\trma{\Sigma}:\catname{Set}\rightarrow \mode{\Lambda}$. \end{proposition} \begin{proof}For any set $X$ take the language $\mathcal{L}_X$ and define $\trma{\Sigma}(X)$ has $(\nabla(\mathcal{L}_X\text{-}\mathbf{Terms}), \Sigma^{\trma{\Sigma}(X)})$ where $c^{\trma{\Sigma}(X)}:=c$ and \begin{align*} f^{\trma{\Sigma}(X)}: \nabla(\mathcal{L}_X\text{-}\mathbf{Terms})^{\ar(f)}\rightarrow \nabla(\mathcal{L}_X\text{-}\mathbf{Terms})\qquad \qty(t_1,\dots, t_{\ar(f)})\mapsto f(t_1,\dots, t_{\ar(f)}) \end{align*} for any $f\in O$. Now, it is immediate to see that for any $\iota:X\rightarrow \mathscr{V}_\Sigma(\mathcal{A})$ the evaluation $\ext{A}{\iota}{(\text{-})}$ is the unique morphism of $\alg{\Sigma}$ that composed with the inclusion $X\rightarrow\mathcal{L}_X\text{-}\mathbf{Terms}$ gives back $\iota.$ \end{proof} We now provide two technical results about interpretations. The first describes how interpretations are moved along morphisms of algebras. \begin{proposition}\label{ind} Let $\mathcal{L}=(\Sigma, X)$ be a language, $\Lambda \in \thr{L}$ and $\mathcal{A}=\qty(\qty(A, \mu_A), \Sigma^{\mathcal{A}}) $, $\mathcal{B}=\qty(\qty(B, \mu_B), \Sigma^{\mathcal{B}})$ be two $\Sigma$-algebras. Let also $f:\mathcal{A}\rightarrow \mathcal{B}$ be a morphism between them, then: \begin{enumerate} \item $\mathcal{A}$ is a model of $\Lambda$ if and only if it is a model of $\Lambda^{\vdash}$; \item $f\circ (-)^{\mathcal{A}, \iota}= (-)^{\mathcal{B}, f\circ \iota}$ for every assignment $\iota:X\rightarrow A$; \item for any assignment $\iota:X\rightarrow A$, $\mathcal{A}\vDash_\iota \phi$ entails $\mathcal{B}\vDash_{f\circ\iota} \phi$; \item if $\mathscr{U}_\Sigma(f)$ is a strong monomorphism in $\fuz{H}$ and $\iota:X\rightarrow A$ is an assignment then, for any formula $\phi$, $\mathcal{A}\vDash_\iota \phi$ if and only if $\mathcal{B}\vDash_{f\circ \iota} \phi$; \item if $\mathscr{U}_\Sigma(f)$ is a strong monomorphism in $\fuz{H}$ and $\mathcal{B}\in \mode{\Lambda}$ then $\mathcal{A}\in \mode{\Lambda}$. \end{enumerate} \end{proposition} \begin{proof} \begin{enumerate} \item The implication from the right to the left is obvious since $\Lambda \subseteq \Lambda^{\vdash}$. The other follows from soundness. \item This follows at once by structural induction. \item This follows from the previous point: if $\phi$ is $t\equiv s$ then \begin{align*} t^{\mathcal{B}, f\circ \iota}=f\qty(t^{\mathcal{A}, \iota})=f\qty(s^{\mathcal{A}, \iota})=s^{\mathcal{B}, f\circ \iota} \end{align*} otherwise \begin{align*} l \leq \mu_A\qty(t^{\mathcal{A}, \iota})\leq \mu_B\qty(f\qty(t^{\mathcal{A}, \iota}))= \mu_B\qty(t^{\mathcal{B}, f\circ \iota}) \end{align*} \item We have to show only the implication from the right to the left. Let us proceed by cases remembering that by \cref{mono} $\mathscr{U}_\Sigma(f)$ is a strong monomorphism if and only if it is injective and $\mu_A(a)=\mu_B(f(a))$ for any $a \in A$. \begin{itemize} \item $\phi=t\equiv s$. $\mathcal{A}\vDash_{f\circ \iota} t\equiv s$ if and only if $t^{\mathcal{A}, \iota}=s^{\mathcal{A}, \iota}$, by injectivity of $f$ this is equivalent to $f(t^{\mathcal{A, \iota}})=f(s^{\mathcal{A, \iota}})$ and by point $2$ this is equivalent to $t^{\mathcal{B},f\circ \iota}=s^{\mathcal{B},f\circ \iota}$, i.e. $\mathcal{B}\vDash_{f\circ \iota}\phi$. \item $\phi=\ex{l}{t}$. As before, $\mathcal{A}\vDash_{ \iota} \phi$ if and only if $\mu_A(t^{\mathcal{A}, \iota})\geq l$ but \begin{align*} \mu_A(t^{\mathcal{A}, \iota})= \mu_B(f(t^{\mathcal{A}, \iota})) =\mu_B(t^{\mathcal{B}, f\circ \iota}) \end{align*} and thus $\mathcal{A}\vDash_{ \iota} \phi$ is equivalent to $\mathcal{B}\vDash_{f\circ \iota} \phi$. \end{itemize} \item Let $\Gamma \vdash \phi $ be in $\Lambda$ and suppose $\mathcal{A}\vDash_\iota \Gamma$ for some assignment $\iota:X\rightarrow B$, by the previous point this implies $\mathcal{B}\vDash_{f\circ \iota }\Gamma$, so, by hypothesis $\mathcal{B}\vDash_{f\circ \iota }\phi$ and we can conclude again using point $3$.\qedhere \end{enumerate} \end{proof} We can also move interpretations and theories along morphisms of signatures. \begin{definition} For any $\mathbf{F}:\Sigma_1\rightarrow \Sigma_2$ arrow of $\catname{Sign}$ and any $\mathcal{A}=\qty(\qty(A, \mu_A), \Sigma_2^{\mathcal{A}})\in \alg{\Sigma_2}$, we define $\rs{F}(\mathcal{A})=\qty(\qty(A,\mu_A), \Sigma_1^{\rs{F}(\mathcal{A})})\in \alg{\Sigma_1}$ putting, for any $f\in O_1$ \begin{equation*} f^{\rs{F}(\mathcal{A})}:(A, \mu_A)^{\ar(f)}\rightarrow (A, \mu_A)\qquad \qty(a_1,\dots, a_{\ar(f)})\mapsto F_2(f)^{\mathcal{A}}\qty(a_1,\dots, a_{\ar(f)}) \end{equation*} and $c^{\rs{F}\qty(\mathcal{A})}:= F_3(c)^{\mathcal{A}}$ for every $c\in C_1$. \end{definition}\begin{lemma}\label{mrp} Let $\mathcal{L}_1=(\Sigma_1, X)$ and $\mathcal{L}_2=(\Sigma_2, Y)$ and $\mathbf{F}=\qty(\qty(F_1,F_2), g):\mathcal{L}_1\rightarrow \mathcal{L}_2$, then: \begin{enumerate} \item there exists a functor $\rs{F}:\alg{\Sigma_2}\rightarrow \alg{\Sigma_1}$ sending $\mathcal{A}$ to $\rs{F}(\mathcal{A})$; \item $t^{\rs{F}(\mathcal{A}), \iota \circ g}=\qty(\trms{\mathbf{F}}(t))^{\mathcal{A}, \iota}$ for any assignment $\iota:Y\rightarrow A$ and $t\in \mathcal{L}_1\text{-}\mathsf{Terms}$; \item for any assignment $\iota:Y\rightarrow A$, $\rs{F}(\mathcal{A})\vDash_{ \iota \circ g } \phi$ if and only if $\mathcal{A}\vDash_\iota \stat{\mathbf{F}}(\phi)$; \item If $X = Y$ and $g=\id{X}$ then $\rs{F}$ restricts to a functor $\res{F}{\Lambda}:\mode{\Lambda}\rightarrow \mode{\mathbf{F}^*(\Lambda)}$. \end{enumerate} \end{lemma} \begin{proof} \begin{enumerate} \item Let $h:\mathcal{A}\rightarrow \mathcal{B}$ be a morphism of $\alg{\Sigma_2}$ then $h\circ u^{\mathcal{A}}=u^{\mathcal{B}}\circ g^{\ar_2(h)}$ and $ d^{\mathcal{B}}=h\circ d^{\mathcal{A}}$ for all $u\in O_2$ and $d\in C_2$. In particular this is true when $u=F_2(f)$ and $d=F_3(c)$ for $f\in O_1$ and $c\in C_1$ but these are exactly the conditions making $h$ into an homomorphism $\rs{F}(\mathcal{A})\rightarrow \rs{F}(\mathcal{B})$. \item This follows by induction: \begin{itemize} \item for any $x\in X$ \begin{align*} x^{ \rs{F}(\mathcal{A}),\iota \circ g}=\iota(g(x))=(\trms{\mathbf{F}}(x))^{\mathcal{A}, \iota} \end{align*} and for any constant $c\in C_1$ \begin{align*} c^{ \rs{F}(\mathcal{A}),\iota \circ g}=c^{ \rs{F}(\mathcal{A})}=F_3(c)^{\mathcal{A}}=(\trms{\mathbf{F}}(c))^{\mathcal{A}}= (\trms{\mathbf{F}}(c))^{\mathcal{A},\iota} \end{align*} \item for any $f\in O_1$: \begin{align*} \qty(f\qty(t_1,\dots,t_{\ar_1(f)}))^{\mathcal{\rs{F}(A)}, \iota \circ g }&=f^{\rs{F}(\mathcal{A})}\qty(t^{\mathcal{\rs{F}(A)}, \iota \circ g }_1,\dots,t^{\mathcal{\rs{F}(A)}, \iota \circ g }_{\ar_1(f)})\\&=f^{\rs{F}(\mathcal{A})}\qty(\qty(\trms{\mathbf{F}}(t_1))^{\mathcal{A}, \iota},\dots, \qty(\trms{\mathbf{F}}(t_{\ar_1(f)}))^{\mathcal{A}, \iota})\\&=F_1(f)^{\mathcal{A}}\qty(\qty(\trms{\mathbf{F}}\qty(t_1))^{\mathcal{A}, \iota},\dots, \qty(\trms{\mathbf{F}}\qty(t_{\ar_1(f)}))^{\mathcal{A}, \iota})\\&= \qty(F_1(f)\qty(\qty(\trms{\mathbf{F}}\qty(t_1)),\dots, \qty(\trms{\mathbf{F}}\qty(t_{\ar_1(f)}))))^{\mathcal{A}, \iota}\\&=\trms{\mathbf{F}} \qty(f\qty(t_1,\dots,t_{\ar_1(f)}))^{\mathcal{A}, \iota} \end{align*} \end{itemize} \item This follows immediately by point $2$: \begin{align*} \rs{F}(\mathcal{A})\vDash_{\iota \circ g}(t\equiv s)&\iff t^{\rs{F}(\mathcal{A}), \iota \circ g }= s^{\rs{F}(\mathcal{A}), \iota \circ g}\\&\iff \qty(\trms{\mathbf{F}}\qty(t))^{\mathcal{A},\iota }=\qty(\trms{\mathbf{F}}\qty(s))^{\mathcal{A}, \iota}\\&\iff \mathcal{A}\vDash_\iota \stat{\mathbf{F}}(t\equiv s)\\\hspace{1pt}\\ \rs{F}(\mathcal{A})\vDash_{\iota \circ g }\ex{l}{t}&\iff l\leq \mu_A\qty(t^{\rs{F}(\mathcal{A}), \iota \circ g})\\&\iff l \leq \mu_A\qty(\trms{\mathbf{F}}\qty(t))^{\mathcal{A}, \iota}\\&\iff \mathcal{A}\vDash_\iota \stat{\mathbf{F}}\qty(\ex{l}{t}) \end{align*} \item Let $\Gamma \vdash \psi$ be in $\mathbf{F}^*(\Lambda)$, by the previous point, for any assignment $\iota:X\rightarrow A$ \begin{equation*} \rs{F}(\mathcal{A})\vDash_{ \iota\circ g} \Gamma\iff \mathcal{A}\vDash_\iota \qty{\stat{\mathbf{F}}(\phi)}_{\phi \in \Gamma} \end{equation*} Since $\qty{\stat{\mathbf{F}}(\phi)}_{\phi \in \Gamma}\vdash \stat{\mathbf{F}}(\psi)$ is in $\Lambda$ we have $\mathcal{A}\vDash_\iota \stat{\mathbf{F}}\qty(\psi)$ but, using again point $3$, this implies $ \rs{F}(\mathcal{A})\vDash_\iota \phi$. \qedhere \end{enumerate} \end{proof} \begin{example}\label{ex:semig2} The models for $\Lambda_S$, $\Lambda_ {LI}$, $\Lambda_{RI}$ and $\Lambda_I$ (\cref{ex:semig1}) are precisely the structures defined in \cite{mordeson2012fuzzy}, while the models for $\Lambda_G$ (\cref{ex:fuzzyg1}) are precisely the fuzzy groups as in \cite{rosenfeld1971fuzzy} and those of $\Lambda_N$ are the structures called \emph{normal fuzzy subgroups} in \cite{ajmal1992fuzzy, ajmal1994homomorphism, mashour1990normal}. \end{example} \subparagraph{Soundness} Now we can proceed proving the soundness of the rules in \cref{fig:scrules}. \begin{lemma}\label{rules} Let $\mathcal{L}=(\Sigma, X)$ be a language and $\mathcal{A} =((A, \mu_A), \Sigma^{\mathcal{A}})$ a $\Sigma$-algebra, then: \begin{enumerate} \item for any assignment $\iota:X\rightarrow A$ and rule \vspace{-1ex} \begin{equation*} \inferrule*[right=R]{\qty{\Psi_i \vdash \xi_i}_{i\in I}}{\Psi \vdash \xi} \end{equation*} different from \textsc{Sub}, if $\Psi_i\vDash_{\mathcal{A}, \iota} \xi_i$ for all $i\in I$ then $\Psi \vDash_{\mathcal{A}, \iota} \xi $ too; \item for any $\sigma:X\rightarrow \terms{L}$, if $\Gamma\vDash_{\mathcal{A}}\psi$ then $\Gamma[\sigma]\vDash_{\mathcal{A}}\psi[\sigma]$. \end{enumerate} \end{lemma} \begin{proof} \begin{enumerate} \item The thesis is vacuous for rule A and it is trivial for \textsc{Refl}, \textsc{Sym} and \textsc{Trans}. For rule \textsc{Weak} if $\mathcal{A}\vDash_{\iota}\Gamma\cup \Delta$ then $\mathcal{A}\vDash_{\iota}\Gamma$ and so, since $\Gamma \vDash_{\mathcal{A}, \iota}\phi$ this implies $\mathcal{A}\vDash_{\iota} \phi$. The thesis for \textsc{Inf} it follows from the fact that $\bot$ is the bottom element, for \textsc{Cong} and \textsc{Fun} it follows since $\mu_A$ and $f^{\mathcal{A}}\in \Sigma^{\mathcal{A}}$ are functions for any $f\in O$. We're left with four rules. \begin{itemize}\item[] \textsc{Cut}. For any assignment $\iota$, if $\mathcal{A}\vDash_\iota \Gamma $ then, since $\Gamma \vDash_{\mathcal{A}, \iota} \phi_i$ for any $i\in I$ we have $\mathcal{A}\vDash_\iota \qty{\phi_i}_{i\in I} $, but $\qty{\phi_i}_{i\in I}\vDash_{\mathcal{A}, \iota} \psi$ and this implies $\mathcal{A}\vDash_\iota \psi$. \item[]\textsc{Sup}. Let $\iota:X\rightarrow A$ be such that $\mathcal{A}\vDash_{\iota}\Gamma$, then $\Gamma\vDash_{\mathcal{A}, \iota}\ex{l}{t}$ for all $l\in \mathcal{L}$ implies that $\mu_A(t^{\mathcal{A}, \iota})$ is an upper bound of $\mathcal{L}$, so the thesis follows. \item[]\textsc{Mon}. As before let $\iota$ be an assignment for which $\mathcal{A}$ satisfies all the formulae in $\Gamma$, then, since $\Gamma\vDash_{\mathcal{A}, \iota} \ex{l}{t}$ we have that $l\leq \mu_A(t^{\mathcal{A}, \iota})$, so, for any $l'\in H$, $l'\wedge l\leq \mu_A(t^{\mathcal{A}, \iota})$ holds too. \item[]\textsc{Exp}. For any $\iota$ such that $ \mathcal{A} \vDash_{ \iota}\Gamma$, $\Gamma\vDash_{\mathcal{A}, \iota}\ex{l_i}{t_i}$ entails $l_i\leq \mu_A(t^{\mathcal{A}, \iota}_i)$ for any $1\leq i\leq \ar(f)$, therefore: \begin{align*} \bigwedge_{i=1}^{\ar(f)} l_i &\leq \bigwedge_{i=1}^{\ar(f)}\mu_A(t^{\mathcal{A}, \iota}_i)= \mu_{A^n}(t^{\mathcal{A}, \iota}_1,\dots,t^{\mathcal{A}, \iota}_{\ar(f)})\leq \mu_A(f^{\mathcal{A}}(t^{\mathcal{A}, \iota}_1,\dots,t^{\mathcal{A}, \iota}_{\ar(f)})) \end{align*} and we are done. \end{itemize} \item Let $\iota:X \rightarrow A$ an assignment such that $\mathcal{A}\vDash_{\iota}\phi_i[\sigma]$ for any $\phi_i\in \Gamma$. By \cref{su} this means that $\mathcal{A}\vDash_{\iota_\sigma}\Gamma$ and so, by hypothesis, $\mathcal{A}\vDash_{\iota_\sigma}\psi$ which, again by \cref{su}, entails $\mathcal{A}\vDash_{\iota}\psi[\sigma]$. \qedhere \end{enumerate} \end{proof} \begin{corollary}[Soundness]\label{sound} If a $\Sigma$-algebra satisfies all the premises of a rule of the fuzzy sequent calculus then it satisfies also its conclusion. \end{corollary} \begin{remark}\label{rem:nodeduclemma} Let us see why the deduction lemma (\cref{ext}) cannot be extended to rule \textsc{Sub}. Take $\Sigma$ to be the empty set, $X=\{x,y, z\}$ and $H=\{0,1\}$. Notice that $\alg{\Sigma}=\fuz{H}$. We have the derivation \vspace{-1ex} \begin{equation*} \inferrule*[Right=Sub]{\vdash x\equiv y}{\vdash x\equiv z} \end{equation*} If the deduction lemma held for \textsc{Sub}, $x\equiv y\vdash x\equiv z$ would be in $\emptyset^{\vdash}$, hence satisfied by any fuzzy set, but $(H, \id{H})$ with $\iota: X\rightarrow H$ sending $x$ and $y$ to $0$ and $z$ to $1$ is a counterexample. \end{remark} \begin{remark} Let us take $\Sigma=\emptyset$ and $H=\{0,1\}$ and $X=\{x,y,z\}$ and the derivation as in \cref{rem:nodeduclemma}. Now, a fuzzy set $(A, \mu_A)$ satisfies $\vdash_{\iota} x\equiv y$ if and only if $\iota(x)=\iota(y)$, thus, if we take $(H, \id{H})$ and the assignment $\iota$ of the previous example, then $(H,\id{H})\vdash_{\iota} x\equiv y$ but it does not satisfy $ x\equiv z$ with respect to $\iota$. \end{remark} \subparagraph{Completeness} Now we prove that the calculus we have provided in \cref{sec:the} is complete. Let us start with the following observation. \begin{remark}\label{rel} For any $\Lambda\in \thr{L}$ the relation $\sim_{\Lambda}$ given by all $t$ and $s$ such that $ \vdash_{\Lambda} t \equiv s$, is an equivalence relation on $\terms{L}$. \end{remark} Using this equivalence, we can define the model of terms, as done next. \begin{definition} Let $\mathcal{L}=(\Sigma, X)$ be a language and $\Lambda\in\thr{L}$, we define $\trms{\Lambda}$ to be the quotient of $\terms{L}$ by $\sim_{\Lambda}$, moreover, by rule \textsc{Fun}, the function \begin{align*} \hat{\mu}:\terms{L}\rightarrow H\qquad t \mapsto \sup\qty{l\in H \mid \hspace{2pt} \vdash_\Lambda \ex{l}{t}} \end{align*} induces a function $\mu_\Lambda:\trms{\Lambda}\rightarrow H$. For any $f\in O$ and $c\in C$ putting $c^{\mathcal{T}_{\Lambda}}\coloneqq[c]$ and \begin{align*} f^{\mathcal{T}_{\Lambda}}:\trms{\Lambda}^{\ar(f)} \rightarrow \trms{\Lambda}\qquad \qty([t_1],\dots, [t_{\ar(f)}])\mapsto \qty[f\qty(t_1,\dots, t_{\ar(f)})] \end{align*} gives us a $\Sigma$-algebra $\mathcal{T}_\Lambda=\qty(\qty(\trms{\Lambda}, \mu_\Lambda), \Sigma^{\mathcal{T}_{\Lambda}})$, called \emph{ the $\Sigma$-algebra of terms in $\Lambda$}. The \emph{canonical assignment} is the function $\iota_{can}:X\rightarrow \trms{\Lambda}$ sending $x$ to its class $[x]$. \end{definition} \begin{remark} Rule \textsc{Cong} assures us that $f^{\mathcal{T}_{\Lambda}}$ is well defined while \textsc{Exp} implies that it is an arrow of $\fuz{H}$. \end{remark} \begin{lemma}\label{trms}Let $\mathcal{L}=(\Sigma, X)$ be a language and $\Lambda \in \thr{L}$, then: \begin{enumerate} \item for any $\phi\in \stat{L}$ the following are equivalent: \begin{enumerate} \item $\mathcal{T}_{\Lambda}\vDash \phi$, \item $\mathcal{T}_{\Lambda}\vDash_{\iota_{can}}\phi$, \item $ \vdash_{\Lambda} \phi$; \end{enumerate} \item for any assignment $\iota:X \rightarrow \trms{\Lambda}$ and formula $\phi$, $\mathscr{T}_\Lambda \vDash_\iota \phi$ if and only if $ \vdash_\Lambda \phi[\sigma \circ \iota]$ for one (and thus any) section $\sigma$ of the quotient $\terms{L}\rightarrow \trms{\Lambda}$; \item $\mathcal{T}_\Lambda=\qty(\qty(\trms{\Lambda}, \mu_\Lambda), \Sigma^{\mathcal{T}_\Lambda})$ is a model of $\Lambda$. \end{enumerate} \end{lemma} \begin{proof} Let us start with a technical result. \begin{proposition}\label{ass} Let $\mathcal{L}=(\Sigma, X)$ be a language, $\Lambda \in \thr{L}$, and $\sigma:\trms{\Lambda}\rightarrow \terms{L}$ a section of the quotient $\terms{L}\rightarrow \trms{\Lambda}$. The equation $t^{\mathcal{T}_{\Lambda}, \iota}=\qty[t\qty[\sigma \circ \iota ]]$ holds for any assignment $\iota:X\rightarrow \trms{\Lambda}$ and $t\in \terms{L}$. In particular $t^{\mathcal{T}_{\Lambda}, \iota_{can}}=[t]$. \end{proposition} \begin{proof} For constants it is obvious, let us proceed by induction. \begin{itemize} \item For any $x\in X$, $\sigma\qty(\iota(x))$ is a representative of $\iota(x)$, so: \begin{align*} x^{\mathcal{T}_{\Lambda}, \iota}=\iota(x)=\qty[\sigma(\iota(x))]=\qty[\sigma\qty(\iota\qty(x))/x]=\qty[x\qty[\sigma\circ \iota]] \end{align*} \item For any $f\in O$ and $t_1,\dots,t_{\ar(f)}\in \terms{L}$: \begin{align*} &\qty(f\qty(t_1,\dots,t_{\ar(f)}))^{\mathcal{T}_\Lambda, \iota}=f^{\mathcal{T}_\Lambda}\qty(t^{\mathcal{T}_\Lambda,\iota}_1,\dots,t^{\mathcal{T}_\Lambda,\iota}_{\ar(f)})=f^{\mathcal{T}_\Lambda}\qty(t^{\mathcal{T}_\Lambda,\iota}_1,\dots,t^{\mathcal{T}_\Lambda,\iota}_{\ar(f)})\\&=f^{\mathcal{T}_\Lambda}\qty(\big{[}t_1\qty[\sigma\circ \iota]\big{]},\dots,\qty[t_{\ar(f)}\qty[\sigma\circ \iota]])= \qty[f\qty(t_1[\sigma\circ \iota],\dots,t_{\ar(f)}[\sigma\circ \iota])]\\&= \qty[\qty(f\qty(t_1,\dots,t_{\ar(f)}))[\sigma \circ \iota]] \qedhere \end{align*} \end{itemize} \end{proof} Now we can proceed with the proof of \cref{trms}. \begin{enumerate} \item Let us show the three implications. \begin{enumerate} \item[](a)$\Rightarrow$(b). By definition. \item[](b)$\Rightarrow$(c). We split the cases. \begin{itemize} \item $\phi$ is $t\equiv s$. Then $\mathcal{T}_\Lambda\vDash_{\iota_{can}} \phi$ means \begin{align*} [t]=t^{\mathscr{T}_\Lambda, \iota_{can}}=s^{\mathscr{T}_\Lambda, \iota_{can}}=[s] \end{align*} thus $t\sim_{\Lambda}s$ i.e. $ \vdash_\Lambda t\equiv s$. \item $\phi$ is $\ex{l}{t}$. Let $S$ be $ \qty{l'\in H \mid \Lambda \vdash \ex{l'}{t}}$, by hypothesis $\mathcal{T}_\Lambda\vDash_{\iota_{can}} \phi$, so \begin{align*} l\leq \mu_\Lambda\qty(t^{\mathscr{T}_\Lambda, \iota_{can}})= \mu_\Lambda\qty([t])=\sup(S) \end{align*} hence $l=l\wedge \sup(S)$ and, since $H$ is a frame, it follows that $l= \sup \qty(\qty{l\wedge l'\mid l'\in S })$, by rule \textsc{Mon} we know that that $\vdash_\Lambda \ex{l\wedge l'}{t}$ for all $l'\in S$ and so rule \textsc{Sup} gives us $ \vdash_\Lambda \ex{l}{t}$. \end{itemize} \item[](c)$\Rightarrow$(a). Let $\iota:X \rightarrow \trms{\Lambda}$ be an assignment and $\sigma$ a section as in the hypothesis, then we can apply \textsc{Sub} to get $\vdash_\Lambda \phi[\sigma\circ \iota]$, by \cref{ass} we get the thesis. \end{enumerate} \item By \cref{ass} we have \begin{align*} t^{\mathscr{T}_\Lambda, \iota}=[t[\sigma\circ \iota]]=\qty(t[\sigma\circ \iota])^{\mathscr{T}_\Lambda, \iota_{can}} \end{align*} we can conclude using the previous point. \item Let $\Gamma\vdash \psi$ be a sequent in $\Lambda$ with $\Gamma=\qty{\phi_i}_{i=1}^n$ and $\iota:X\rightarrow \trms{\Lambda}$ an assignment such that $\mathcal{T}_{\Lambda}\vDash_\iota \Gamma$. By point $1$ above this means that $\vdash_\Lambda \Gamma[\sigma \circ \iota]$ and applying \textsc{Sub} and \textsc{Cut} we can conclude that $\vdash_\Lambda \psi[\sigma \circ\iota]$. By the previous point this is equivalent to $\mathscr{T}_\Lambda\vDash_{\iota} \psi$.\qedhere \end{enumerate} \end{proof} \begin{corollary}[Completeness for formulae] For any theory $\Lambda \in \thr{L}$, $\mathcal{A}\vDash \phi$ for all $\mathcal{A}\in \mode{\Lambda}$ if and only if $\vdash_{\Lambda}\phi$. \end{corollary} \section{From theories to monads}\label{sec:fre} Given a language $\mathcal{L}= \qty(\Sigma, X)$ and a fuzzy theory $\Lambda\in \thr{L}$ we have a forgetful functor: $\mathscr{U}_{\Lambda}:\mode{\Lambda}\rightarrow \fuz{L}$. In this section we first show that it has a left adjoint (\cref{sec:ffafs}) and that for a specific class of theories, models correspond to Eilenberg-Moore algebras for the monad induced by this adjunction (\cref{sec:emalg}). \subsection{The free fuzzy algebra on a fuzzy set}\label{sec:ffafs} To give the definition of free models (\cref{def:freemodel}) we need some preliminary constructions. \begin{definition} Let $\mathcal{A}$ be a $\Sigma$-algebra and $f:(B,\mu_B)\rightarrow \mathscr{U}_\Sigma(\mathcal{A})$ an arrow in $\fuz{H}$, a $\Sigma$-algebra \emph{generated by $f$ in $\mathcal{A}$} is a morphism $\epsilon:\gen{B}{f}{A}\rightarrow \mathcal{A}$ such that: \begin{itemize} \item $\mathscr{U}_\Sigma(\epsilon)$ is strong mono; \item there exists $\bar{f}:(B,\mu_B)\rightarrow \gen{B}{f}{A}$ such that $\mathscr{U}_\Sigma(\epsilon) \circ \bar{f}=f$; \item if $g:\mathcal{C}\rightarrow \mathcal{A}$ is a morphism such that $\mathscr{U}_\Sigma(g)$ is strong monomorphism and $\mathscr{U}_\Sigma(g)\circ h=f$ for some $h$ then there exists a unique $k:\gen{B}{f}{A}\rightarrow \mathcal{C}$ such that $g\circ k=\epsilon$. \end{itemize} \iffalse \begin{center} \begin{tikzpicture} \node(A)at(0,0){$\mathscr{U}_\Sigma(\mathcal{A})$}; \node(B)at(-2.5,1.5){$\gen{B}{f}{A}$}; \node(C)at(-5,0){$(B,\mu_B)$}; \node(D)at(0,3){$\mathscr{U}_\Sigma(\mathcal{C})$}; \draw[->](C)--(A)node[pos=0.5,below]{$f$}; \draw[->](D)--(A)node[pos=0.5,right]{$\mathscr{U}_\Sigma(g)$}; \draw[->](C)..controls(-5,2.5)and(-3,3)..(D)node[pos=0.5,above]{$h$}; \draw[->](C)--(B)node[pos=0.5,above, xshift=-0.1cm, yshift=-0.1cm]{$\bar{f}$}; \draw[->](B)--(A)node[pos=0.5,above, xshift=0.3cm, yshift=-0.1cm]{$\mathscr{U}_\Sigma(\epsilon)$}; \draw[dashed, ->](B)--(D)node[pos=0.5,left, xshift=-0.1cm, yshift=0.1cm]{$\mathscr{U}_\Sigma(k)$}; \end{tikzpicture} \end{center} \fi \end{definition} \begin{proposition}\label{con} For any signature $\Sigma$, $\Sigma$-algebra $\mathcal{A}$ and $f:(B, \mu_B)\rightarrow \mathscr{U}_\Sigma(\mathcal{A})$, $\gen{B}{f}{A}$ exists and it is unique up to isomorphism. \end{proposition} \begin{proof} This is straightforward: if $\mathcal{A}=((A, \mu_A), \Sigma^{\mathcal{A}})$ it is enough to consider as carrier set $\mathscr{U}_\Sigma(\gen{B}{f}{A})$ the smallest subset of $A$ such that: \begin{itemize} \item $f(B)\subset \mathscr{U}_\Sigma(\gen{B}{f}{A})$; \item $\qty{c^{\mathcal{A}}}_{c\in C} \subset \mathscr{U}_\Sigma(\gen{B}{f}{A})$; \item if $g\in O$ and $b_1,\dots, b_{\ar(g)}\in \mathscr{U}(\gen{B}{f}{A})$ then $g^{\mathcal{A}}(b_1,\dots,b_{\ar(g)})\in\mathscr{U}_\Sigma(\gen{B}{f}{A})$. \end{itemize} with the restriction of $\mu_A$ as membership degree function. As $\Sigma$-algebra structure we can take the restriction of $\Sigma^{\mathcal{A}}$. By \cref{mono} the inclusion $i$ is a strong monomorphism and by construction an arrow of $\alg{\Sigma}$. Let $g:\mathcal{C}\rightarrow \mathcal{A}$ and $h$ be as in the definition, if we consider the inclusion $i:(f(B), {\mu_A}_{|f(B)})\rightarrow (A,\mu_A)$, by the left lifting property we obtain \begin{center} \begin{tikzpicture} \node(A)at(0,0){$(B, \mu_B)$}; \node(B)at(0,-1.5){$(f(B), {\mu_A}_{|f(B)})$}; \node(C)at(3,-1.5){$(A,\mu_A)$}; \node(D)at(3,0){$\mathscr{U}_\Sigma(\mathcal{C})$}; \draw[->](A)--(B)node[pos=0.5, left]{$\bar{f}$}; \draw[->](B)--(C)node[pos=0.5, below]{$i$}; \draw[->](A)--(D)node[pos=0.5, above]{$h$}; \draw[->](B)--(D)node[pos=0.5, above, xshift=0cm, yshift=0cm]{$\bar{k}$}; \draw[<-](C)--(D)node[pos=0.5, right]{$\mathscr{U}_\Sigma(g)$}; \end{tikzpicture} \end{center} and we can define $k$ by induction as: \begin{itemize} \item $k(b)=\bar{k}(b)$ if $b\in f(B)$; \item $k(c^{\mathcal{A}})=c^{\mathcal{C}}$ if $c\in C$; \item $k(t^{\mathcal{A}}(b_1,\dots,b_{\ar(g)}))=t^{\mathcal{C}}(k(b_1),\dots,k(b_{\ar(t)}))$ if $t\in O$ and $b_1,\dots,b_{\ar(t)}\in \gen{B}{f}{A}$. \end{itemize} Notice that injectivity of $g$ implies that $k$ is actually well-defined, in fact, proceeding by induction: \begin{itemize} \item if $x\in B$ is such that $f(x)=c^\mathcal{A}$ for some $c\in C$ then \begin{align*} g(h(x))=\epsilon(\bar{f}(x))=c^{\mathcal{A}}=g(c^\mathcal{C}) \end{align*} so \begin{align*} k(f(x))=h(x)=c^{\mathcal{C}}=k(c^{\mathcal{A}}) \end{align*} \item if $x\in B$ is such that $f(x)=t^{\mathcal{A}}(b_1,\dots, b_{\ar(t)})$ for some $t\in O$ and $b_1,\dots,b_{\ar(t)}\in \gen{B}{f}{A}$ then \begin{align*} g(h(x))&=\epsilon(\bar{f}(x))=t^{\mathcal{A}}(b_1, \dots, b_{\ar(t)})\\ &=t^{\mathcal{A}}(g(k(b_1)), \dots, g(k(b_{\ar(t)})))= g(t^{\mathcal{C}}(b_1,\dots, b_{\ar(t)})) \end{align*} so $h(x)=t^{\mathcal{C}}(b_1,\dots, b_{\ar(t)})$ and we are done; \item if $c\in C$ is such that $c^{\mathcal{A}}=t^{\mathcal{A}}(b_1,\dots, b_{\ar(t)})$ for some $t\in O$ and $b_1,\dots,b_{\ar(t)}\in \gen{B}{f}{A}$ then \begin{align*} g(c^{\mathcal{C}})&=c^{\mathcal{A}}=t^{\mathcal{A}}(b_1, \dots, b_{\ar(t)})=t^{\mathcal{A}}(g(k(b_1)), \dots, g(k(b_{\ar(t)})))= g(t^{\mathcal{C}}(b_1,\dots, b_{\ar(t)})) \end{align*} so $c^{\mathcal{C}}=t^{\mathcal{C}}(b_1,\dots, b_{\ar(t)})$ and we are done again; \item if $s^{\mathcal{A}}(b'_1,\dots, b'_{\ar(s)})=t^{\mathcal{A}}(b_1,\dots, b_{\ar(t)})$ for some $t, s\in O$ and $b'_1,\dots,b'_{\ar(s)}, b_1,\dots,b_{\ar(t)}, \in \gen{B}{f}{A}$ then \begin{align*} g(s^{\mathcal{C}}(k(b'_1),\dots, k(b'_{\ar(s)}))&=s^{\mathcal{A}}(b'_1,\dots, b'_{\ar(s)})=t^{\mathcal{A}}(b_1, \dots, b_{\ar(t)})\\ &=t^{\mathcal{A}}(g(k(b_1)), \dots, g(k(b_{\ar(t)})))= g(t^{\mathcal{C}}(b_1,\dots, b_{\ar(t)})) \end{align*} so $s^{\mathcal{C}}(k(b'_1),\dots, k(b'_{\ar(s)}))=t^{\mathcal{C}}(b_1,\dots, b_{\ar(t)})$ and even in this case $k$ is well defined. \end{itemize} Moreover, for any $t\in \gen{B}{f}{A}$, if $\mathscr{U}(\mathcal{C})=(D, \mu_D)$ then \begin{align*} \mu_{D}(k(t))=\mu_A(g(k(t)))=\mu_A(i(t)) \end{align*} Uniqueness follows at once by induction. \end{proof} \begin{remark}\label{sub2} \cref{ind} implies that, given a model $\mathcal{A}=\qty(\qty(A, \mu_A), \Sigma^{\mathcal{A}})$ of a theory $\Lambda\in \thr{L}$, and a morphism $f:(B, \mu_B)\rightarrow (A, \mu_A)$, the $\Sigma$-algebra $\gen{B}{f}{A}$ is in $\mode{\Lambda}$. \end{remark} \begin{proposition}\label{uni} Let $\mathcal{A}$ be a $\Sigma$-algebra and $f:(B, \mu_B)\rightarrow \mathscr{U}_\Sigma(\mathcal{A})$, then, for any other $\Sigma$-algebra $\mathcal{C}$ and $h:(B, \mu_B)\rightarrow \mathscr{U}_\Sigma(\mathcal{C})$ there exists at most one $k:\gen{B}{f}{A}\rightarrow \mathcal{C}$ such that $k\circ \bar{f}=h$. \end{proposition} \begin{proof} Let $k$ and $k'$ as in the thesis, we can proceed by induction: \begin{itemize} \item $k(f(x))=k'(f(x))$ for any $x\in B$ by hypothesis; \item $k\qty(c^{\gen{B}{f}{A}})=k'\qty(\gen{B}{f}{A})$ since $k$ and $k'$ are morphism of $\alg{\Sigma}$; \item $k\qty(g^{\gen{B}{f}{A}}\qty(b_1,\dots,b_{\ar(g)}))=g^{\mathcal{C}}\qty(k\qty(b_1),\dots,k(b_{\ar(g)}))$, by inductive hypothesis this is equal to $g^{\mathcal{C}}(k'(b_1),\dots,k'(b_{\ar(g)}))$ and we conclude using again the fact that $k'$ is an arrow of $\alg{\Sigma}$.\qedhere \end{itemize} \end{proof} The next definition explains how to extend a theory in a given language with the data of a fuzzy set. \begin{definition} Let $(M, \mu_M)$ be a fuzzy set, $\mathcal{L}=(\Sigma, X)$ a language with $\Sigma = (O, \ar, C)$. We define $\Sigma[M, \mu_M]$ to be $\qty( O, \ar, C\sqcup M)$ and $\mathcal{L}_{(M,\mu_M)}$ to be $\qty(\Sigma[M, \mu_M], X)$. We have an obvious morphism $\mathbf{I}:\mathcal{L}\rightarrow \mathcal{L}_{(M,\mu_M)}$ given by the identities and the inclusion $i_C:C\rightarrow C\sqcup M$. For any $\Lambda \in \thr{L}$ we define $\Lambda[M, \mu_M]\in \mathcal{L}_{(M,\mu_M)}$ as $\mathbf{I}_*\qty(\Lambda)\cup \overline{\qty(M, \mu_M)}$ where $\overline{\qty(M, \mu_M)}=\qty{\vdash \ex{l}{m} \mid m \in M, l\in L \text{ and } \mu_M(m)\geq l}$. \end{definition} \begin{remark} It is immediate to see that $\mathbf{I^*}\qty(\Lambda[M,\mu_M])=\Lambda$. \end{remark} In the next proposition we show that, for any theory $\Lambda$, a fuzzy set can be mapped into the term model of the theory $\Lambda$ extended with it. Hence, the natural candidate to be the free model is the algebra generated by such map. \begin{proposition}\label{init} For any fuzzy set $(M,\mu_M)$ and any theory $\Lambda \in \thr{L}$: \begin{enumerate} \item the function $\bar{\eta}_{(M,\mu_M)}$ sending $m$ to the class $[m]$ of the corresponding constant defines an arrow of fuzzy sets $\bar{\eta}_{(M,\mu_M)}:(M,\mu_M)\rightarrow \trms{\Lambda\qty[M,\mu_M]}$; \item any element in $\langle M,\mu_M \rangle_{\mathcal{T}_{\Lambda\qty[M,\mu_M]}, \bar{\eta}_{(M,\mu_M)}}$ has a representative without variables; \item $\langle M,\mu_M \rangle_{\mathcal{T}_{\Lambda\qty[M,\mu_M]}, \bar{\eta}_{\qty(M,\mu_M)}}$ is the initial object of $\mode{\Lambda[M, \mu_M]}$; \end{enumerate} \end{proposition} \begin{proof} \begin{enumerate} \item The only thing to do is to show that $\mu_M(m)\leq \mu_{{\Lambda[M,\mu_M]}}\qty([m])$ but we are easily done since $\vdash \ex{\mu_M}{m}\in \Lambda\qty[M, \mu_M]$. \item This follows by the explicit construction given in \cref{con}. \item $\langle M,\mu_M \rangle_{\mathcal{T}_{\Lambda\qty[M,\mu_M]}, \bar{\eta}_{\qty(M,\mu_M)}}$ is in $\mode{\Lambda[M, \mu_M]}$ by \cref{sub2}. For every model $\mathcal{A}$ of $\Lambda[M, \mu_M]$, mapping $m\in M$ to $m^{\mathcal{A}}$ provides a morphism of fuzzy sets $(M,\mu_M)\rightarrow \mathscr{U}_{\Sigma[M,\mu_M]}(\mathcal{A})$. By \cref{uni} there exists at most one morphism of $\Sigma[M,\mu_M]$-algebras from $\langle M,\mu_M \rangle_{\mathcal{T}_{\Lambda\qty[M,\mu_M]}, \bar{\eta}_{\qty(M,\mu_M)}}$ to $\mathcal{A}$. On the other hand, by point 2 for every $[t]\in \langle M,\mu_M \rangle_{\mathcal{T}_{\Lambda\qty[M,\mu_M]}, \bar{\eta}_{(M,\mu_M)}}$ there exists a term $s$ with no variables such that $\Lambda[M, \mu_M]\vdash t\equiv s$, therefore $t^{\mathcal{A}, \iota}=t^{\mathcal{A}, \iota'}$ for any two assignments $\iota, \iota':X\rightarrow A$. Hence we get a morphism of $\Sigma[M,\mu_M]$-algebras sending the class $[t]$ of a term $t$ to its interpretation $t^{\mathcal{A}, \iota}$ for any chosen assignment $\iota$.\qedhere \end{enumerate} \end{proof} \begin{definition}\label{def:freemodel} For any language $\mathcal{L}$, $\Lambda\in \thr{L}$ and $(M,\mu_M)\in \fuz{H}$ we define the \emph{free model $\mathcal{F}_\Lambda\qty(M,\mu_M)$ of $\Lambda$ generated by $\qty(M,\mu_M)$} to be $\res{I}{\Lambda\qty[M,\mu_M]}\qty(\langle M,\mu_M \rangle_{\mathcal{T}_{\Lambda\qty[M,\mu_M]},\bar{\eta}_{\qty(M,\mu_M)}})$. We set $\term{\Lambda}\qty(M,\mu_M)$ to be $\mathscr{U}_{\Lambda}\qty(\mathcal{F}_\Lambda(M,\mu_M))$. \end{definition} Now it is enough to check that the free model just defined actually provides the left adjoint.% \begin{theorem}\label{free} For any language $\mathcal{L}$ and $\Lambda\in \thr{L}$ the functor $\mathscr{U}_\Lambda:\mode{\Lambda}\rightarrow \fuz{L}$ has a left adjoint $\mathscr{F}_{\Lambda}$. \end{theorem} \begin{proof} By construction $\bar{\eta}_{(M,\mu_M)}$ factors through $ \eta_{(M,\mu_M)}:(M,\mu_M)\rightarrow \term{\Lambda}(M,\mu_M)$ which sends $m$ to $[m]$. Let now $g:(M,\mu_M)\rightarrow \mathscr{U}_\Lambda(\mathcal{B})$ be another arrow in $\fuz{H}$, we can turn $\mathcal{B}$ into a $\Sigma[M,\mu_M]$-algebra $\mathcal{B}^g$ setting $m^{\mathcal{B}^g}$ to be $g(m)$ for any $m\in M$. Let us show that $\mathcal{B}^g$ is a model of $\Lambda[M, \mu_M]$. Surely it is a model of $\Lambda$ since $\mathcal{B}$ is, let $\vdash \ex{l}{m}$ be a sequent in $\overline{(M, \mu_M)}$, then for any assignment $\iota:V\rightarrow B$: \begin{align*} \mathcal{B}^g \vDash_\iota \ex{l}{m} &\iff l\leq \mu_{B}(m^{\mathcal{B}^g, \iota})l\leq \mu_{\Lambda}\qty( t^{\mathscr{F}_{\Lambda}(M, \mu_M), \eta_{(M,\mu_M)}\circ \iota})\iff l\leq \mu_B(g(m)) \end{align*} but $g$ is an arrow of $\fuz{H}$ so $\mu_B(g(m))\geq \mu_M(m)$ and we are done. Now, since $\mathcal{B}^{g}$ is a model of $\Lambda[M, \mu_M]$, we can take $\bar{g}$ to be the image through $\res{\mathbf{I}}{\Lambda[M, \mu_M]}$ of the unique arrow $\langle M,\mu_M \rangle_{\mathcal{T}_{\Lambda[(M,\mu_M)]}, \bar{\eta}_{(M,\mu_M)}} \rightarrow \mathcal{B}^{g}$, by construction \begin{align*} \bar{g}(\eta_{(M,\mu_M)}(m))=\bar{g}([m])=m^{\mathcal{B}^g}=g(m) \end{align*} so $\mathscr{U}_\Lambda(\bar{g})\circ \eta_{(M,\mu_M)}=g$. Uniqueness follows from \cref{init}. \end{proof} \begin{definition} Given a theory $\Lambda\in \thr{L}$, its \emph{associated monad} $\term{\Lambda}:\fuz{H}\rightarrow \fuz{H}$ is the composite $\mathscr{U}_\Lambda\circ \mathscr{F}_\Lambda$. \end{definition} \begin{remark} If $\Lambda$ is the empty theory (in any language), then, by \cref{left}, the composittion $\mathscr{F}_\emptyset\circ \nabla$ gives us a functor isomorphic to $\trma{\Sigma}$. \end{remark} \begin{notazione} We will denote by $\trm{\emptyset}$ with $\trm{\Sigma}$ and with $\term{\Sigma}$ the monad $\term{\emptyset}=\mathscr{U}_\Sigma\circ \trm{\Sigma}$. \end{notazione} In this setting we can provide a result similar to \cref{trms}. \begin{lemma}\label{trms2} For any language $\mathcal{L}=(\Sigma, X)$ we define the \emph{natural assignment} $\iota_{nat}$ as the adjoint to the unit $\nabla(X)\rightarrow \term{\Lambda}(\nabla(X))$. Then $\trm{\Lambda}(\nabla(X))\vDash_{\iota_{nat}}\phi$ if and only if $\vdash_\Lambda \phi $. \end{lemma} \begin{proof} The implication from the right to the left follows immediately since $\trm{\Lambda}(\nabla(X))$ is a model for $\Lambda$. By adjointness he canonical assignment $\iota_{can}$ induces an arrow $\nabla(X)\rightarrow \mathcal{U}_{\Lambda[\nabla(X)]}\qty( \mathcal{T}_{\Lambda[\nabla(X)]})$, which, in turn, induces a morphism $e:\trm{\Lambda}(\nabla(X))\rightarrow \mathcal{T}_{\Lambda[\nabla(X)]}$ of $\Sigma$-algebras such that, as function between sets, $e\circ \iota_{nat}=\iota_{can}$. Recalling that $\mathbf{I}$ is the arrow $(\Sigma, X)\rightarrow (\Sigma[\nabla(X)], X )$ and using \cref{ind}, \cref{mrp} and \cref{trms}: \begin{align*} \trm{\Lambda}(\nabla X)\vDash_{\iota_{nat}}\phi &\iff \res{I}{\Lambda[\nabla(X)]}\qty(\gn)\vDash_{\iota_{nat}}\phi \\ &\iff\rs{I}\qty(\gn)\vDash_{\iota_{nat}}\phi \\ &\iff \gn \vDash_{\iota_{nat}}\phi \\ &\hspace{0.2cm}\Longrightarrow \mathcal{T}_{\Lambda[\nabla(X)]} \vDash_{e\circ \iota_{nat}}\phi\\ &\iff \mathcal{T}_{\Lambda[\nabla(X)]} \vDash_{\iota_{can}}\phi \\&\iff \vdash_{\Lambda[\nabla(X)]} \phi \end{align*} Now, by definition $\overline{\nabla(X)}$ is equal to $\qty{\vdash \ex{\bot}{x}\mid x\in X}$, therefore $\qty(\Lambda[\nabla(X)])^{\vdash}=\Lambda^{\vdash}$ and we get the thesis. \end{proof} \subsection{Eilenberg-Moore algebras and models}\label{sec:emalg} In this section we will compare the category $\mode{\Lambda}$ of models of some $\Lambda \in \thr{L}$ and $\eim{\Lambda}$ of Eilenberg-Moore algebras for the corresponding monad $\term{\Lambda}$. First of all we recall the following classic lemma (\cite[Prop.~4.2.1]{borceux1994handbook} and \cite[Theorem VI.3.1]{mac2013categories}). \begin{lemma} Let $\mathscr{L}:\catname{C}\rightarrow \catname{D}$ be a functor with right adjoint $\mathscr{R}$ and let $\mathsf{T}=\mathscr{R}\circ \mathscr{L}$ be its associated monad, then there exists a \emph{comparison functor} $\mathscr{K}:\catname{D}\rightarrow \catname{Alg}(\mathsf{T})$ such that $\mathscr{U}_{\mathsf{T}}\circ \mathscr{K}=\mathscr{R}$, where $\mathscr{U}_{\mathsf{T}}:\catname{Alg}(\mathsf{T})\rightarrow \catname{C}$ is the forgetful functor. $\mathscr{K}$ sends $D$ in $(\mathscr{R}(D), \mathscr{R}(\epsilon_D))$, where $\epsilon$ is the counit of the adjunction. \end{lemma} As a consequence, for any theory $\Lambda$ we have a functor from $\mode{\Lambda}$ to $\eim{\Lambda}$. We want to construct an inverse of such functor. \begin{definition} Let $\Lambda$ be in $\thr{L}$ and $\xi:\term{\Lambda}(M, \mu_M)\rightarrow (M, \mu_M)$ an object of $\eim{\Lambda}$, we define its \emph{associated algebra} $\mathscr{H}(\xi)=\qty(\qty(M, \mu_M), \Sigma^{\mathscr{H}(\xi)})$ putting \begin{equation*} c^{\mathscr{H}(\xi)}\coloneqq\xi\qty(c^{\mathscr{F}_\Lambda(X, \mu_X)}) \qquad f^{\mathscr{H}\qty(\xi)}\coloneqq\xi \circ f^{\mathscr{F}_\Lambda(X, \mu_X)}\circ \eta_{\qty(M,\mu_M)}^{\ar(f)} \end{equation*} for every $c\in C$ and $f\in O$. \end{definition} \begin{lemma}\label{hom} For any Eilenberg-Moore algebra $\xi:\term{\Lambda}(M, \mu_M)\rightarrow (M, \mu_M)$, $\xi$ itself is an arrow $\mathscr{F}_\Lambda(X,\mu_X)\rightarrow \mathscr{H}(\xi)$ of $\alg{\Sigma}$. \end{lemma} \begin{proof} Let us start with the following observation. \begin{claim}\label{expl} Let $\Lambda$ be a theory in the language $\mathcal{L}$ and $\hat{\mu}$ the multiplication of $\term{\Lambda}$, then, for any $g:(A,\mu_A)\rightarrow (B, \mu_B)$ and operation $f$ the following diagrams commutes: \begin{center} \begin{tikzpicture} \node(A) at(0,-1.5) {$\term{\Lambda}(B, \mu_B )^{\ar(f)}$}; \node(B) at(4,-1.5) {$\term{\Lambda}(B, \mu_B)$}; \node(D) at(4,0) {$\term{\Lambda}(M, \mu_M)$}; \node(C) at(0,0) {$\term{\Lambda}(M, \mu_M)^{\ar(f)}$}; \draw[->](A)--(B) node[pos=0.5, below]{$f^{\mathscr{F}_{\Lambda}(B, \mu_B)}$}; \draw[<-](B)--(D) node[pos=0.5, right]{$\term{\Lambda}(g)$}; \draw[<-](A)--(C) node[pos=0.5, left]{$\term{\Lambda}(g)^{\ar(f)}$}; \draw[->](C)--(D) node[pos=0.5, above]{$f^{\mathscr{F}_\Lambda(M, \mu_M)}$}; \node(A) at(-0.5,1) {$\term{\Lambda}(M, \mu_M )^{\ar(f)}$}; \node(B) at(4.5,1) {$\term{\Lambda}(M, \mu_M )^{\ar(f)}$}; \node(D) at(4.5,2.5) {$\term{\Lambda}(\term{\Lambda}(M, \mu_M))$}; \node(C) at(-0.5,2.5) {$\term{\Lambda}(\term{\Lambda}(M, \mu_M))^{\ar(f)}$}; \draw[->](A)--(B) node[pos=0.5, above]{$f^{\mathscr{F}_\Lambda(M, \mu_M)}$}; \draw[<-](B)--(D) node[pos=0.5, left]{$\hat{\mu}_{(M,\mu_M)}$}; \draw[<-](A)--(C) node[pos=0.5, left]{$\hat{\mu}_{(M,\mu_M)}^{\ar(f)}$}; \draw[->](C)--(D) node[pos=0.5, above]{$f^{\mathscr{F}_\Lambda\qty(\term{\Lambda}(M, \mu_M))}$}; \node(A) at(8.95,2.5) {$(1, c_{\bot})$}; \node(B) at(7.2,1) {$\term{\Lambda}\qty(\term{\Lambda}(M, \mu_M))$}; \node(C) at(10.7,1) {$\term{\Lambda}(M, \mu_M)$}; \draw[->](A)--(B) node[pos=0.5, left]{$c^{\mathscr{F}_{\Lambda}\qty(\term{\Lambda}\qty(M, \mu_M))}$}; \draw[->](B)--(C) node[pos=0.5, above]{$\hat{\mu}_{(M,\mu_M)}$}; \draw[->](A)--(C) node[pos=0.5, right, xshift=0.2cm]{$c^{\mathscr{F}_{\Lambda}(M, \mu_M)}$}; \node(A) at(8.95,0) {$(1, c_{\bot})$}; \node(B) at(7.2,-1.5) {$\term{\Lambda}(M, \mu_M)$}; \node(C) at(10.7,-1.5) {$\term{\Lambda}(M, \mu_M)$}; \draw[->](A)--(B) node[pos=0.5, left]{$c^{\mathscr{F}_{\Lambda}(M, \mu_M)}$}; \draw[->](B)--(C) node[pos=0.5, below]{$\term{\Lambda}(g)$}; \draw[->](A)--(C) node[pos=0.5, right, xshift=0.2cm]{$c^{\mathscr{F}_{\Lambda}(M, \mu_M)}$}; \end{tikzpicture} \end{center} \end{claim} \begin{proof} $\term{\Lambda}(g)=\mathscr{U}_\Lambda(\mathscr{F}_\Lambda(g))$ and $\hat{\mu}_{(A,\mu_A)} = \mathscr{U}_\Lambda(\epsilon_{\mathscr{F}_\Lambda(A,\mu_A)})$ where $\epsilon:\mathscr{F}_\Lambda\circ \mathscr{U}_\Lambda\rightarrow \id{\mode{\Lambda}}$ is the counit (\cite{borceux1994handbook} proposition $4.2.1$ or \cite{mac2013categories}, chapter VI). Now the thesis follows since both $\mathscr{F}_\Lambda(g)$ and $\epsilon_{\mathscr{F}_\Lambda(A,\mu_A)} $ are arrows of $\alg{\Sigma}$. \end{proof} We can now come back to the proof of our lemma: $\xi\circ c^{\mathscr{F}_\Lambda(M,\mu_M)}=c^{\mathscr{H}(\xi)}$ while the other condition is equivalent to commutativity of the outer rectangle in the diagram: \begin{center} \begin{tikzpicture}[scale=0.85] \node(A) at (0,0){$\term{\Lambda}\qty(\term{\Lambda}(M,\mu_M))^{\ar(f)}$}; \node(B) at (0,2){$\term{\Lambda}(M,\mu_M)^{\ar(f)}$}; \node(C) at (0,-2.5){$\term{\Lambda}(M,\mu_M)^{\ar(f)}$}; \node(D) at (-4,0){$\term{\Lambda}(M,\mu_M)^{\ar(f)}$}; \node(E) at (-4,2){$(M,\mu_M)^{\ar(f)}$}; \node(F) at (5.5,-2.5){$\term{\Lambda}(M,\mu_M)$}; \node(G) at (9.5,-2.5){$(M,\mu_M)$}; \node(H) at (5.5,0){$\term{\Lambda}\qty(\term{\Lambda}(M,\mu_M))$}; \node(I) at (9.5,0){$\term{\Lambda}(M,\mu_M)$}; \draw[->](E)--(B)node[pos=0.5, above]{$\eta_{(M, \mu_M)}^{\ar(f)}$}; \draw[->](D)--(A)node[pos=0.5, below]{$\eta_{\term{\Lambda}(M, \mu_M)}^{\ar(f)}$}; \draw[->](D)--(E)node[pos=0.5, left]{$\xi^{\ar(f)}$}; \draw[->](A)--(B)node[pos=0.5, right]{$\term{\Lambda}(\xi)^{\ar(f)}$}; \draw[->](A)--(H)node[pos=0.5, below]{$f^{\mathscr{F}_\Lambda\qty(\mathscr{F}_\Lambda\qty(M,\mu_M))}$}; \draw[->](A)--(C)node[pos=0.5, right]{$\hat{\mu}_{(M,\mu_M)}^{\ar(f)}$}; \draw[->](C)--(F)node[pos=0.5, below]{$f^{\mathscr{F}_\Lambda\qty(M,\mu_M)}$}; \draw[->](H)--(F)node[pos=0.5, left]{$\hat{\mu}_{(M,\mu_M)}$}; \draw[->](F)--(G)node[pos=0.5, below]{$\xi$}; \draw[->](I)--(G)node[pos=0.5, right]{$\xi$}; \draw[->](H)--(I)node[pos=0.5, above]{$\term{\Lambda}(\xi)$}; \draw[->](B)..controls(6.5,2) and (9.5,2)..(I)node[pos=0.2, above, yshift=0cm]{$f^{\mathscr{F}_\Lambda\qty(M,\mu_M)}$}; \draw[->](D)..controls (-4,-2.5)..(C)node[pos=0.2, left, yshift=0cm]{$\id{\term{\Lambda}(M, \mu_M)}$}; \node(a)at(-2,1){$1$}; \draw (a) circle [radius=0.3cm]; \node(b)at(-2,-1.25){$3$}; \draw (b) circle [radius=0.3cm]; \node(c)at(2.75,-1.25){$4$}; \draw (c) circle [radius=0.3cm]; \node(d)at(7.5,-1.25){$5$}; \draw (d) circle [radius=0.3cm]; \node(d)at(4.75,1){$2$}; \draw (d) circle [radius=0.3cm]; \end{tikzpicture} \end{center} but $\circled{1}$ commutes by naturality of $\eta$, $\circled{2}$ and $\circled{4}$ by \cref{expl}, $\circled{3}$ since $\term{\Lambda}$ is a monad and $\circled{5}$ from the fact that $\xi$ is an Eilenberg-Moore algebra. \end{proof} In general $\mathscr{H}(\xi)$ is not a model of $\Lambda$, but we can restrict to a class of theories such this holds. As in \cite{bacci2020quantitative, mardare2017axiomatizability}, we consider theories whose sequents' premises contain only variables. \begin{definition} A theory $\Lambda\in \thr{L}$ is \emph{basic}\footnote{In \cite{bacci2018algebraic} such theories are called \emph{simple}.} if, for any sequent $\Gamma \vdash \phi$ in it, all the formulae in $\Gamma$ contain only variables. \end{definition} \begin{example} Fuzzy groups, fuzzy normal groups, fuzzy semigroups and left, right, bilateral ideals (\cref{ex:fuzzyg1,ex:semig1}) are all examples of basic theories. \end{example} \begin{lemma}$ \mathscr{H}(\xi)$ is a model of $\Lambda$ for any basic theory $\Lambda\in \thr{L}$ and Eilenberg-Moore algebra $\xi:\term{\Lambda}(M, \mu_M)\rightarrow (M, \mu_M)$. \end{lemma} \begin{proof} We can start by observing that if $\Gamma \vdash \phi$ is in $\Lambda$ and $\iota:X\rightarrow M$ is an assignment such that $ \mathscr{H}(\xi)\vDash_{\iota} \Gamma$ then $\mathscr{F}_{\Lambda}(M, \mu_M)\vDash_{\eta_{(M,\mu_M)}\circ \iota} \Gamma$. Indeed, for every $\psi$ in $\Gamma$, we have two cases: \begin{itemize} \item $\psi$ is $x\equiv y$. Since $\iota(x)=\iota(y)$ we can easily conclude. \item $\psi$ is $\ex{l}{x}$. The thesis follows at once since the membership degree of $\eta_{(M,\mu_M)}(\iota(x))$ in $\term{\Lambda}(M, \mu_M)$ is greater than $\mu_{M}(\iota(x))$. \end{itemize} Therefore, we know that $\mathscr{F}_{\Lambda}(M, \mu_M)\vDash_{\eta_{(M,\mu_M)}\circ \iota} \phi$. Let us split again the two cases. \begin{itemize} \item $\phi$ is $t\equiv s$. In this case, $ t^{\mathscr{F}_{\Lambda}(M, \mu_M), \eta_{(M,\mu_M)}\circ \iota}=s^{\mathscr{F}_{\Lambda}(M, \mu_M), \eta_{(M,\mu_M)}\circ \iota}$, point $2$ of \cref{ind} and the fact that $\xi$ is an Eilenberg-Moore algebra thus imply: \begin{align*} t^{\mathscr{H}(\xi), \iota}&=t^{\mathscr{H}(\xi), \xi \circ \eta_{(M,\mu_M)}\circ \iota}=\xi\qty(t^{\mathscr{F}_{\Lambda}(M, \mu_M), \eta_{(M,\mu_M)}\circ \iota})\\&=\xi\qty(s^{\mathscr{F}_{\Lambda}(M, \mu_M), \eta_{(M,\mu_M)}\circ \iota})=s^{\mathscr{H}(\xi), \xi \circ \eta_{(M,\mu_M)}\circ \iota}=s^{\mathscr{H}(\xi), \iota} \end{align*} \item $\phi$ is $\ex{l}{t}$. This means that $l\leq \mu_{\Lambda}\qty(t^{\mathscr{F}_{\Lambda}(M, \mu_M), \eta_{(M,\mu_M)}\circ \iota})$, hence, using again \cref{hom} and \cref{ind}: \begin{align*} l&\leq \mu_{\Lambda}\qty( t^{\mathscr{F}_{\Lambda}(M, \mu_M), \eta_{(M,\mu_M)}\circ \iota})\leq \mu_{M}\qty(\xi\qty( t^{\mathscr{F}_{\Lambda}(M, \mu_M), \eta_{(M,\mu_M)}\circ \iota}))\\&= \mu_M\qty(t^{\mathscr{H}(\xi), \xi \circ \eta_{(M,\mu_M)}\circ \iota})=\mu_M\qty(t^{\mathscr{H}(\xi), \iota}) \end{align*} and we can conclude.\qedhere \end{itemize} \end{proof} \begin{theorem} For any basic theory $\Lambda\in \thr{L}$, the functor $\mathscr{K}:\mode{\Lambda}\rightarrow \eim{\Lambda}$ has an inverse $\mathscr{H}:\eim{\Lambda}\rightarrow \mode{\Lambda}$ sending $\xi:\term{\Lambda}(M, \mu_M)\rightarrow (M, \mu_M)$ to $\mathscr{H}(\xi)$. \end{theorem} \begin{proof} Let $\xi:\term{\Lambda}(M, \mu_M)\rightarrow (M, \mu_M)$, $\xi':\term{\Lambda}(N, \mu_N)\rightarrow (N, \mu_N)$ be two Eilenberg-Moore algebras and $g:(M, \mu_M)\rightarrow (N, \mu_N)$ an arrow between them, we claim that $g$ itself is a morphism of $\mode{\Lambda}$. Let $f\in O$ and $c\in C$, we have diagrams: \begin{center} \begin{tikzpicture} \node(A) at(3.5,2) {$(M, \mu_M )$}; \node(B) at(7.5,2) {$(N, \mu_N)$}; \node(D) at(7.5,3.5) {$\term{\Lambda}(N, \mu_N)$}; \node(C) at(3.5,3.5) {$\term{\Lambda}(M, \mu_M)$}; \draw[->](A)--(B) node[pos=0.5, below]{$g$}; \draw[<-](B)--(D) node[pos=0.5, right]{$\xi'$}; \draw[<-](A)--(C) node[pos=0.5, left]{$\xi$}; \draw[->](C)--(D) node[pos=0.5, below]{$\term{\Lambda}(g)$}; \node(d)at(5.5,2.65){$2$}; \draw (d) circle [radius=0.2cm]; \node(e)at(5.5,4.2){$1$}; \draw (e) circle [radius=0.2cm]; \node(E) at(5.5,5) {$(1, c_{\bot})$}; \draw[->](E)--(C) node[pos=0.5, left]{$c^{\mathscr{F}_{\Lambda}(M, \mu_M)}$}; \draw[->](E)--(D) node[pos=0.5, right, xshift=0.2cm]{$c^{\mathscr{F}_{\Lambda}(N, \mu_N)}$}; \node(A) at(0,1){$(M,\mu_M)^{\ar(f)}$}; \node(B) at(0,-0.5){$(N,\mu_N)^{\ar(f)}$}; \node(C) at(3.5,1){$\term{\Lambda}(M,\mu_M)^{\ar(f)}$}; \node(D) at(3.5,-0.5){$\term{\Lambda}(N,\mu_N)^{\ar(f)}$}; \node(E) at(7.5,1){$\term{\Lambda}(M,\mu_M)$}; \node(F) at(7.5,-0.5){$\term{\Lambda}(N,\mu_N)$}; \node(G) at(11,1){$(M,\mu_M)$}; \node(H) at(11,-0.5){$(N,\mu_N)$}; \node(a)at(1.75,0.25){$3$}; \draw (a) circle [radius=0.2cm]; \node(b)at(5.5,0.25){$4$}; \draw (b) circle [radius=0.2cm]; \node(c)at(9.25,0.25){$5$}; \draw (c) circle [radius=0.2cm]; \draw[->](A)--(B)node[pos=0.5, left]{$g^{\ar(f)}$}; \draw[->](C)--(D)node[pos=0.5, right]{$\term{\Lambda}(g)^{\ar(f)}$}; \draw[->](E)--(F)node[pos=0.5, left]{$\term{\Lambda}(g)$}; \draw[->](G)--(H)node[pos=0.5, right]{$g$}; \draw[->](A)--(C)node[pos=0.5, above]{$\eta_{(M, \mu_M)}^{\ar(f)}$}; \draw[->](B)--(D)node[pos=0.5, below]{$\eta_{(N, \mu_N)}^{\ar(f)}$}; \draw[->](C)--(E)node[pos=0.5, above]{$f^{\mathscr{F}_\Lambda(M,\mu_M)}$}; \draw[->](D)--(F)node[pos=0.5, below]{$f^{\mathscr{F}_\Lambda(N,\mu_N)}$}; \draw[->](E)--(G)node[pos=0.5, above]{$\xi$}; \draw[->](F)--(H)node[pos=0.5, below]{$\xi'$}; \end{tikzpicture} \end{center} Commutativity of $\circled{1}$ and $\circled{4}$ follows from \cref{expl}, that of $\circled{3}$ from naturality of $\eta$, $\circled{2}$ and $\circled{5}$ from the fact that $g$ is an arrow of $\eim{\Lambda}$. So $\mathscr{H}$ is a functor. Since both $\mathscr{H}$ and $\mathscr{K}$ are the identity on arrows, it is enough to show that they are the inverse of each other on objects. Let $\xi:\term{\Lambda}(M,\mu_M)\rightarrow (M,\mu_M)$ be in $\eim{\Lambda}$, then \cref{hom} implies that $\xi$ is a morphism of $\mode{\Lambda}$ such that $\mathscr{U}_\Lambda(\xi)\circ \eta_{(M,\mu_M)}=\id{\qty(M,\mu_M)}$, but there is only one such morphism, namely the component of the counit in $\mathscr{H}(\xi)$, so $\mathscr{U}_\Lambda\qty(\epsilon_{\mathscr{H}(\xi)})=\xi$ and $\mathscr{K}\circ \mathscr{H}=\id{\eim{\Lambda}}$. On the other hand, let $\mathcal{A}=\qty(\qty(A,\mu_A), \Sigma^{\mathcal{A}})\in \mode{\Lambda}$, and consider, for any $f\in O$ and $c\in C$, the diagrams \begin{center} \begin{tikzpicture} \node(A)at (0,0) {$\term{\Lambda}(A,\mu_A)^{\ar(f)}$}; \node(B)at (0,-1.5) {$(A,\mu_A)^{\ar(f)}$}; \node(C)at (4,0) {$\term{\Lambda}(A,\mu_A)$}; \node(D)at (4,-1.5) {$(A,\mu_A)$}; \node(E)at(-4,0){$(A,\mu_A)^{\ar(f)}$}; \draw[->](E)--(A)node[pos=0.5, above]{$\eta_{(A, \mu_A)}^{\ar(f)}$}; \draw[->](E)..controls(-4,-1.5)..(B)node[pos=0.5, left]{$\id{{(A, \mu_A)}^{\ar(f)}}$}; \draw[->](A)--(B)node[pos=0.5, right]{$\mathscr{U}_\Lambda(\epsilon_{\mathcal{A}})^{\ar(f)}$}; \draw[->](C)--(D)node[pos=0.5, right]{$\mathscr{U}_\Lambda(\epsilon_{\mathcal{A}})$}; \draw[->](A)--(C)node[pos=0.5, above]{$f^{\mathcal{A}}$}; \draw[->](B)--(D)node[pos=0.5, below]{$f^{\mathcal{A}}$}; \node(a)at(-2,-0.75){$2$}; \draw (a) circle [radius=0.2cm]; \node(b)at(2.5,-0.75){$3$}; \draw (b) circle [radius=0.2cm]; \node(A)at (0,2.5) {$(1,c_{\bot})$}; \node(C)at (-2,1) {$\term{\Lambda}(A,\mu_A)$}; \node(D)at (2,1) {$(A,\mu_A)$}; \draw[->](C)--(D)node[pos=0.5, below]{$\mathscr{U}_\Lambda(\epsilon_{\mathcal{A}})$}; \draw[->](A)--(C)node[pos=0.5, left]{$c^{{\mathscr{F}_\Lambda(A, \mu_A)}}$}; \draw[->](A)--(D)node[pos=0.5, right, xshift=0.1cm]{$c^{\mathcal{A}}$}; \node(b)at(0,1.75){$1$}; \draw (b) circle [radius=0.2cm]; \end{tikzpicture} \end{center} Commutativity of $\circled{1}$ and $\circled{3}$ follows since each component of $\epsilon$ is an arrow of $\mode{\Lambda}$, that of $\circled{2}$ since $\epsilon$ is the counit. So we can deduce now that $ f^{\mathscr{H}(\mathscr{U}_\Lambda(\epsilon_{\mathcal{A}}))}=f^{\mathcal{A}}$ and $ c^{\mathscr{H}(\mathscr{U}_\Lambda(\epsilon_{\mathcal{A}}))}=c^{\mathcal{A}}$ from which we can deduce that $\mathscr{H}\circ \mathscr{K}=\id{\mode{\Lambda}}$. \end{proof} \begin{corollary} For any basic theory $\Lambda\in \thr{L}$, $\eim{\Lambda}$ and $\mode{\Lambda}$ are isomorphic, and thus equivalent, categories. \end{corollary} \section{Equational axiomatizations}\label{sec:birk} In this section we prove two results for our calculus analogous to the classic HSP theorem \cite{birkhoff1935structure}, using the results by Milius and Urbat \cite{milius2019equational}. \subparagraph{The abstract framework} Let us start recalling the tools introduced in \cite{milius2019equational}, adapted to our situation. In the following we will fix a tuple\footnote{In their work Milius and Urbat additionaly require a full subcategory of $\catname{C}$ and a fixed class of cardinals, but we will not need this level of generality.} $\qty(\catname{C}, \qty(\mathscr{E}, \mathscr{M}), \mathscr{X} )$ where $\catname{C}$ is a category, $\qty(\mathscr{E}, \mathscr{M})$ is a proper factorization system on $\catname{C}$ and $\mathscr{X}$ is a class of objects of $\catname{C}$. \begin{definition} An object $X$ of $\catname{C}$ is \emph{projective with respect to an arrow $f:A\rightarrow B$} if for any $h:X\rightarrow B$ there exists a $k:X\rightarrow A$ such that $f\circ k=h$. \iffalse \begin{center} \begin{tikzpicture} \node(A) at(0,0){$A$}; \node(B) at(0,-1.5){$B$}; \node(X) at(-2,-1.5){$X$}; \draw[->](A)--(B)node[pos=0.5, right]{$f$}; \draw[->](X)--(B)node[pos=0.5, below]{$h$}; \draw[->, dashed](X)..controls(-1.75,-0.75)and(-1.25, -0.25)..(A)node[pos=0.5, above]{$k$}; \end{tikzpicture} \end{center} \fi We define $ \mathscr{E}_{\mathscr{X}}$ as the class of $e\in\mathscr{E}$ such that for every $X\in \mathscr{X}$, $X$ is projective with respect to $e$. A \emph{$\mathscr{E}_{\mathscr{X}}$-quotient} is just an arrow in $\mathscr{E}_{\mathscr{X}}$. \end{definition} In the rest of the section, we assume that $\qty(\catname{C},\qty(\mathscr{E}, \mathscr{M}), \mathscr{X} )$ satisfies the following requirements: \begin{itemize} \item $\catname{C}$ has all (small) products; \item for any $X\in \mathscr{X}$, the class $ \arr{X}{C}$ of all $e\in \mathscr{E}$ with domain $X$ is essentially small, i.e. there is a set $\mathcal{J}\subset\arr{X}{C}$ such that for any $e:X\rightarrow C\in \arr{X}{C}$ there exists $e':X\rightarrow D \in \mathcal{J}$ and an isomorphism $\phi$ such that $\phi \circ e=e'$; \iffalse \begin{center} \begin{tikzpicture} \node(A)at(0,0){$X$}; \node(B)at(-1,-1.5){$C$}; \node(C)at(1,-1.5){$D$}; \draw[->](A)--(B)node[pos=0.5, left]{$e$}; \draw[->](A)--(C)node[pos=0.5, right]{$e'$}; \draw[->](B)--(C)node[pos=0.5, below]{$\phi$}; \end{tikzpicture} \end{center} commute;\fi \item for every object $C$ of $\catname{C}$ there exists $e:X\rightarrow C$ in $\mathscr{E}_{\mathscr{X}}$ with $X\in \mathscr{X}$. \end{itemize} \begin{definition}\label{equat} An \emph{$\mathscr{X}$-equation} is an arrow $e\in \arr{X}{C}$ with $X\in \mathscr{X}$. \iffalse Let $X$ be in $\mathscr{X}$ and preordered with $e\leq e'$ if and only if there exists $k$ such that $e'=k\circ e$. An \emph{$\mathscr{X}$-equation over $X$} is a class $\mathscr{J}_X\subset \arr{X}{C}$ such that: \begin{enumerate} \item $e:X\rightarrow E$ in $\mathscr{J}_X$ and $q:E\rightarrow E'$ in $\mathscr{E}_X$ imply $q\circ e \in \mathscr{J}_X$; \item for every $\lambda \in \Lambda$ any family $\qty{e_i}_{i\in \lambda}\subset \mathscr{J}_X$ admits a lower bound $e\in \mathscr{J}_X$. \end{enumerate} \fi We say that an object $A$ of $\catname{C}$ \emph{satisfies} $e:X\rightarrow C$, and we write $A\vDash_{\mathscr{X}}e$, if for every $h:X\rightarrow A$ there exists $q:C\rightarrow A$ such that $q\circ e=h$. Given a class $\mathbb{E}$ of $\mathscr{X}$-equations, we define $\mathcal{V}(\mathbb{E})$ as the full subcategory of $\catname{C}$ given by objects that satisfy $e$ for every $e\in \mathbb{E}$. A full subcategory $\catname{V}$ is $\mathscr{X}$-\emph{equationally presentable} if there exists $\mathbb{E}$ such that $\catname{V}=\mathcal{V}(\mathbb{E})$. \end{definition} \begin{remark}\label{rmk} The definition of equation in \cite[Def.~3.3]{milius2019equational} is given in terms of suitable subclasses of $\arr{X}{C}$. However in our setting Milius and Urbat's definition reduces to ours (cfr.~\cite[Remark 3.4]{milius2019equational}). \end{remark} \iffalse \begin{lemma}[\cite{milius2019equational}, remark $3.4$]\label{equa} If $\arr{X}{C}$ is a set and $\Lambda$ is the class of all cardinals then every equation $\mathcal{T}_X$ over $X$ has a bottom element $e:X\rightarrow E$ and $A\vDash \mathcal{J}_X$ if and and only if any $h:X\rightarrow A$ factors through it. \end{lemma} \begin{remark} Since $\leq$ is only a preorder on $\arr{X}{C}$ we can have many of bottom elements, all isomorphic to each other. \end{remark} \begin{proof} If $\arr{X}{C}$ is a set and $\Lambda$ is the class of all cardinals then a bottom element $e$ exists by item $2$ of the definition of equations over $X$. The implication from the right to the left is immediate, for the other let $h:X\rightarrow A$ be an arrow in $\catname{C}$ and suppose that $A\vDash \mathscr{J}_X$, then there exist $e':X\rightarrow E'$ in $\mathscr{J}_X$ and $q:E'\rightarrow A$ such that $h=q\circ e'$ but from $e\leq e'$ we deduce that $e'=k\circ e$ for some arrow $k$, hence $h=(q\circ k)\circ e$. \begin{center} \begin{tikzpicture} \node(A) at(0,0){$A$}; \node(B) at(0,1.5){$E$}; \node(C) at(2,1.5){$E'$}; \node(X) at(-2,1.5){$X$}; \draw[<-](C)--(B)node[pos=0.5, above]{$q$}; \draw[<-, dashed](A)--(B); \draw[->](X)--(B)node[pos=0.5, above]{$e$}; \draw[->](X)..controls(-1.75,0.75)and(-1.25, 0.25)..(A)node[pos=0.5, below]{$h$}; \draw[->](X)..controls(-1,2.5)and(1, 2.5)..(C)node[pos=0.5, above]{$e'$}; \draw[->](C)..controls(1.75,0.75)and(1.25, 0.25)..(A)node[pos=0.5, below]{$k$}; \end{tikzpicture} \end{center} \end{proof} \begin{definition}We say that a full subcategory $\catname{V}$ of $\catname{C}_0$ is: \begin{itemize}\item a \emph{variety} if it is closed $\mathscr{E}_{\mathscr{X}}$-quotients, $\mathscr{M}$-subobjects and $\Lambda$-products; \item \emph{equationally presentable} if there exists a (possibly large) collection $\mathbb{E}$ of $\mathscr{X}$-equations such that $\catname{V}=\mathcal{V}(\mathbb{E})$. \end{itemize} \end{definition} \fi \begin{theorem}[{\cite[Th.~3.15, 3.16]{milius2019equational}}] \label{milius} A full subcategory $\catname{V}$ of $\catname{C}$ is $\mathscr{X}$-equationally presentable if and only if it is closed under $\mathscr{E}_\mathscr{X}$-quotients, $\mathscr{M}$-subobjects and (small) products. \end{theorem} \subparagraph{Application to fuzzy algebras} In order to apply the results above to $\alg{\Sigma}$, we need to define the required inputs, i.e., to specify a factorization system and a class of $\Sigma$-algebras. \begin{lemma}\label{facto} For any signature $\Sigma$ the classes $\mathscr{E}_\Sigma\coloneqq\qty{e \text{ arrow of } \alg{\Sigma} \mid \mathscr{U}_\Sigma(e) \text{ is epi} }$ and $\mathscr{M}_\Sigma\coloneqq\qty{m \text{ arrow of } \alg{\Sigma} \mid \mathscr{U}_\Sigma(m) \text{ is strong mono} }$ form a proper factorization system on $\alg{\Sigma}$. \end{lemma} \begin{proof} Let $\mathcal{A}=\qty((A, \mu_A), \Sigma^{\mathcal{A}})$ and $\mathcal{B}=\qty((B, \mu_B), \Sigma^{\mathcal{B}})$ two $\Sigma$-algebras with a morphism $g:\mathcal{A}\rightarrow \mathcal{B}$ between them. $\mathcal{U}_\Sigma(g)$ factors as $m\circ e$ where $e:(A, \mu_A)\rightarrow(g(A), {\mu_B}_{|g(A)})$ and $m:(g(A), {\mu_B}_{|g(A)})\rightarrow(B, \mu_B)$ is the usual epi-monomorphism factorization of $f$ on $\fuz{H}$ (cfr.~\cref{prod}). Notice that $c^{\mathcal{B}}=g(c^\mathcal{A})\in g(A)$ for all $c\in C$ and $f^{\mathcal{B}}\qty(g(a_1),\dots, g(a_{\ar(g)}))=g\qty(f^{\mathcal{A}}(a_1,\dots,a_{\ar(g)}))\in g(A)$ for every $f\in O$ and $g(a_1),\dots, g(a_{\ar(g)})\in g(A)$ so $\Sigma^{\mathcal{B}}$ restricts to a $\Sigma$-algebra structure on $(g(A), {\mu_B}_{|g(A)})$ and it is clear that with this choice $e$ and $m$ becomes morphisms of $\alg{\Sigma}$. We have now to show the left lifting property. Given $e\in \mathscr{E}_\Sigma$, $m\in \mathscr{M}_\Sigma$ and $g$ and $h$ such that $m\circ g=h\circ e$ we can apply $\mathscr{U}_\Sigma$ and get a square \begin{center} \begin{tikzpicture} \node(A) at(0,0) {$\mathscr{U}_\Sigma(\mathcal{A})$}; \node(B) at(2.5,0) {$\mathscr{U}_\Sigma(\mathcal{B})$}; \node(D) at(2.5,-1.5) {$\mathscr{U}_\Sigma\qty(\mathcal{B'})$}; \node(C) at(0,-1.5) {$\mathscr{U}_\Sigma\qty(\mathcal{A'})$}; \draw[->](A)--(B) node[pos=0.5, above]{$\mathscr{U}_\Sigma(g)$}; \draw[->](B)--(D) node[pos=0.5, right]{$\mathscr{U}_\Sigma(m)$}; \draw[->](A)--(C) node[pos=0.5, left]{$\mathscr{U}_\Sigma(e)$}; \draw[->](C)--(D) node[pos=0.5, below]{$\mathscr{U}_\Sigma(h)$}; \end{tikzpicture} \end{center} which, by \cref{prod}, has a diagonal filling $k:\mathscr{U}_\Sigma\qty(\mathcal{A}')\rightarrow \mathscr{U}_\Sigma(\mathcal{B})$. Let us show that $k$ is a morphism of $\alg{\Sigma}$. For any $c\in C$ we have $c^{\mathcal{A'}}=e(c^\mathcal{A})$ and for every $f\in O$ and $x_1,\dots, x_{\ar(f)}\in \mathscr{U}_\Sigma\qty(\mathcal{A}')$ there exist $a_1,\dots, a_{\ar(f)}\in \mathscr{U}_\Sigma\qty(\mathcal{A})$ such that $e(a_i)=x_i$ for $1\leq i\leq \ar(f)$, so $k(c^\mathcal{A'})=k\qty(e\qty(c^\mathcal{A}))=g\qty(c^\mathcal{A})=c^\mathcal{B}$ and \begin{align*} k\qty(f^{\mathcal{A'}}\qty(x_1,\dots, x_{\ar(f)})) & = k\qty(f^{\mathcal{A'}}\qty(e\qty(a_1),\dots,e\qty(a_{\ar(f)})))= k\qty(e\qty(f^{\mathcal{A}}\qty(a_1,\dots,a_{\ar(f)}))) \\ & = g\qty(f^{\mathcal{A}}\qty(a_1,\dots,a_{\ar(f)})) = f^{\mathcal{B}}\qty(g\qty(a_1),\dots,g\qty(a_{\ar(f)})) \\ &= f^{\mathcal{B}}\qty(k\qty(e\qty(a_1)),\dots,k\qty(e\qty(a_{\ar(f)}))) =f^{\mathcal{B}}\qty(k\qty(x_1),\dots,k\qty(x_{\ar(f)})) \end{align*} Finally, properness follows at once since $\mathscr{U}_\Sigma$ is faithful and so reflects epis and monos. \end{proof} \iffalse \begin{definition} We define two triples as inputs of Milius and Urbat's tools. \begin{itemize} \item In both cases we take $\alg{\Sigma}$ as $\catname{C}$. \item $(\mathscr{E}, \mathscr{M})$ is the factorization system $(\mathscr{E}_\Sigma, \mathscr{M}_\Sigma)$ constructed in \cref{facto}. \item $\mathscr{X}$ is one of the following: \end{itemize} \end{definition} \fi \begin{definition} We define the following two classes of $\Sigma$-algebras: \begin{align*} \mathscr{X}_0\coloneqq\qty{\mathscr{F}^{\catname{Set}}_{\Sigma}\qty(X)\mid X \in \catname{Set}}\qquad \mathscr{X}_{\mathsf{E}}\coloneqq\qty{\mathscr{F}_{\Sigma}(X, \mu_X)\mid (X, \mu_X)\in \fuz{H}} \end{align*} We will use $\mathscr{E}_{\Sigma,\mathscr{X}_0}$ (resp., $\mathscr{E}_{\Sigma,\mathscr{X}_\mathsf{E}}$) for the class of $e\in\mathscr{E}$ such that every $X\in \mathscr{X}_0$ (resp. $X\in \mathscr{X}_\mathsf{E}$) is projective with respect to $e$. \end{definition} \begin{remark} $\mathscr{X}_0=\qty{\trm{\Sigma}\qty(X, \mu_X)\mid \supp{X}=\emptyset}$. \end{remark} We have now all the ingredients needed to use the results recalled above. \begin{lemma}\label{aaa} With the above definitions: \begin{enumerate} \item $\mathscr{E}_{\Sigma,\mathscr{X}_0}=\mathscr{E}_\Sigma$; \item $ \mathscr{E}_{\Sigma, \mathscr{X}_{\mathsf{E}}}=\qty{e\in \mathscr{E}_{\Sigma} \mid \mathscr{U}_\Sigma(e) \text{ is split}}$; \item $(\alg{\Sigma}, (\mathscr{E}_\Sigma, \mathscr{M}_\Sigma), \mathscr{X}_0)$ and $(\alg{\Sigma}, (\mathscr{E}_\Sigma, \mathscr{M}_\Sigma), \mathscr{X}_{\mathsf{E}} )$ satisfy the conditions of our settings. \end{enumerate} \end{lemma} \begin{proof} Let us start adapting the usual notion of congruence to our set environment. \begin{definition} Given a $\Sigma$-algebra $\mathcal{A}=\qty(\qty(A, \mu_A), \Sigma^{\mathcal{A}})$, a \emph{fuzzy congruence} on $\mathcal{A}$ is a pair $(\sim, \mu)$ where \begin{itemize} \item $\sim$ is a congruence: i.e. an equivalence relation such that, for any $f\in O$, if $a_i\sim b_i$ fo $1\leq i \leq \ar(f)$ then $f^{\mathcal{A}}\qty(a_1,\dots a_{\ar(f)})\sim f^{\mathcal{A}}\qty(b_1,\dots, b_{\ar(f)})$; \item $\mu:A\rightarrow H$ is a function such $\mu(a)=\mu(b)$ whenever $a\sim b$; \item for any $f\in O$, \begin{equation*} \bigwedge_{i=1}^{\ar(f)} \mu(a_i) \leq \mu\qty(f^{\mathcal{A}}\qty(a_1,\dots a_{\ar(f)})) \end{equation*} \item $\mu_A(a)\leq \mu(a)$ for every $a\in A$. \end{itemize} \end{definition} \begin{proposition}\label{cong} Let $\mathcal{A}=\qty(\qty(A, \mu_A), \Sigma^{\mathcal{A}})$ be a $\Sigma$-algebra, then: \begin{enumerate}[label=(\alph*)] \item if $\qty{\qty(\sim_{i}, \mu_i)}_{i\in I}$ is a family of fuzzy congruence then $\qty(\bigcap_{i\in I}\sim_{i}, \mu)$ with $\mu:A\rightarrow H$ the pointwise infimum of $\qty{\mu_i}_{i\in I} $ is a fuzzy congruence; \item for every fuzzy congruence $(\sim, \mu)$ there exists an epimorphism: $e_{(\sim, \mu)}:\mathcal{A}\rightarrow \mathcal{B}$ such that $\mu_B(b)=\mu(a)$ for any $a\in e^{-1}(b)$ and $e_{(\sim, \mu)}(a)=e_{(\sim, \mu)}(b)$ if and only if $a\sim b$; \item for every epimorphism $e:\mathcal{A}\rightarrow \mathcal{B}$ there exists a fuzzy congruence $(\sim_e, \mu_e)$ on $\mathcal{A}$ such that $e\leq e_{(\sim, \mu)}$ and $e_{(\sim, \mu)}\leq e$ in $\mathcal{A}\arro \alg{\Sigma}$. \end{enumerate} \end{proposition} \begin{proof} \begin{enumerate}[label=(\alph*)] \item This is straightforward. \item Define $\mathcal{B}=\qty(\qty(B, \mu_B), \Sigma^{\mathcal{B}})$ setting $B:=A/\sim$, $\mu_B([a]):=\mu(a)$ and, for any $f\in O$ \begin{equation*} f^{\mathcal{A}}\qty(\qty[a_1],\dots,[a_{\ar(f)}]):=\qty[f^{\mathcal{B}}\qty(\qty[a_1], \dots, [a_{\ar(f)}])] \end{equation*} Since $(\sim, \mu)$ is a fuzzy congruence all these objects are well defined, the fact that $f^{\mathcal{B}}$ is an arrow of fuzzy sets follows from the second condition on $\mu$, while the last condition entails that the projection on the quotient is an arrow of $\fuz{H}$. \item Put $a\sim_e b$ if and only if $e(a)=e(b)$ and $\mu_e(a):=\mu_B(e(a))$. Since $e$ is a morphism of $\alg{\Sigma}$ we get the first and the last condition in the definition of a fuzzy congruence, while the second one follows since \begin{align*} \mu_e\qty(f^{\mathcal{A}}\qty(a_1,\dots, a_{\ar(f)}))&=\mu_B\qty(e\qty(f^{\mathcal{A}}\qty(a_1,\dots, a_{\ar(f)})))=\mu_B\qty(f^{\mathcal{B}}\qty(e\qty(a_1),\dots, e\qty(a_{\ar(f)})))\\&\geq \bigwedge_{i=1}^{\ar(f)}\mu_B\qty(e\qty(a_i))=\bigwedge_{i=1}^{\ar(f)}\mu_e\qty(a_i) \end{align*} Now, it is immediate to see that the function sending the equivalence class $[a]$ of $a\in A$ to $e(b)$ induces an isomorphism of $\alg{\Sigma}$ witnessing the thesis.\qedhere \end{enumerate} \end{proof} So equipped we can turn back to the proof of \cref{aaa}. \begin{enumerate} \item Let $e:\mathcal{A}\rightarrow \mathcal{B}$ be an arrow in $\mathscr{E}_\Sigma$ and let $h:\trma{\Sigma}(X)\rightarrow \mathcal{B}$ be any morphism of $\alg{\Sigma}$. By point $2$ of \cref{mono} $e$ is surjective so for any $x\in X$ we can take a $a_x\in e^{-1}\qty(h\qty(\eta_X\qty(x)))$, where $\eta$ is the unit of the adjunction $\trma{\Sigma}\dashv\mathscr{V}_\Sigma $ of \cref{left}, and define $ \bar{k}:X\rightarrow A$ mapping $x$ to $a_x$, where $\mathcal{A}=\qty(\qty(A, \mu_A), \Sigma^{\mathcal{A}})$. By adjointness, from $\bar{k}$ we get $k:\trma{\Sigma}(X)\rightarrow \mathcal{A}$ and \begin{align*} \qty(e\circ k)\circ \eta_{X}=e\circ \qty(k\circ \eta_{X})=e \circ \bar{k}=h\circ \eta_{X} \end{align*} so $e\circ k = h$. \begin{center} \begin{tikzpicture} \node(A) at(1.5,0){$\mathscr{V}_\Sigma(\mathcal{A})$}; \node(B) at(1.5,-1.5){$\mathscr{V}_\Sigma(\mathcal{B})$}; \node(X) at(-2,-1.5){$\mathscr{V}_\Sigma\qty(\trma{\Sigma}\qty(X))$}; \node(Y) at(-5.5,-1.5){$X$}; \draw[->](A)--(B)node[pos=0.5, right]{$\mathscr{V}_\Sigma(e)$}; \draw[<-](X)--(Y)node[pos=0.5, below]{$\eta_{\nabla(X)}$}; \draw[->](X)--(B)node[pos=0.5, below]{$\mathscr{V}_\Sigma(h)$}; \draw[->, dashed](X)..controls(-1.75,-0.75)and(-1.25, -0.25)..(A)node[pos=0.35, left, xshift=-0.1cm]{$\mathscr{V}_\Sigma(k)$}; \draw[->, dashed](Y)..controls(-4.5,0)and(-1, 0)..(A)node[pos=0.5, above]{$\bar{k}$}; \end{tikzpicture} \end{center} \item Let $e:\mathcal{A}\rightarrow \mathcal{B}$ be in $\mathscr{E}_\Sigma$ such that $\mathscr{U}_\Sigma(e)$ is split and let $s$ be a section in $\fuz{H}$, then, for any $h:\trm{\Sigma}(X,\mu_X)\rightarrow \mathcal{B}$ we can consider the arrow $s\circ h\circ \eta_{(X, \mu_X)}$, which, by adjointness provides a $k:\trm{\Sigma}(X,\mu_X)\rightarrow \mathcal{A}$, moreover: \begin{align*} \qty(e\circ k)\circ \eta_{(X, \mu_X)}&=e\circ \qty(k\circ \eta_{(X, \mu_X)})=e\circ \qty(s\circ h\circ \eta_{(X,\mu_X)})\\&=\qty(e\circ s)\circ \qty(h\circ \eta_{(X,\mu_X)})=h\circ \eta_{(X,\mu_X)} \end{align*} so $k$ is the wanted lifting. On the other hand, if $e$ is in $\mathscr{E}_{\Sigma, \mathscr{X}_1}$ we can take the diagram: \begin{center} \begin{tikzpicture} \node(A) at(1.5,0){$\mathscr{U}_\Sigma(\mathcal{A})$}; \node(B) at(1.5,-1.5){$\mathscr{U}_\Sigma(\mathcal{B})$}; \node(X) at(-2,-1.5){$\mathscr{U}_\Sigma\qty(\trm{\Sigma}(\mathscr{U}_\Sigma(\mathcal{B})))$}; \node(Y) at(-5.5,-1.5){$\mathscr{U}_\Sigma(\mathcal{B})$}; \draw[->](A)--(B)node[pos=0.5, right]{$\mathscr{U}_\Sigma(e)$}; \draw[<-](X)--(Y)node[pos=0.5, above]{$\eta_{\mathscr{U}_\Sigma(\mathcal{B})}$}; \draw[->](X)--(B)node[pos=0.5, above]{$\mathscr{U}_\Sigma(\epsilon_{\mathcal{B}})$}; \draw[->](X)..controls(-1.75,-0.25)and(0, 0)..(A)node[pos=0.5, above, xshift=-0.05cm]{$\mathscr{U}_\Sigma(k)$}; \draw[->](Y)..controls(-2.5,-2.5)and(-1.5, -2.5)..(B)node[pos=0.5, below,]{$\id{\mathscr{U}_\Sigma(\mathcal{B})}$}; \end{tikzpicture} \end{center} where $\epsilon_{\mathcal{B}}$ is the component of the counit $\epsilon:\trm{\Sigma}\circ \mathscr{U}_\Sigma\rightarrow \id{\alg{\Sigma}}$ and $k$ its lifting. Taking $\mathscr{U}_\Sigma(k)\circ \eta_{\mathscr{U}_\Sigma(\mathcal{B})}$ we get the desired section of $\mathscr{U}_\Sigma(e)$. \item Let us proceed by steps. \begin{itemize} \item $\fuz{H}$ has all products by \cref{prod}. \item $\arr{X}{C}$ is essentially small by point $3$ of \cref{cong}. \item For any fuzzy set $(X, \mu_X)$ we can consider the identity $ \id{(X, \mu_X)}:(X, \mu_X)\rightarrow (X, \mu_X)$ and the counit $\epsilon_{(X, \mu_X)}:\nabla(X)\rightarrow (X, \mu_X)$ of the adjunction $\nabla \dashv\mathscr{U}$ of \cref{adj}. They induce arrows $ e_0:\trma{\Sigma}(X)\rightarrow (X, \mu_X)$ and $ e_{\mathsf{E}}:\trm{\Sigma}(X, \mu_X)\rightarrow (X, \mu_X)$ such that $\mathscr{U}_\Sigma \qty(e_0)\circ \eta_{\nabla(X)}= \epsilon_{(X, \mu_X)}$ and $\mathscr{U}_\Sigma \qty(e_H)\circ \eta_{(X, \mu_X)}=\id{(X, \mu_X)}$. So $\mathscr{U}_\Sigma \qty(e_H)$ is split and, since $\epsilon_{(X, \mu_X)}$ is surjective, point $2$ of \cref{mono} allows us to conclude that $\mathscr{U}_\Sigma \qty(e_0)$ is an epimorphism. \qedhere \end{itemize} \end{enumerate} \end{proof} We want now to translate formulae of our sequent calculus into $\mathscr{X}_0$- and $\mathscr{X}_\mathsf{E}$-equations. To this end, we have to restrict to two classes of theories, which we introduce next. \begin{definition} Let $\mathcal{L}=(\Sigma, X)$ be a language, a $\Lambda \in \thr{L}$ is said to be: \begin{itemize} \item \emph{unconditional} (\cite[App.~B.5]{milius2019equational}) if any sequent in $\Lambda$ is of the form $\vdash \phi$ for some formula $\phi$; \item \emph{of type $\mathsf{E}$} if any sequent in $\Lambda$ is of the form $\qty{\ex{l_i}{x_i}}_{i\in I}\vdash \phi$ for some formula $\phi$, $\{x_i\}_{i\in I}\subset X$ and $\{l_i\}_{i\in I}\subset H$. \end{itemize} \end{definition} \begin{lemma}\label{te} For any signature $\Sigma$ and $\mathscr{X}_{\mathsf{E}}$-equation $e:\trm{\Sigma}(X, \mu_X)\rightarrow \mathcal{B}$ there exists a type ${\mathsf{E}}$ theory $\Lambda_e$ such that, for every $\Sigma$-algebra $\mathcal{A}$, $ \mathcal{A}\vDash_{\mathscr{X}_1} e$ if and only if $\mathcal{A}\in \modd(\Lambda_e)$. Moreover $\abs{\Gamma}\leq \abs{\supp{X}}$ for any $\Gamma \vdash \phi \in \Lambda_e$. \end{lemma} \begin{proof} Let $\mathcal{L}_e$ be $(\Sigma, X)$. We define $\Gamma_X:=\{\ex{\mu_X(x)}{x}\mid x\in \supp{X}\}$ and $\Lambda_e\in \thr{L}$ as $\Lambda_e^{1}\cup \Lambda_e^{2}$ where \begin{align*} \Lambda_e^{1}\coloneqq\qty{\Gamma_X\vdash \ex{l}{t}\mid l\leq \mu_{B}\qty(e\qty([t]))}\qquad \Lambda_e^{2}\coloneqq\qty{\Gamma_X\vdash [s]\equiv [t]\mid e\qty([t])=e\qty([s])} \end{align*} and $(B, \mu_B)$ is $\mathscr{U}_\Sigma(\mathcal{B})$. Let us show the two implications. \begin{itemize} \item[$\Rightarrow$] Any $\iota:X\rightarrow A$ such that $\mathcal{A}\vDash_\iota \Gamma_X$ defines an arrow $\bar{\iota}(X,\mu_X)\rightarrow \mathscr{U}_\Sigma(\mathcal{A})$. By adjointness we have a homomorphism $h_\iota:\trm{\Sigma}(X,\mu_X)\rightarrow \mathcal{A}$ hence, by hypothesis, there exists $q_\iota:\mathcal{B}\rightarrow \mathcal{A}$ such that $q_\iota\circ e=h_\iota$. Now, notice that (see~\cref{free}, and \cref{init}(4)) $h_\iota([t])=t^\mathcal{A, \iota}$ Take a sequent $\Gamma_X \vdash \psi$ in $\Lambda_e$, we have two cases, depending on $\psi$. \begin{itemize} \item If $\psi=\ex{l}{ t}\in \Lambda^{me}_{e}$ we have \begin{align*} l\leq \mu_B\qty(e\qty([t]))\leq \mu_A\qty(q_\iota\qty(e\qty([t])))=\mu_A\qty(h_\iota\qty([t]))={t}^{\mathcal{A}, \iota} \end{align*} therefore $\mathcal{A}\vDash_{\iota}\psi$. \item If $\phi=[s]\equiv [t]\in \Lambda^{eq}_{e}$ then \begin{align*} {t}^{\mathcal{A}, \iota}=h_\iota\qty([t])=q_\iota\qty(e([t]))=q_\iota\qty(e([s]))=h_\iota\qty([t])={s}^{\mathcal{A}, \iota} \end{align*} and even in this case $\mathcal{A}\vDash_{\iota}\psi$. \end{itemize} \item[$\Leftarrow$] Take $h:\trm{\Sigma}\qty(X,\mu_X)\rightarrow \mathcal{A}$, $\mathscr{U}_\Sigma(h)\circ \eta_{\nabla(X)}$ is an arrow $(X,\mu_X)\rightarrow \mathscr{U}_\Sigma(\mathcal{A})$, so forgetting the fuzzy set structure too gives us an assignment $\iota_h:X\rightarrow A$ such that $\mathcal{A}\vDash_{\iota_h} \Gamma_X$. As before $ h([t])=t^{\mathcal{A}, \iota_h} $ for every $[t]\in \trm{\Sigma}\qty(X,\mu_X)$. Since $\mathcal{A}\in \mode{\Lambda_e}$ we have \begin{itemize} \item $t^{\mathcal{A}, \iota_h}=s^{\mathcal{A}, \iota_h}$ for all terms $t$ and $s$ such that $e([t])=e([s])$; \item $l\leq \mu_A(t^{\mathcal{A}, \iota_h})$ for all terms $t$ such that $l\leq \mu_B(e([t]))$. \end{itemize} So, the function $ q:B\rightarrow A$ which sends $ b\in B$ to $h([t])$ for some $[t]\in e^{-1}(b)$, provides us with an arrow $\mathscr{U}_\Sigma(\mathcal{B})\rightarrow \mathscr{U}_\Sigma(\mathcal{A})$ such that $q\circ e=h$. Now: \begin{equation*} \begin{split} &q\qty(c^{\mathcal{B}})=q\qty(e\qty(c^{\trm{\Sigma}\qty(X,\mu_X)}))\\&=h\qty(c^{\trm{\Sigma}\qty(X,\mu_X)})=c^{\mathcal{A}} \\ \\ \end{split}\quad \begin{split} &q\qty(f^{\mathcal{B}}\qty(b_1,\dots, b_{\ar(f)}))=q\qty(f^{\mathcal{B}}\qty(e\qty(c_1),\dots, \qty(e\qty(c_{\ar(f)}))))\\&=q\qty(e\qty(f^{\trm{\Sigma}\qty(X,\mu_X)}\qty(c_1,\dots,c_{\ar\qty(f)} )))\\&=h\qty(f^{\trm{\Sigma}\qty(X,\mu_X)}\qty(c_1,\dots,c_{\ar\qty(f)} ))= f^{\mathcal{A}}\qty(h\qty(c_1),\dots, h\qty(c_{\ar(f)}))\\&= f^{\mathcal{A}}\qty(q\qty(e\qty(c_1)),\dots, q\qty(e\qty(c_{\ar(f)})))= f^{\mathcal{A}}\qty(q\qty(b_1),\dots, q\qty(b_{\ar(f)})) \end{split} \end{equation*} so we can conclude that $q$ is an arrow of $\alg{\Sigma}$ and we are done. \qedhere \end{itemize} \end{proof} \begin{corollary}\label{tec}For any signature $\Sigma$ and $\mathscr{X}_0$-equation $e:\trma{\Sigma}\qty(X)\rightarrow \mathcal{B}$ there exists an unconditional theory $\Lambda_e$ such that, for any $\Sigma$-algebra $\mathcal{A}$, $ \mathcal{A}\vDash_{\mathscr{X}_0} e$ if and only if $\mathcal{A}\in \modd(\Lambda_e)$. \end{corollary} Finally, from the results above we can easily conclude HSP-like results for $\alg{\Sigma}$. \begin{theorem}\label{hsp} Let $\catname{V}$ be a full subcategory of $\alg{\Sigma}$, then \begin{enumerate} \item $\catname{V}$ is closed under epimorphisms, (small) products and strong monomorphisms if and only if there exists a class of unconditional theories $\qty{\Lambda_e}_{e\in \mathbb{E}}$ such that $\mathcal{A}\in \catname{V}$ if and only if $\mathcal{A}\in \mode{\Lambda_e}$ for all $e\in \mathbb{E}$. \item $\catname{V}$ is closed under split epimorphisms, (small) products and strong monomorphisms if and only if there exists a class of type $\mathsf{E}$ theories $\qty{\Lambda_e}_{e\in \mathbb{E}}$ such that $\mathcal{A}\in \catname{V}$ if and only if $\mathcal{A}\in \mode{\Lambda_e}$ for all $e\in \mathbb{E}$. \end{enumerate} \end{theorem} \begin{proof} This is straightforward in light of \cref{milius}, \cref{te} and \cref{tec}. \end{proof} \begin{remark} We cannot arrange the collection $\{\Lambda_e\}_{e\in \mathbb{E}}$ into a unique theory since a proper class of variables is needed to write down all the necessary sequents. A possible way to deal with this issue is to fix two Grothendieck universes (\cite{williams1969grothendieck}) $\catname{U}_1\subset \catname{U}_2$ and modify the definition of language allowing for a possible class (i.e., an element of $\catname{U}_2$) of variables. All the proof of this paper can be repeated verbatim in this context carefully distinguishing between fuzzy \emph{sets} (i.e., those defined on an element of $\catname{U}_1$) and fuzzy \emph{classes} (i.e., those defined on an element of $\catname{U}_2$). Then the algebras of terms will be a fuzzy class in general but it is possible to show, using the explicit construction, that $\term{\Lambda}(X,\mu_X)$ is a fuzzy set if $X\in\catname{U}_1$ and so we can retain all the results of \cref{sec:fre}. \end{remark} The issue mentioned in the previous remark can be avoided if the family $\{\Lambda_e\}_{e\in\mathbb{E}}$ satisfies a boundedness property about the premises of the sequents belonging to each $\Lambda_e$. \begin{definition} Given a cardinal $\kappa$ we say that a $\mathscr{X}_\mathsf{E}$-equation $e:\trm{\Sigma}(X,\mu_X)\rightarrow \mathcal{B}$ is \emph{$\kappa$-supported} if $\abs{\supp{X}}<\kappa$. \end{definition} \begin{proposition} Let $\catname{V}=\mathcal{V}(\mathbb{E})$ be an $\mathcal{X}_\mathsf{E}$-equational defined subcategory of $\alg{\Sigma}$ and suppose every $e\in \mathbb{E}$ is $\kappa$-supported, then there exists a theory $\Lambda\in \thr{L}$, where $\mathcal{L}=(\Sigma, \kappa)$, such that $\catname{V}=\mode{\Lambda}$. \end{proposition} \begin{proof}For any $e:\trm{\Sigma}(X_e, \mu_{X_e})\rightarrow \mathcal{B}_e$ in $\mathbb{E}$ we can fix an injection $i_e:\supp{X_e}\rightarrow \kappa$ and an extension let $\bar{i}_e:X\rightarrow \kappa$ of it, fix also morphisms $\mathbf{I}^e:\mathcal{L}_e\rightarrow\mathcal{L}$ given by $(\id{\Sigma}, \bar{i}_e)$. Let now $\qty{\Lambda_e}_{e\in \mathbb{E}}$ be the collection of theories given by \cref{tec} and \cref{hsp}, since each $\Lambda_e\in \mathbf{Form}\qty(\mathcal{L}_e)$ we can define $\Lambda$ as $\bigcup_{e\in \mathbb{E}}\mathbf{I}^e_*\qty(\Lambda_e)$. We have to show that $\mathcal{A}\in \catname{V}$ if and only if $\mathcal{A}\in \mode{\Lambda}$. \begin{itemize} \item[$\Rightarrow$] Let $\mathsf{Form}\qty(\mathbf{I}^e)\qty(\Gamma_{X_e}) \vdash \mathsf{Form}\qty(\mathbf{I}^e)\qty(\psi) $ be a sequent in $\Lambda$ and let $\iota:\kappa \rightarrow A$ an assignment such that $\mathcal{A}\vDash_\iota\mathsf{Form}\qty(\mathbf{I}^e)\qty(\Gamma_{X_e})$. By point $3$ of \cref{mrp} this implies $\mathcal{A}\vDash_{\iota \circ \bar{i}_e} \Gamma_{X_e}$, therefore $\mathcal{A}\vDash_{\iota \circ \bar{i}_e} \psi$ and we conclude applying lemma \ref{mrp} again. \item[$\Leftarrow$] If $\mathscr{U}_\Sigma(\mathcal{A})=(\emptyset, \rotatebox[origin=c]{180}{!}_{H})$, ($\rotatebox[origin=c]{180}{!}_H$ being the empty map $\emptyset\rightarrow H$) then there are no assignment $\kappa \rightarrow A$ and so $\mathcal{A}$ is in $\mode{\Lambda}$. In the other cases let $\Gamma_{X_e}\vdash \psi$ be in $\Lambda_e$ and $\iota:X_e\rightarrow A$ such that $\mathcal{A}\vDash_{\iota} \Gamma_{X_e}$, since $A\neq \emptyset$ there exists $\hat{\iota}:\kappa \rightarrow A$ such that $\hat{\iota}\circ \bar{i}_e= \iota$ as in the previous point \cref{mrp} implies $\mathcal{A}\vDash_{\hat{\iota}}\mathsf{Form}\qty(\mathbf{I}^e)\qty(\Gamma_{X_e})$, so $\mathcal{A}\vDash_{\hat{\iota}}\mathsf{Form}\qty(\mathbf{I}^e)\qty(\psi)$ and again this is equivalent to $\mathcal{A}\vDash_{\iota}\psi$.\qedhere \end{itemize} \end{proof} \begin{corollary} $\catname{V}$ is closed under epimorphisms, (small) products and strong monomorphisms if and only if there exists a language $\mathcal{L}$ and an unconditional theory $\Lambda\in \thr{L}$ such that $\catname{V}=\mode{\Lambda}$. \end{corollary} \section{Conclusions and future work}\label{sec:conc} In this paper we have introduced a \emph{fuzzy sequent calculus} to capture equational aspects of fuzzy sets. While equalities are captured by usual equations, information contained in the membership function is captured by \emph{membership proposition} of the form $\ex{l}{t}$, to be interpreted as ``the membership degree of $t$ is at least $l$''. We have used a natural concept of \emph{fuzzy algebras} to provide a sound and complete semantics for such calculus in the sense that a formula is satisfied by all the models of a given theory if and only if it is derivable from it using the rules of our calculus. As in the classical and quantitative contexts, there is a notion of \emph{free model} of a theory $\Lambda$ and thus an associated monad $\term{\Lambda}$ on the category $\fuz{H}$. However, in general Eilenberg-Moore algebras for such monad are not equivalent to models of $\Lambda$, but we have shown that this equivalence holds if $\Lambda$ is \emph{basic}. In this direction it would be interesting to better understand the categorical status of our approach, investigating possible links between our notion of fuzzy theory and $\fuz{H}$-Lawvere theories as introduced in full generality by Nishizawa and Power in \cite{nishizawa2009lawvere}. A difference between the two approaches is that for us arities are simply finite sets, while following \cite{nishizawa2009lawvere} a $\fuz{H}$-Lawvere theory arities would be given by finite fuzzy sets. Finally, using the results provided in \cite{milius2019equational} we have proved that, given a signature $\Sigma$, subcategories of $\alg{\Sigma}$ which are closed under products, strong monomorphisms and epimorphic images correspond precisely with categories of models for \emph{unconditional theories}, i.e. theories axiomatised by sequents without premises. Moreover, using the same results, we have also proved that the categories of models of \emph{theories of type $\mathsf{E}$}, i.e. those whose axioms' premises contain only membership propositions involving variables, are exactly those subcategories closed under products, strong monomorphisms and split epimorphisms. Our category $\fuz{H}$ of fuzzy sets has crisp arrows and crisp equality: arrows are ordinary functions between the underlying sets and equalities can be judged to be either true or false. A way to further ``fuzzifying'' concepts is to use the topos of \emph{$H$-sets} over the frame $H$ introduced in \cite{fourman1979sheaves}: this is equivalent to the topos of sheaves over $H$ and contains $\fuz{H}$ as a (non full) subcategory. By construction, equalities and functions are ``fuzzy''. It would be interesting to study an application of our approach to this context. A promising feature is that in an $H$-set the membership degree function is built-in as simply the equality relation, so it would not be necessary to distinguish between equations and membership propositions. Even more generally, we can replace $H$ with an arbitrary quantale $\mathcal{V}$ and consider the category of sets endowed with a ``$\mathcal{V}$-valued equivalence relation'' \cite{bkp:concur18}.
{'timestamp': '2021-10-22T02:38:51', 'yymm': '2110', 'arxiv_id': '2110.10970', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.10970'}
arxiv
\section{Introduction} Knowledge Graphs (KG) have successfully contributed to a variety of applications, including information retrieval, chatbots\cite{liang2018knowledge}, smart energy systems~\cite{orlandi2019interlinking}. In this work, we explore how to perform weather analysis by querying our climate knowledge graph\footnote{\url{http://jresearch.ucd.ie/linkclimate/}}. The data in our climate knowledge graph is modeled in RDF (Resource Description Framework) following our Climate Analysis (CA) ontology~\cite{wu2021ontology} and is stored in a SPARQL endpoint. The creation of climate KGs provides an interoperable data structure for climate data, which makes the data easily integrated with other domain data modeled by other ontologies across federated endpoints. We use the data from the National Oceanic and Atmospheric Administration (NOAA), a reputable climate data center that provides raw tables (\textit{e.g.} RDB, CSV, JSON) of global climate datasets such as temperature and precipitation~\cite{manandhar2018importance}. The rest of the paper begins by outlining the context for this work, followed by some examples of automated climate analysis. Finally, we conclude the paper describing our future work. \section{Representing Climate Data Using KG} In this section, we include context information about the initial data source NOAA Climate Data and our Climate Analysis Ontology. \paragraph{NOAA Climate Data} The National Oceanic and Atmospheric Administration (NOAA) is a research organization that studies the seas, major rivers, and atmospher \cite{center2012national}. NOAA Climate Data Online (CDO) offers free access to the National Climatic Data Center's (NCDC) database of global historical weather and climate data, as well as station history data\cite{graham2014growing}. The NOAA's RESTful APIs provide access to data in CSV, SSV, JSON, PDF, and NetCDF formats. Our work is based on NOAA climate data\cite{difranzo2011web}. \paragraph{Climate Analysis Ontology} In our research, we use the CA ontology~\cite{wu2021ontology} to model the NOAA daily summary datasets. There are two major classes in the CA ontology: (\textit{i}) Station and (\textit{ii}) Observation. A station is a site that generates climate observations. Geographical factors (longitude and latitude) or literal names can be used to identify a station. An observation is used to describe a climate feature of interest that has been detected that generated by station, the observed value, and the datatype that defines the feature of interest are typically associated with it. \section{Analyzing Climate Data using KG} This section showcases how to write SPARQL queries to gather climate data for study\footnote{In the spirit of reproducible research, all the source code is available at \url{https://github.com/futaoo/sparql-weatheranalysis}.}. The first sub-section lists example SPARQL queries that are executed for producing data sources used by the climate analysis experiments in the second sub-section. \subsection{Data Collection} Listing 1 is the SPARQL query to gather data on the average temperature in Dublin from 1980 to 2019 and Listing 2 is to gain the weather types data in Sculthorpe, England, from 1951 to 1963\footnote{For this older time period, weather types (\textit{e.g} fog, haze) are available for analysis. These are categorical data for which the detailed processing procedure is given in Section~\ref{sec:analysis}.}. \vspace{-0.3cm} \begin{figure}[htb] \centering \includegraphics[width=0.47\textwidth]{listing1.png} \end{figure} \begin{figure}[htb] \centering \includegraphics[width=0.49\textwidth]{listing2.png} \end{figure} \begin{figure}[htb] \centering \includegraphics[width=0.49\textwidth]{listing3.png} \end{figure} \subsection{Use Case I: Variation of monthly temperature} \label{sec:analysis} To analyze the temperature in Dublin (IE) and Manston (UK) from 1980 to 2019, we construct a station-grouped box-plots based on the results (see Fig.~\ref{fig:tprt}). Each packet contains monthly statistics for 40 years daily temperature records. The figure shows that the temperatures in Dublin and Manston reached their highest levels in July and are close in the winter from November to January but in other seasons temperature in Manston is generally a bit higher than Dublin. \begin{figure}[ht!] \centering \includegraphics[width=0.46\textwidth]{Figure1.png} \caption{Monthly temperature in Dublin and Manston from 1980 to 2019} \label{fig:tprt} \end{figure} To analyze the past weather in Sculthorpe, England, we requested the weather type data and used temperature and precipitation data as auxiliary data from our SPARQL endpoint to judge each day's weather condition. The assumption is that a raining day is determined if the data field showing rainfall is accurate and the day's precipitation is greater than 0 and the temperature is greater than 0. Similar decisions are made on snow that when the field describing snowfall is true and the precipitation is greater than 0 and the temperature is low, then we consider the day to be a snowy day. Drizzle day is asserted when the weather type haze is presented as 1. Additionally, a day without data indicating such weather conditions implies that it was a sunny day. \subsection{Use Case II: Distribution of weather type} Finally, we present the strip plot (Fig.~\ref{fig:wtype}) to present the distribution of weather types (rain, fog, drizzle, snow, sun) on every day of the year 1951, 1955, 1959 and 1963. The weather in Sculthorpe was bad most of the time during 1950s as a result of frequent drizzle, fog, and haze, as seen in Fig.~\ref{fig:wtype}. \begin{figure}[ht!] \centering \includegraphics[width=0.48\textwidth]{Figure2.png} \caption{Distribution of days by weather type in Sculthorpe, UK} \label{fig:wtype} \end{figure} \section{Conclusion \& Future Work} In this paper, we demonstrated how to use standards like RDF and SPARQL to obtain knowledge graph data modeled by the CA ontology for climate studies. According to the data type variety, this paper provides two different weather analyses of which the one is based on the statistics on the quantity data about temperature and the other is based on the categorical meteorological records. Both analyses provide basic understanding to the weather conditions in the corresponding cities (\textit{i.e.} Dublin, Manston and Sculthorpe). In the future, we will leverage the power of semantic approaches to enhance the usability of our climate knowledge graph for climate researchers. For instance, integrating additional data sources for more advanced climate studies. \bibliographystyle{IEEEtran.bst}
{'timestamp': '2021-10-22T02:41:49', 'yymm': '2110', 'arxiv_id': '2110.11039', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.11039'}
arxiv
\section{Introduction} \label{section1} Timely status updates play a key role in networked control and monitoring systems. Age of Information (AoI) has recently been introduced to quantify the timeliness of information freshness in status update systems \cite{kaul_etal_SMAN11}. In the general AoI framework outlined in \cite{kosta_etal_survey}, information sources sample a source-specific random process at random epochs and generate information packets containing the sample values as well as the sampling times. On the other hand, servers gather the information packets from multiple sources so as to be transmitted to a remote monitor using queueing, buffer management, scheduling, etc. For a given source, AoI is defined as the time elapsed since the generation of the last successfully received update packet. Therefore, AoI is a source-specific random process whose sample paths increase in time with unit slope but are subject to abrupt downward jumps at information packet reception instances. The PAoI process is obtained by sampling the AoI process just before the cycle termination instances. In this paper, we consider a non-preemptive status update system in Fig.~\ref{fig:twosource} with two sources, a server, and a monitor, with random information packet arrivals from the sources. The server employs Single-Buffer Per-Source queueing (SBPSQ) for which the freshest packet from each source is held in a single buffer. The server is work-conserving, i.e., it does not idle unless the waiting room is empty, and it serves the packets probabilistically (probabilities denoted by $p_i$ in Fig.~\ref{fig:twosource}) when there are two waiting packets. The scheduler is age-agnostic and does not require the server to read the timestamp field in the packets and keep track of the instantaneous AoI values. The scheduling probabilities are to be chosen so as to provide AoI/PAoI differentiation. In this paper, we attempt to provide differentiation through the minimization of the weighted average AoI/PAoI. The motivation behind AoI differentiation is that in a networked control system, the information about certain input processes need to be kept relatively fresher at the control unit since this information will have profound impact on the overall performance of the control system. The studied model falls in the general framework of status update systems analytically studied in the literature; see the surveys on AoI \cite{kosta_etal_survey},\cite{survey_Yates} and the references therein for a collection of multi-source queueing models for AoI. \begin{figure}[tb] \centering \begin{tikzpicture}[scale=0.32] \draw[very thick](3,2) circle (2); \draw (3,4) node[anchor=south] {\small{source-$2$}} ; \draw[very thick] (3,9) circle (2) ; \draw (3,11) node[anchor=south] {\small{source-$1$}} ; \draw[very thick,->] (6,2) -- (10,2) ; \draw (8,2) node[anchor=south] {$\lambda_2$}; \draw[very thick,->] (6,9) -- (10,9) ; \draw (8,9) node[anchor=south] {$\lambda_1$}; \filldraw[fill=gray!50, thick] (13,1) rectangle(15,3); \draw[thick] (11,1) -- (13,1); \draw[thick] (11,3) -- (13,3); \filldraw[fill=gray!50, thick] (13,8) rectangle(15,10); \draw[thick] (11,8) -- (13,8); \draw[thick] (11,10) -- (13,10); \draw[thick,->] (15,2) -- (20,5) ; \draw[thick,->] (15,9) -- (20,6) ; \draw[thick, ->, dashed] (20,3.5) arc (270:90:2) node[anchor=south east] {$p_1$}; \filldraw (20,3.5) circle (0.01) node[anchor=north east] {$p_2$}; \draw[very thick](24,6) circle (3); \filldraw (24,6) circle (0.01) node[anchor=center] {server}; \draw[very thick,->] (28,6) -- (32,6) ; \draw[very thick](33,4) rectangle (40,8); \filldraw (36.5,6) circle (0.01) node[anchor=center] {monitor}; \end{tikzpicture} \caption{A single-hop status update system with two sources employing per-source queueing. A single-buffer queue is dedicated to each source to hold the freshest packet from that source.} \label{fig:twosource} \end{figure} Our main contributions are as follows: \begin{itemize} \item As the main contribution of this paper, under the assumption of Poisson packet arrivals, and exponentially distributed service times, we obtain the exact distributions of the AoI/PAoI processes for the two sources for the system of interest in Fig.~\ref{fig:twosource} as a function of the scheduling probabilities. The analysis is based on well-known absorbing Continuous-Time Markov Chains (CTMC) and does not employ relatively more specific tools such as Stochastic Hybrid Systems (SHS) that were recently proposed for AoI modeling \cite{yates_kaul_tit19} and used in several works. We believe that the simplicity of the tool we use to derive the AoI/PAoI distributions makes it a convenient tool for researchers and practitioners in this field. Subsequently, for given traffic parameters, the proposed analytical model is used to numerically obtain the Optimum Probabilistic Scheduling (OPS) policy which minimizes the weighted average AoI or PAoI, referred to as OPS-A and OPS-P, respectively. \item A heavy-traffic analysis is presented to obtain closed-form expressions for the average per-source AoI/PAoI values which has enabled us to write the OPS-P policy in closed-form in heavy-traffic regime. On the other hand, the OPS-A policy for the heavy-traffic regime is shown to be obtainable by solving a quartic equation. \item On the basis of the heavy-traffic analysis, we propose two age-agnostic heuristic schedulers that are quite easy to implement in comparison with age-aware schedulers and therefore they can be used in more challenging multi-hop scenarios and resource-constrained servers. \end{itemize} The paper is organized as follows. Section~\ref{section2} presents the related work. In Section~\ref{section3}, the analytical model is presented. The heavy-traffic regime is addressed in Section~\ref{section4} along with the two heavy-traffic analysis-based heuristic schedulers. Section~\ref{section5} addresses the analytical model and associated closed-form expressions for the Non-Preemptive Bufferless (NPB) variation of the same problem which is used as a benchmark in the numerical examples. In Section~\ref{section6}, we provide numerical examples for comparative evaluation of the age-agnostic schedulers of interest. We conclude in Section~\ref{section7}. \section{Related Work} \label{section2} There has been a great deal of interest on AoI modeling and optimization problems in the context of communication systems since the reference \cite{kaul_etal_infocom12} first introduced the AoI concept in a single-source, single-server queueing system setting. The existing analytical models can be classified according to one or more of the following: (i) existence of one, two, or more information sources, (ii) random access vs. scheduled access, (iii) existence of transmission errors, (iv) performance metrics used, e.g., average AoI/PAoI values, age violation probabilities, etc., (v) buffer management mechanisms, (vi) scheduling algorithms, (vii) arrival and service processes used in the models, (viii) single-hop vs. multi-hop systems, (ix) continuous-time vs. discrete-time systems. The recent references \cite{kosta_etal_survey} and \cite{survey_Yates} present exhaustive surveys on existing work on AoI and moreover describe several open problems. \subsection{Single-source Queueing Models} The average AoI is obtained for the M/M/1, M/D/1, and D/M/1 queues with infinite buffer capacity and FCFS (First Come First Serve) in \cite{kaul_etal_infocom12}. The reference \cite{costa_etal_TIT16} obtains the AoI and PAoI distributions for small buffer systems, namely M/M/1/1 and M/M/1/2 queues, as well as the non-preemptive LCFS (Last Come First Serve) M/M/1/2$^{\ast}$ queue for which the packet waiting in the queue is replaced by a fresher packet arrival. The average AoI and PAoI are obtained in \cite{najm_nasser_isit16} for the preemptive LCFS M/G/1/1 queueing system where a new arrival preempts the packet in service and the service time distribution is assumed to follow a more general gamma distribution. Average PAoI expressions are derived for an M/M/1 queueing system with packet transmission errors with various buffer management schemes in \cite{chen_huang_isit16}. Expressions for the steady-state distributions of AoI and PAoI are derived in \cite{inoue_etal_tit19} for a wide range of single-source systems. The authors of \cite{akar_etal_tcom20} obtain the exact distributions of AoI and PAoI in bufferless systems with probabilistic preemption and single-buffer systems with probabilistic replacement also allowing general phase type distributions to represent interrarival times and/or service times. \subsection{Multi-source Queueing Models} For analytical models involving multiple sources, the average PAoI for M/G/1 FCFS and bufferless M/G/1/1 systems with heterogeneous service time requirements are derived in \cite{huang_modiano} by which one can optimize the information packet generation rates from the sources. An exact expression for the average AoI for the case of multi-source M/M/1 queueing model under FCFS scheduling is provided in \cite{moltafet2020average} and three approximate expressions are proposed for the average AoI for the more general multi-source M/G/1 queueing model. The reference \cite{yates_kaul_tit19} investigates the multi-source M/M/1 model with FCFS, preemptive bufferless, and non-preemptive single buffer with replacement, using the theory of Stochastic Hybrid Systems (SHS) and obtain exact expressions for the average AoI. Hyperexponential (H$_2$) service time distribution for each source is considered in \cite{yates_etal_isit19} for an M/H$_2$/1/1 non-preemptive bufferless queue to derive an expression for the average per-source AoI per class. The authors of \cite{farazi_etal_Asilomar19} study a self-preemptive system in which preemption of a source in service is allowed by a newly arriving packet from the same source and AoI expressions are derived using the SHS technique. For distributional results, the MGF (Moment Generating Function) of AoI has been derived for a bufferless multi-source status update system using global preemption \cite{moltafet2021moment}. The work in \cite{abdelmagid2021closedform} considers a real-time status update system with an energy harvesting transmitter and derive the MGF of AoI in closed-form under certain queueing disciplines making use of SHS techniques. The authors of \cite{dogan_akar_tcom21} obtain the exact distributions of AoI/PAoI in a probabilistically preemptive bufferless multi-source M/PH/1/1 queue where non-preemptive, globally preemptive, and self-preemptive systems are investigated using a common unifying framework. In \cite{optimumpreemption}, the optimum packet generation rates are obtained for self-preemptive and global preemptive bufferless systems for weighted AoI minimization, the latter case shown to allow closed-form expressions. The most relevant existing analytical modeling work to this paper are the ones that study SBPSQ models for status update systems. The merits of SBPSQ systems are presented in \cite{pappas_etal_ICC15} in terms of lesser transmissions and AoI reduction. The authors of \cite{moltafet_isit} derive the average AoI expressions for a two-source M/M/1/2 queueing system in which a packet waiting in the queue can be replaced only by a newly arriving packet from the same source using SHS techniques. The per-source MGF of the AoI is also obtained \cite{moltafet_wcomlet} for the two-source system by using SHS under self-preemptive and non-preemptive policies, the latter being a per-source queueing system. However, in these works, the order of packets in the queue does not change based on new arrivals and therefore AoI differentiation is not possible. \subsection{Scheduling Algorithms for Random Arrivals} We now review the existing work on AoI scheduling with random arrivals that are related to the scope of the current paper. The authors of \cite{bedewy_etal_tit21} consider the problem of minimizing the age of information in a multi-source system and they show that for any given sampling strategy, the Maximum Age First (MAF) scheduling strategy provides the best age performance among all scheduling strategies. The authors of \cite{joo_eryilmaz_TNET18} propose an age-based scheduler that combines age with the interarrival times of incoming packets, in its scheduling decisions, to achieve improved information freshness at the receiver. Although the analytical results are obtained for only heavy-traffic, their numerical results reveal that the proposed algorithm achieves desirable freshness performance for lighter loads as well. The authors of \cite{kadota_tn18} and \cite{kadota_tmc21} consider an asymmetric (source weights/service times are different) discrete-time wireless network with a base station serving multiple traffic streams using per-source queueing under the assumption of synchronized and random information packet arrivals, respectively, and propose nearly optimal age-based schedulers and age-agnostic randomized schedulers. For the particular vase of random arrivals which is more relevant to the current paper, the reference \cite{kadota_tmc21} proposes a non-work-conserving stationary randomized policy for the single-buffer case with optimal scheduling probabilities depending on the source weights and source success probabilities through a square-root relationship and this policy is independent of the arrival rates. Moreover, they propose a work-conserving age-based Max-Weight scheduler for the same system whose performance is better and is close to the lower bound. We also note that similar results had been obtained in \cite{kadota_tn18} for synchronized arrivals. Our focus in this paper is on work-conserving age-agnostic schedulers that are more suitable for resource-constrained environments and multi-hop scenarios for which it is relatively difficult to keep track of per-source AoI information at the server. \section{Probabilistic Scheduling} \label{section3} \subsection{Definitions of AoI and PAoI} In a very general setting, let $T_j^{(i)}$ and $A_j^{(i)}$ for $j\geq 1$ denote the times at which the $j$th successful source-$i$ packet is received by the monitor and generated at the source, respectively. We also let $\Psi^{(i)}_j$ denote the system time of the $j$th successful source-$i$ information packet which is the sum of the packet's queue wait time and service times, i.e., $\Psi^{(i)}_j=T_j^{(i)} - A_j^{(i)}$. Fig.~\ref{fig:samplepath} depicts a sample path of the source-$i$ AoI process $\Delta^{(i)}(t)$ which increases with unit slope from the value $\Phi_{j}^{(i)}$ at $t=T_{j}^{(i)}$ until $t=T_{j+1}^{(i)}$ in cycle-$j$. The peak value in cycle-$j$ is denoted by $\Psi_{j}^{(i)}$ which represents the Peak AoI process for source-$i$. These definitions apply to general status update systems. Note that for the specific system of Fig.~\ref{fig:twosource}, successful packets are the ones which are received by the monitor, and those that are replaced by fresher incoming packets while at the waiting room are unsuccessful packets. Let $\Delta^{(i)}$ and $\Phi^{(i)}$ denote the steady-state values for the source-$i$ processes $\Delta^{(i)}(t)$ and $\Phi_j^{(i)}$, respectively. The weighted average AoI, $W_{AoI}$, and the weighted average PAoI, $W_{PAoI}$, of the system are written as \begin{equation} W_{AoI} = \sum_{i=1}^2 \omega_i E [ \Delta^{(i)}], \ W_{PAoI}= \sum_{i=1}^2 \omega_i E [ \Phi^{(i)}], \label{W} \end{equation} where $\omega_i, i=1,2,$ with $\omega_1+\omega_2=1$ are the (normalized) weighting coefficients. \subsection{System Model} In this paper, we consider a non-preemptive status update system in Fig.~\ref{fig:twosource} with two sources, a server, and a monitor. Source-$i$, $i=1,2$ generates information packets (containing time-stamped status update information) according to a Poisson process with intensity $\lambda_i$. The generated packets become immediately available at the server. The server maintains two single-buffer queues, namely $Q_i, i=1,2$, that holds the freshest packet from source-$i$. This buffer management is referred to as Single-Buffer Per-Source Queueing (SBPSQ). A newcoming source-$i$ packet receives immediate service if the server is idle and there are no waiting packets, or joins the empty $Q_i$, or replaces the existing staler source-$i$ packet at $Q_i$. The server is work-conserving as a result of which an information packet is immediately transmitted unless the system is idle. Consequently, when the system has one packet waiting at $Q_i$ for $i=1$ or $i=2$ upon the server becoming idle, then this packet from $Q_i$ will immediately be served. When there are two packets waiting at the two queues, then the server is to transmit the packet from $Q_i$ with probability $p_i$ with $p_1 + p_2 =1$. Therefore, the scheduler is age-agnostic and does not require the server to read the timestamp field in the packets and keep track of the instantaneous AoI values. The probabilities $p_i$'s are to be chosen so as to provide AoI/PAoI differentiation. At the end of a single transmission, positive/negative acknowledgments from the monitor to the server are assumed to be immediate, for the sake of convenience. The channel success probability for source-$i$ is $s_i$ and when a packet's transmission gets to start, it will be retransmitted until it is successfully received by the monitor. Therefore, if a single transmission is assumed to be exponentially distributed with parameter $\nu_i$, then the transmission time of successful source-$i$ packets from the server to the monitor are exponentially distributed with parameter $\mu_i = \nu_i s_i$ by taking into account of the retransmissions. With this choice, error-prone channels are also considered in this paper. We define the source-$i$ load as $\rho_i = \frac{\lambda_i}{\mu_i}$ and the total load $\rho = \rho_1+\rho_2$. We also define the traffic mix parameter $r_i$ so that $\rho_i =\rho r_i$, and the traffic mix ratio $r=\frac{r_1}{r_2}$. The studied model falls in the general framework of status update systems analytically studied in the literature; see the surveys on AoI \cite{kosta_etal_survey},\cite{survey_Yates} and the references therein for a collection of multi-source queueing models for AoI. \begin{figure}[t] \centering \begin{tikzpicture}[scale=0.45] \draw[thick,<->,gray] (9,13) -- (16,13); \filldraw (12.5,13) circle (0.01) node[anchor=south, thick] {cycle-$j$}; \draw[ultra thick,->] (0,0) -- (23,0) node[anchor=north] {$t$}; \draw[ultra thick,->] (0,0) -- (0,14) node[anchor=west] {$\Delta^{(i)}(t)$}; \draw[ultra thick,red] (4.5,4.5) -- (9,9); \filldraw[red] (4,4) circle (3pt); \filldraw[red] (3.5,3.5) circle (3pt) ; \filldraw[red] (3,3) circle (3pt); \draw (0,9) node[anchor=east] {$\Phi_{j+1}^{(i)}$}; \draw (0,5) node[anchor=east] {$\Psi_j^{(i)}$}; \draw[dashed,gray] (0,9) -- (23,9); \draw[dashed,gray] (0,5) -- (23,5); \draw[dashed,gray] (0,2) -- (23,2); \draw[dashed,gray] (9,12.5) -- (9,0) node[anchor=north, thick, black] {$T_{j}^{(i)}$}; \draw[dashed,very thick,gray] (9,5) -- (4,0) node[anchor=north, thick, black] {$A_{j}^{(i)}$}; \draw[dashed,very thick, gray] (16,2) -- (14,0) node[anchor=north east, thick, black] {$\quad A_{j+1}^{(i)}$}; \draw[ultra thick,red] (9,9) -- (9,5.2); \draw[ultra thick,red] (9.1,5.1) -- (16,12); \draw (0,12) node[anchor=east] {$\Phi_{j}^{(i)}$}; \draw (0,2) node[anchor=east] {$\Psi_{j+1}^{(i)}$}; \draw[dashed,gray] (16,12.5) -- (16,0) node[anchor=north, thick, black] {$T_{j+1}^{(i)}$}; \draw[dashed,gray] (0,12) -- (23,12); \draw[ultra thick,red] (16,12) -- (16,2.2); \draw[ultra thick,red] (16.1,2.1) -- (20,6); \filldraw[red] (20.5,6.5) circle (3pt); \filldraw[red] (21,7) circle (3pt) ; \filldraw[red] (21.5,7.5) circle (3pt); \draw[red] (9,5) circle (6pt); \draw[red] (16,2) circle (6pt); \end{tikzpicture} \caption{Sample path of the AoI process $\Delta^{(i)}(t)$.} \label{fig:samplepath} \end{figure} The analytical method we propose in the next subsection enables us to obtain the distribution of $\Delta^{(1)}$ and $\Phi^{(1)}$. By renumbering the sources, the distribution of $\Delta^{(2)}$ and $\Phi^{(2)}$ can also be obtained using the same method. \subsection{Queueing Model} \begin{table}[tb] \begin{center} \begin{tabular}{||c|c|c|c||} \hline State & Server & $Q_1$ & $Q_2$ \\ [0.5ex] \hline\hline 1 & I & E & E \\ \hline 2 & B1 & E & E \\ \hline 3 & B1 & F & E \\ \hline 4 & B1 & E & F \\ \hline 5 & B1 & F & F \\ \hline 6 & B2 & E & E \\ \hline 7 & B2 & F & E \\ \hline 8 & B2 & E & F \\ \hline 9 & B2 & F & F \\ [0.1ex] \hline \hline \end{tabular} \end{center} \caption{Description of the 9 states of the CTMC $\bm{X}(t)$. I, E, and F, stand for idle, empty, and full, respectively. B1 (B2) stands for the server being busy serving a source-1 (source-2) packet.} \label{step1} \end{table} The proposed method consists of two main steps. In the first step, we construct an irreducible Continuous Time Markov Chain (CTMC) denoted by $\bm{X}(t)$ with nine states each of which is described in detail in Table~\ref{step1}. The CTMC $\bm{X}(t)$ has the generator matrix $\bm{P}$ where \begin{align} \bm{P_0} & = \begin{pmatrix} 0 & \lambda_1 & 0 & 0 & 0 & \lambda_2 & 0 & 0 & 0 \\ \mu_1 & 0 & 0 & \lambda_1& \lambda_2 & 0 & 0 & 0 & 0 \\ 0 & \mu_1 & 0 & 0 & 0 & \lambda_2 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & \lambda_1 & \mu_1 & 0 & 0 & 0 \\ 0 & 0 & 0 & \mu_1 p_1 & 0 & 0 & \mu_1 p_2 & 0 & 0 \\ \mu_2 & 0 & 0 & 0 & 0 & 0 &\lambda_1 & \lambda_2 &0\\ 0& \mu_2 & 0 & 0 & 0 & 0 & 0 & 0 & \lambda_2 \\ 0& 0 & 0 & 0 & 0 & \mu_2 & 0 & 0 & \lambda_1 \\ 0& 0 & 0 & \mu_2 p_1 & 0 & 0 & \mu_2 p_2 & 0 & 0 \end{pmatrix}, \end{align} and $\bm{P}$ is the same as $\bm{P_0}$ except for its diagonal entries which are set to the corresponding row sums with a minus sign so that $\bm{P} \bm{1} =\bm{0}$ where $\bm{1}$ and $\bm{0}$ are column vectors of ones and zeros, respectively, of appropriate size. Let $\bm{\pi}$ be the stationary solution for $\bm{X}(t)$ so that \begin{align} \bm{\pi} \bm{P} = 0, \ \bm{\pi} \bm{1}=1, \end{align} with $\bm{\pi_j}$ denoting the steady-state probability of any new packet arrival finding the system in state $j$. In the second step of the proposed method, we construct an absorbing CTMC denoted by $\bm{Y}(t)$ with 14 transient states $1,2,\ldots,14$ and two absorbing states $15,16$ which starts to evolve with the arrival of a source-1 packet, say packet $n$ into the system. If this packet turns out to be unsuccessful then we transition to the absorbing state 15. If packet $n$ turns out to be successful, then we evolve until the reception of the next successful packet say $m$ at which point the absorbing state 16 is transitioned to, which is referred to as a successful absorption. The 14 transient states are described in Table~\ref{step2}. \begin{table}[tb] \begin{center} \begin{tabular}{||c|c|c|c|c||} \hline State & Server & Packet $n$ & $Q_1$ & $Q_2$ \\ [0.5ex] \hline\hline 1 & \bf{B1}& N& E & E \\ \hline 2 & \bf{B1} & N & E & E \\ \hline 3 & B1 & N & F & E \\ \hline 4 & \bf{B1} & N & E & F \\ \hline 5 & \bf{B1} & N & F & F \\ \hline 6 & B1 & N & F & F \\ \hline 7 & B2 & N & E & F \\ \hline 8 & B2 & N & F & F \\ \hline 9 & I & Y & E & E \\ \hline 10 & B1 & Y & X & X \\ \hline 11 & B2 & Y & E & E \\ \hline 12 & B2 & Y & F & E \\ \hline 13 & B2 & Y & E & F \\ \hline 14 & B2 & Y & F & F \\ [0.1ex] \hline \hline \end{tabular} \end{center} \caption{Description of the 14 states of the CTMC $\bm{Y}(t)$. I, E, and F, stand for idle, empty, and full, respectively, and B1 (B2) stands for the server being busy serving a source-1 (source-2) packet. The notation {\bf B1} means the particular packet $n$ is being served. N and Y stand for packet $n$ not successful yet and otherwise, respectively, and X is don't care.} \label{step2} \end{table} The generator for the absorbing CTMC, denoted by $\bm{Q}$ is in the form \begin{align} \bm{Q}=\begin{pmatrix} \bm{A} & \bm{u} & \bm{s} \\ \bm{0} & 0 & 0 \\ \bm{0} & 0 & 0 \end{pmatrix}, \end{align} where \begin{align} \bm{A_0} & = \left( \begin{array}{cccccccccccccc} 0 & \lambda_1 & 0 & \lambda_2 & 0 & 0 & 0 & 0 & \mu_1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & \lambda_2 & 0 & 0 & 0 & 0 & \mu_1 & 0 & 0 & 0 & 0 \\ \mu_1 & 0 & 0 & 0 & 0 & \lambda_2 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & \lambda_1 & 0 & 0 & 0 & 0 & 0 & \mu_1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \mu_1 p_1 & 0 & \mu_1 p_2 & 0 & 0 \\ 0 & 0 & 0 & \mu_1 p_1 & 0 & 0 & \mu_1 p_2 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \mu_2 & 0 & 0 & 0 & 0 & 0 & 0 & \lambda_2 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & \mu_2 p_1 & 0 & 0 & \mu_2 p_2 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \lambda_1 & \lambda_2 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \mu_2 &0 &0 & \lambda_1 & \lambda_2 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \mu_2 & 0 & 0 & 0 & \lambda_2 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \mu_2 & 0 & 0 & \lambda_1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \mu_2 p_1 & 0 & \mu_2 p_2 & 0 & 0 \\ \end{array} \right), \bm{u} = \begin{pmatrix} 0 \\ 0 \\ \lambda_1 \\ 0 \\ 0 \\ \lambda_1 \\ \lambda_1 \\ \lambda_1 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \end{pmatrix}, \bm{s} = \begin{pmatrix} 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ \mu_1 \\ 0 \\ 0 \\ 0 \\ 0 \end{pmatrix}, \bm{h} = \begin{pmatrix} 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 1 \\ 1 \\ 1 \\ 1 \\ 1 \\ 1 \end{pmatrix} \label{big} \end{align} $\bm{A}$ is the same as $\bm{A_0}$ in \eqref{big} except for its diagonal entries which are set to the corresponding row sums with a minus sign so that $\bm{A} \bm{1} + \bm{u} + \bm{s}=\bm{0}$. Note that $\bm{A}$ is the sub-generator matrix corresponding to the transient states and $\bm{u}$ and $\bm{s}$ are the transition rate vectors from the transient states to the unsuccessful and successful absorbing states, respectively. The vector $\bm{h}$ which takes the unit value for the indices 9 to 14, and zero otherwise, will be needed in deriving the AoI distribution. The initial probability vector of the CTMC $\bm{Y}(t)$ is denoted by $\bm{\alpha}$ which is given as follows: \begin{align} \bm{\alpha} & = \begin{pmatrix} \bm{\pi_1} & 0 & \bm{\pi_{23}} & \bm{0_{1 \times 2}} & \bm{\pi_{45}} & \bm{\pi_{67}} & \bm{\pi_{89}} & \bm{0_{1 \times 6}} \end{pmatrix}, \end{align} where $\bm{\pi_{ij}} := \bm{\pi_i} + \bm{\pi_j}$. In order to understand this, a new source-1 packet $n$ will find the system idle (state 1 of ${\bm X(t)}$) with probability $\bm{\pi_1}$ and therefore will be placed in service immediately, i.e., state 1 of ${\bm Y(t)}$. Similarly, packet $n$ will find the system in states 2 and 3 of ${\bm X(t)}$ with probability $\bm{\pi_{23}}$ and in either case this packet will start its journey from state 3 of ${\bm Y(t)}$ and so on. With this step, the two CTMCs ${\bm X(t)}$ and ${\bm Y(t)}$ are linked. Let us visit Fig.~\ref{fig:samplepath} and relate it to the absorbing CTMC ${\bm Y(t)}$. The instance $A_{j}^{(i)}$ is the arrival time of packet $n$ of ${\bm Y(t)}$ and $T_{j+1}^{(i)}$ is the reception time of packet $m$. Therefore, the distribution of the absorption times of ${\bm Y(t)}$ in successful absorptions enables us to write the steady-state distribution of the PAoI process. In particular, \begin{align} \Pr \{ \Phi^{(1)} \leq x \} & = \Pr \{ {\bm Y(x)} =16 \ | \ {\bm Y(\infty)} = 16\} \\ & = \frac{\Pr \{ {\bm Y(x)} =16 \}}{\Pr\{ {\bm Y(\infty)} = 16 \} } \end{align} Differentiating this expression with respect to $x$, we obtain the pdf (probability density function) of $\Phi^{(1)}$, denoted by $f_{ \Phi^{(1)}}(x)$, as follows; \begin{align} f_{\Phi^{(1)}}(x) & = \beta \ \bm{\alpha} \mathrm{e}^{\bm{A}x} \bm{s}, \end{align} where $\beta^{-1} =\Pr\{ {\bm Y(\infty)} = 16 \} = -\bm{\alpha} \bm{A^{-1}} \bm{s} $. Revisiting Fig.~\ref{fig:samplepath}, the probability $\Pr \{ x < \Delta^{(1)} \leq x + \delta x \}$ is proportional with $\Pr \{ {\bm Y(x)} \in \cal{S} \}$ with the subset $\cal{S}$ containing the six transient states 9 to 14 of ${\bm Y(t)}$ and the proportionality constant being the reciprocal of the mean holding time in $\cal{S}$ in successful absorptions. Consequently, we write \begin{align} f_{ \Delta^{(1)}}(x) & = \kappa \ \bm{\alpha} \mathrm{e}^{\bm{A}x} \bm{h}, \end{align} where $\kappa^{-1} = -\bm{\alpha} \bm{A^{-1}} \bm{h} $. The $k$th non-central moments of $\Phi^{(1)}$ and $\Delta^{(1)}$ are subsequently very easy to write: \begin{align} E \left[(\Phi^{(1)})^k\right] & = \beta \ \bm{\alpha}( -\bm{A})^{-k-1} \bm{s}, \quad E \left[ (\Delta^{(1)})^k \right] = \kappa \ \bm{\alpha}( -\bm{A})^{-k-1} \bm{h}. \label{momentsPA} \end{align} \section{Heavy-traffic Regime} \label{section4} In this section, we study the so-called heavy-traffic regime, i.e., $\lambda_i \rightarrow \infty$. We first describe the analytical model in this regime along with the closed-form average AoI/PAoI expressions. Subsequently, we propose two heuristic schedulers based on this model that are devised to operate at any load as well as an optimum probabilistic scheduler on the basis of the analytical model of the previous section. \subsection{Analytical Model} In this case, the CTMC in step 1 of the proposed method reduces to one single state corresponding to a busy server with both queues being full since in the heavy-traffic regime, neither the queues can be empty nor the server can be idle. Moreover, the absorbing CTMC with 14 transient and 2 absorbing states reduces to one with 3 transient states and 1 successful absorbing state (the state $\bm{s}$). The transient states 1 and 3 indicate that packet $n$ and packet $m$ are in service, respectively, whereas transient state 2 indicates the transmission of a source-2 packet. Consequently, the matrices characterizing this absorbing CTMC take the following simpler form: \begin{align} \bm{A} & = \left( \begin{array}{ccc} -\mu_1 & \mu_1 p_2 & \mu_1 p_1 \\ 0 & -\mu_2 p_1 & \mu_2 p_1 \\ 0 & 0 & -\mu_1 \end{array} \right), \bm{s} = \begin{pmatrix} 0 \\ 0 \\ \mu_1 \end{pmatrix}, \bm{h} = \begin{pmatrix} 0 \\ 1 \\ 1 \end{pmatrix}, {\bm \alpha}=\begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}^T, \label{small} \end{align} and the expressions in \eqref{momentsPA} are valid for the moments of AoI/PAoI in this heavy-traffic regime. Using the upper-triangular nature of the matrix $\bm{A}$ and \eqref{momentsPA}, it is not difficult to show that \begin{align} E [ \Phi^{(1)}] & = \frac{2}{\mu_1} + \frac{p_2}{\mu_2 p_1}, \ E [ \Phi^{(2)}] = \frac{2}{\mu_2} + \frac{p_1}{\mu_1 p_2}. \label{nail11} \end{align} Defining the probability ratio $p=\frac{p_1}{p_2}$ and the weight ratio $\omega=\frac{\omega_1}{\omega_2}$, the weighted average PAoI simplifies to \begin{align} W_{PAoI} & = \frac{\omega_2}{\mu_1 \mu_2} \left( 2 \omega (\mu_1 + \mu_2) + \omega \mu_1 p^{-1} + \mu_2 p \right) \end{align} Employing the Karush–Kuhn–Tucker (KKT) conditions on this expression and defining $\mu = \frac{\mu_1}{\mu_2}$, the optimum probability ratio that yields the minimum $W_{PAoI}$, denoted by $p_{PAoI}^*$, can easily be shown to satisfy the following: \begin{align} p_{PAoI}^* & \; {\propto } \; \sqrt{\omega \mu}. \label{HL} \end{align} The expression for the average AoI is somewhat more involved: \begin{align} E [ \Delta^{(1)}] & = \frac{1}{\mu_1} + \frac{\mu_2 p_1 + \mu_1}{\mu_1 \mu_2 p_1} - \frac{1}{\mu_2 p_1 + \mu_1 p_2}. \label{nail10} \end{align} A similar expression for $E [ \Delta^{(2)}]$ is easy to write due to symmetry. However, in this case, the KKT conditions for the expression for $W_{AoI}$ give rise to a quartic equation, i.e, 4th degree polynomial equation, for the roots of which closed-form expressions are not available. However, numerical techniques can be used to find the optimum probability ratio minimizing $W_{AoI}$, denoted by $p_{AoI}^*$, in this case. However, for the special case $\mu_1 = \mu_2 = u$, the expression \eqref{nail10} reduces to \begin{align} E [ \Delta^{(1)}] & = \frac{1}{u} + \frac{1}{u p_1}, \ E [ \Delta^{(2)}] = \frac{1}{u} + \frac{1}{u p_2}, \end{align} which are identical to the expressions for $E [ \Phi^{(1)}]$ and $E [ \Phi^{(2)}]$ in \eqref{nail11}, respectively, for the special case $\mu_1 = \mu_2 = u$. Employing KKT conditions on $W_{AoI}$, it is obvious to show that \begin{align} p_{AoI}^* & \; {\propto } \; \sqrt{\omega}. \label{HL2} \end{align} When $\mu_1 \neq \mu_2$, we use exhaustive search to obtain $p_{AoI}^*$ throughout the numerical examples of this paper. \subsection{Proposed Heuristic Schedulers} The focus of this paper is on work-conserving schedulers that are neither age- or timestamp-aware, i.e., the schedulers make a decision only on the source indices of packets in the waiting room, and not on the timestamp information in the packets or the instantaneous ages of the source processes. This allows us to use simple-to-implement scheduling policies without the server having to process the timestamp information included in the information packets. Given the traffic parameters $\lambda_i, \mu_i,$ and the weights $\omega_i$, for $i=1,2$, we first introduce the OPS-P (Optimum Probabilistic Scheduling for PAoI) policy that minimizes the weighted average PAoI of the system given in \eqref{W}. OPS-A (Optimum Probabilistic Scheduling for PAoI) is defined similarly so as to minimize the weighted average AoI in \eqref{W}. We use the analytical model and exhaustive search to obtain OPS-P and OPS-A. Although the analytical model is computationally efficient, one needs to resort to simpler heuristics which may be beneficial especially in situations where the traffic parameters may vary in time and the server may need to update its scheduling policy without having to perform extensive computations. For this purpose, we propose a generic heuristic probabilistic scheduler called H1$(p)$ that employs the probability ratio $p=\frac{p_1}{p_2}, p_1=\frac{p}{1+p}, p_2=\frac{1}{1+p},$ using the information about $\omega$ and $\mu$ only but not the actual arrival rates $\lambda_i, i=1,2$. The second heuristic scheduler we propose is called H2$(p)$ which is obtained by determinizing the probabilistic policy H1$(p)$ as described below. In H2$(p)$, each source-$i$ maintains a bucket $b_i$ so that $b_1 + b_2=0$ at all times. Initially, $b_i=0, i=1,2$. When there are two packets in the waiting room, the source with the larger bucket value $b_i$ is selected for transmission. Every time a source-$1$ packet is transmitted, $b_1$ is decremented by $(1 - p_1)$ and $b_2$ is incremented by $p_2$. Similarly, when a source-$2$ packet is transmitted, $b_2$ is decremented by $(1 - p_2)$ and $b_1$ is incremented by $p_1$. In order for the bucket values not to grow to infinity (which may occur if there are no packet arrivals from a specific source for an extended duration of time), we impose a limit on the absolute values of the buckets, i.e., $| b_i | < B$ where $B$ is called the bucket limit. Note that in the heavy-traffic regime, H2$(p)$ is the determinized version of H1$(p)$. To see this, let $p=1,p_1=p_2=0.5$. In H1$(p)$, a geometrically distributed (with parameter 0.5) number of source-1 packets will be transmitted followed with the transmission of a geometrically distributed (again with parameter 0.5) number of source-2 packets. On the other hand, in H2$(1)$, an alternating pattern arises where a single source-1 packet transmission is to be followed by a single packet-2 transmission, i.e., round-robin scheduling. For both heuristic schedulers, the ratio of source-1 transmissions to source-2 transmissions is kept at $p$ in the heavy-traffic regime, but H2$(p)$ manages to maintain this ratio using deterministic patterns as opposed to being probabilistic. The bucket-based nature of the algorithm enables one to obtain this deterministic pattern for all values of the ratio parameter $p$ which is advantageous especially for average AoI. Moreover, in H2$(p)$, we seek to maintain a probability ratio $p$ of transmissions between the two sources throughout the entire operation of the system whereas this probability ratio is maintained in H1$(p)$ only during times when there are two packets in the waiting room. When we choose $p=p_{PAoI}^*$ with $p_{PAoI}^*$ being the optimum probability ratio in the heavy-traffic regime (see Eqn.~\eqref{HL}), we obtain our two proposed schedulers H1-P (Heuristic 1 Scheduler for PAoI) and H2-P (Heuristic Scheduler 2 for PAoI) for average weighted PAoI minimization, i.e., \begin{align} \text{H1-P} & \equiv \text{H1}(p_{PAoI}^*), \ \text{H2-P} \equiv \text{H2}(p_{PAoI}^*), \end{align} where the notation $\equiv$ is used to denote equivalence. Similarly, we propose two schedulers for average weighted AoI minimization, namely H1-A (Heuristic 1 Scheduler for AoI) and H2-A (Heuristic Scheduler 2 for AoI) , i.e., \begin{align} \text{H1-A} &\equiv \text{H1}(p_{AoI}^*), \ \text{H2-A} \equiv \text{H2}(p_{AoI}^*). \end{align} For two-source networks with $\mu=1$, H1-P $\equiv$ H1-A, and H2-P $\equiv$ H2-A. \section{Analytical Model for the Non-preemptive Bufferless Server} \label{section5} Up to now, we have considered SBPSQ servers with scheduling. In this section, we also study the Non-Preemptive Bufferless (NPB) server for the purpose of using it as a benchmark against the per-source queueing systems of our interest. In the NPB scenario, the newcoming source-$i$ packet is served immediately if the server is idle or is otherwise discarded since there is no waiting room. Actually, an analytical model for AoI and PAoI is recently proposed in \cite{dogan_akar_tcom21} for servers serving a general number of sources with more general phase-type distributed service times, also allowing arbitrary preemption probabilities. In this section, we make use of the model introduced by \cite{dogan_akar_tcom21} to provide closed-form expressions for the average AoI/PAoI for the specific case of two sources, no preemption, and exponentially distributed service times. While doing so, we use absorbing CTMCs as opposed to Markov Fluid Queues (MFQ) used in \cite{dogan_akar_tcom21}. Both yield the same results but ordinary CTMCs of absorbing type are more commonly known and established than MFQs. In this case, the CTMC in step 1 is not needed due to the bufferless nature of the system. Moreover, the absorbing CTMC with 14 transient and 2 absorbing states reduces to one with 4 transient states and 1 absorbing state. The transient states 1 and 4 indicate that packet $n$ and packet $m$ are in service, respectively, whereas in transient state 2, we wait for a packet arrival, and in transient state 3, a source-2 packet is in service. Consequently, the matrices characterizing this absorbing CTMC are written as: \begin{align} \bm{A} & = \left( \begin{array}{cccc} -\mu_1 & \mu_1 & 0 & 0 \\ 0 & -(\lambda_1+\lambda_2) & \lambda_2 & \lambda_1 \\ 0 & \mu_2 & -\mu_2 & 0 \\ 0 & 0 & 0 & -\mu_1 \end{array} \right), \ \bm{s} = \begin{pmatrix} 0 \\ 0 \\ 0 \\ \mu_1 \end{pmatrix},\ \bm{h} = \begin{pmatrix} 0 \\ 1 \\ 1 \\ 1 \end{pmatrix}, \ {\bm \alpha} =\begin{pmatrix} 1 \\ 0 \\ 0 \\ 0 \end{pmatrix}^T, \label{bufferless} \end{align} and the expressions \eqref{momentsPA} can be used for obtaining the moments of AoI/PAoI for the bufferless system. Using \eqref{momentsPA}, for the average per-source PAoI, one can easily show that \begin{align} E [ \Phi^{(1)}] & = \frac{1}{\mu_1} + \frac{(1+\rho)}{\lambda_1}, \ E [ \Phi^{(2)}] = \frac{1}{\mu_2} + \frac{(1+\rho)}{\lambda_2}. \end{align} Recalling the definition of the traffic mix parameter $r_i$ and the traffic mix ratio $r=\frac{r_1}{r_2}$, the weighted average PAoI can be written in terms of $r_1$ as follows: \begin{align} W_{PAoI} & = \frac{\omega_1}{\mu_1} + \frac{\omega_2}{\mu_2} + \frac{\omega_1(1+\rho)}{\rho r_1 \mu_1} + \frac{\omega_2(1+\rho)}{\rho (1-r_1) \mu_2}. \end{align} Fixing $\rho$ and employing the KKT conditions for this expression, the optimum traffic mix ratio, denoted by $r_{PAoI}^*$, is given as: \begin{align} r_{PAoI}^* & \; {\propto } \; \sqrt{\frac{\omega}{\mu}}. \label{optimum_mix_ratio} \end{align} Note that the above ratio does not depend on the load parameter $\rho$. If we define the arrival rate ratio $\lambda = \frac{\lambda_1}{\lambda_2}$, then the optimum arrival rate ratio, denoted by $\lambda_{PAoI}^*$, can be written as: \begin{align} \lambda_{PAoI}^* & \; {\propto } \; \sqrt{{\omega}{\mu}}. \label{optimum_arrivalrate_ratio} \end{align} The expression for the average AoI can be written as: \begin{align} E [ \Delta^{(1)}] & = \frac{1}{\mu_1 \mu_2} \left( {\mu_2} + \frac{\mu_2}{\rho_1} + \frac{\lambda_2}{\rho_1} + \frac{\mu_2 \rho_1 + \mu_1 \rho_2}{(1+\rho)} \right) . \end{align} A similar expression for $E [ \Delta^{(2)}]$ is again very easy to write due to symmetry. However, in this case, the KKT conditions for the expression for $W_{AoI}$ again result in a quartic equation in which case numerical techniques can be used to find the optimum traffic mix ratio denoted by $r_{AoI}^*$. \section{Numerical Examples} \label{section6} \subsection{Heavy-traffic Scenario} In the first numerical example, we study the heavy-traffic regime and we depict the corresponding optimum probability ratio parameters $p_{PAoI}^*$ and $p_{AoI}^*$ as a function of the square root of the weight ratio parameter, $\sqrt{\omega}$, for three values of the service rate ratio parameter $\mu$ in Fig.~\ref{fig:ornek1}. When the service rates of the two sources are identical, then these probability ratios are the same for both AoI and PAoI. However, when the service rate ratio starts to deviate from unity, then the optimum probability ratio parameters for PAoI and AoI turn out to deviate from each other. More specifically, $p_{AoI}^* < p_{PAoI}^*$ when $\mu < 1$ and $p_{AoI}^* > p_{PAoI}^*$ when $\mu > 1$. Subsequently, we study whether one can use the easily obtainable $p_{PAoI}^*$ in Eqn.~\eqref{HL} in place of $p_{AoI}^*$ when the minimization of weighted AoI is sought. Fig.~\ref{fig:ornek1b} depicts the ratio of $W_{AoI}$ obtained with the use of the probability ratio $p_{PAoI}^*$ to that obtained using $p_{AoI}^*$ as a function of the weight ratio $\omega$. We observe that $p_{PAoI}^*$ can be used in place of $p_{AoI}^*$ only when the rate ratio $\mu$ and the weight ratio $w$ are both close to unity. It is clear that when $\mu=1$, the depicted ratio in Fig.~\ref{fig:ornek1b} is always one irrespective of $\omega$; also see \eqref{HL2}. \begin{figure}[bth] \centering \includegraphics[width=0.7\linewidth]{ornek1.pdf} \caption{The probability ratio parameters $p_{PAoI}^*$ and $p_{AoI}^*$ as a function of the square root of the weight ratio parameter, $\sqrt{\omega}$, for three values of the service rate ratio parameter $\mu$. } \label{fig:ornek1} \end{figure} \begin{figure}[bth] \centering \includegraphics[width=0.7\linewidth]{ornek1b.pdf} \caption{The ratio of $W_{AoI}$ obtained with the use of $p_{PAoI}^*$ to that using $p_{AoI}^*$ as a function of the weight ratio parameter, ${\omega}$, for five values of the service rate ratio parameter $\mu$. } \label{fig:ornek1b} \end{figure} \subsection{Numerical Study of the Proposed Schedulers} A two-source network is called symmetric when $\omega=1, \ \mu=1$ in \cite{kadota_tmc21} and is asymmetric otherwise. We first present our numerical results for symmetric networks and subsequently, asymmetric network results are presented first for weighted average PAoI minimation, and then for weighted average AoI minimization. We fix $\mu_2=1$ in all the numerical examples. Thus, one time unit is taken as the average service time of source-2 packets. All the results are obtained through the analytical models developed in this paper except for the bucket-based H2-P and H2-A for which an analytical model is cumbersome to build for all values of the probability parameter $p$ and therefore we resorted to simulations. \subsection{Symmetric Network} The weighted average PAoI or AoI are depicted in Fig.~\ref{fig:symmetricexample} as a function of the traffix mix parameter $r$ on a log-log scale for two values of the load $\rho$ using the four schedulers OPS-P(A), NPB, H1-P(A), and H2-P(A) and note that H1-P $\equiv$ H1-A and H2-P $\equiv$ H2-A for symmetric networks. We have the following observations about symmetric networks: \begin{itemize} \item For symmetric networks, the optimum traffic mix should be unity due to symmetry. The discrepancy between NPB and the other SBPSQ systems is reduced as $r \rightarrow 1$ and it vanishes as $r \rightarrow 1$ and $\rho \rightarrow \infty$. However, for moderate loads and when $r$ deviates from unity, SBPSQ has substantial advantages compared to NPB. \item The proposed heuristic schedulers are developed without the knowledge of load and traffic mix using only heavy-traffic conditions. However, we observe through numerical results that the heuristic schedulers perform very close to that obtained by the computation-intensive optimum probabilistic scheduler. This observation is in line with those made in \cite{joo_eryilmaz_TNET18}. \item H2-P (H2-A) presents very similar performance to OPS-P (OPS-A) for all the load and traffic mix values we have obtained whereas H1-P and H1-A are slightly outperformed by them except for light and heavy loads. We also note that there are even cases when H2-A outperforms OPS-A in the high load regime when $r \rightarrow 1$. This stems from the fact that in the heavy-traffic regime, determinized source scheduling strategies perform better than their corresponding probabilistic counterparts for AoI. However, this observation does not necessarily apply to PAoI. \end{itemize} \begin{figure} \centering \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$W_{PAoI}$ ($\rho=1$)} \vspace*{-0.3cm} \includegraphics[width=\textwidth]{SymmetricExample1} \label{fig:symmetric1} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$W_{AoI}$ ($\rho=1$)} \vspace*{-0.3cm} \includegraphics[width=\textwidth]{SymmetricExample2} \label{fig:symmetric2} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$W_{PAoI}$ ($\rho=10$)} \vspace*{-0.3cm} \includegraphics[width=\textwidth]{SymmetricExample3} \label{fig:symmetric3} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$W_{AoI}$ ($\rho=10$)} \vspace*{-0.3cm} \includegraphics[width=\textwidth]{SymmetricExample4} \label{fig:symmetric4} \end{subfigure} \caption{The weighted average PAoI or AoI as a function the traffic mix parameter $r$ for two values of the load $\rho$.} \label{fig:symmetricexample} \end{figure} \subsection{Asymmetric Network - Weighted Average PAoI Minimization} In this numerical example, we depict $W_{PAoI}$ as a function of the load $\rho$ (on a log-log scale) employing four different buffer management/scheduling mechanisms, namely OPS-P, NPB, H1-P, and H2-P in Fig.~\ref{fig:PAoIexample} for which we fix $\omega=4$ and $\mu=4$. In Fig.~\ref{fig:PAoIexample1}, for given load $\rho$, we choose $\rho_i = \rho r_{PAoI}^*$ where the traffic mix ratio $r_{PAoI}^*=1$ as given in \eqref{optimum_mix_ratio}. This choice ensures that source-$i$ packet generation intensities are chosen such that NBP performance is maximized in terms of $W_{PAoI}$. On the other hand, for Fig.~\ref{fig:PAoIexample2}, we fix $r=1/4$, a choice which is quite different than the choice $r_{PAoI}^*=1$ giving rise to a scenario for which the arrival rate selections are not as consistent with the weights and average service rates as in Fig.~\ref{fig:PAoIexample1}. The following observations are made for this example. \begin{itemize} \item If the per-source packet arrival rates are chosen to optimize NBP as in Fig.~\ref{fig:PAoIexample1}, then the discrepancy between NPB and the other three SBPSQ systems is reduced especially for light and heavy loads. For this scenario, there are moderate load values at which NPB outperformed H1-P but OPS-P and H2-P always outperformed NPB in all the cases we had investigated. \item When the arrival rates deviate from the the optimum values derived for NPB as in Fig.~\ref{fig:PAoIexample2}, then the advantage of using SBPSQ with respect to NBP is magnified. Therefore, one can conclude that the sensitivity of the performance of SBPSQ systems to the specific choice of the arrival rates are lower than that of NPB. \item The performance of H2-P is quite similar to that of OPS-P for all the values we had tried both of which slightly outperform H1-P. We conclude that H2-P depends only on the knowledge on $\omega$ and $\mu$ and does not use the load and traffic mix. However, H2-P can safely be used at all loads and all traffic mixes as a simple-to-implement alternative to OPS-P for weighted PAoI minimization. \end{itemize} \begin{figure} \centering \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$\omega=4, \ \mu=4, \ r=1$}\vspace*{-0.2cm} \includegraphics[width=\textwidth]{PAoIexample1} \label{fig:PAoIexample1} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$\omega=4, \ \mu=4, \ r=1/4$} \vspace*{-0.2cm} \includegraphics[width=\textwidth]{PAoIexample2} \label{fig:PAoIexample2} \end{subfigure} \caption{$W_{PAoI}$ depicted as a function of the total load $\rho$ obtained with the algorithms OPS-P, NPB, H1-P, and H2-P for two different scenarios.} \label{fig:PAoIexample} \end{figure} \subsection{Asymmetric Network - Weighted Average AoI Minimization} In this example, we continue with the same example of the previous subsection but we focus on $W_{AoI}$ which is plotted as a function of the load $\rho$ (on a log-log scale) under the policies OPS-A, NPB, H1-A, and H2-A, in Fig.~\ref{fig:AoIexample} with $\omega=4$ and $\mu=4$. The traffic mix parameter $r$ is fixed to $r=1$ and $r=1/4$ in Fig.~\ref{fig:AoIexample1} and Fig.~\ref{fig:AoIexample2}, respectively. We have the following observations: \begin{itemize} \item The OPS-A curve is not monotonically decreasing with respect to load $\rho$ as in OPS-P for the two values of the traffic mix parameter $r$ we have studied; it first decreases until a certain load threshold is reached but then it slightly rises up to its heavy-traffic limit obtained with the probability ratio $p_{AoI}^*$. The corresponding load threshold value appears to depend on the traffic mix. \item The H2-P policy tracks the performance of OPS-A until the load threshold is reached but when the load ranges between the load threshold and infinity, H2-P outperforms OPS-A. This observation does not pertain to the results obtained for weighted average PAoI minimization. \end{itemize} \begin{figure} \centering \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$\omega=4, \ \mu=4, \ r=1$}\vspace*{-0.2cm} \includegraphics[width=\textwidth]{AoIexample1} \label{fig:AoIexample1} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$\omega=4, \ \mu=4, \ r=1/4$} \vspace*{-0.2cm} \includegraphics[width=\textwidth]{AoIexample2} \label{fig:AoIexample2} \end{subfigure} \caption{$W_{AoI}$ depicted as a function of the total load $\rho$ obtained with the algorithms OPS-A, NPB, H1-A, and H2-A for two different scenarios.} \label{fig:AoIexample} \end{figure} \section{Conclusions} \label{section7} We studied a two-source SBPSQ-based status update system with probabilistic scheduling and we proposed a method to obtain the distributions and moments of AoI and PAoI numerically using CTMCs of absorbing-type. The proposed technique is quite simple to implement making it amenable to use for a wider range of analytical modeling problems regarding AoI/PAoI distributions. Moreover, we performed heavy-traffic analysis for the same scenario to obtain closed form expressions for the per-source average AoI/PAoI values from which we have proposed two simple-to-implement age-agnostic heuristic schedulers. The proposed heuristic schedulers are developed without the knowledge of load and traffic mix using only heavy-traffic conditions. However, we observed through numerical results that the heuristic schedulers perform very close to that obtained by their computation-intensive optimum probabilistic scheduler counterparts and at all loads and traffic mixes. In particular, for weighted AoI minimization, our proposed heuristic scheduler H2-A's performance tracked that of the optimum probabilistic scheduler OPS-A except for heavy loads where it even outperformed OPS-A. For weighted PAoI minimization, our proposed heuristic scheduler H2-P's performance tracked that of the optimum probabilistic scheduler OPS-P. Therefore, H2-A and H2-P are promising candidates for scheduling in SBPSQ systems stemming from their performance and age-agnostic nature. Future work will be on extending the results to general number of sources and non-exponentially distributed service times, and also to discrete-time. \bibliographystyle{unsrtnat} \section{Introduction} \label{section1} Timely status updates play a key role in networked control and monitoring systems. Age of Information (AoI) has recently been introduced to quantify the timeliness of information freshness in status update systems \cite{kaul_etal_SMAN11}. In the general AoI framework outlined in \cite{kosta_etal_survey}, information sources sample a source-specific random process at random epochs and generate information packets containing the sample values as well as the sampling times. On the other hand, servers gather the information packets from multiple sources so as to be transmitted to a remote monitor using queueing, buffer management, scheduling, etc. For a given source, AoI is defined as the time elapsed since the generation of the last successfully received update packet. Therefore, AoI is a source-specific random process whose sample paths increase in time with unit slope but are subject to abrupt downward jumps at information packet reception instances. The PAoI process is obtained by sampling the AoI process just before the cycle termination instances. In this paper, we consider a non-preemptive status update system in Fig.~\ref{fig:twosource} with two sources, a server, and a monitor, with random information packet arrivals from the sources. The server employs Single-Buffer Per-Source queueing (SBPSQ) for which the freshest packet from each source is held in a single buffer. The server is work-conserving, i.e., it does not idle unless the waiting room is empty, and it serves the packets probabilistically (probabilities denoted by $p_i$ in Fig.~\ref{fig:twosource}) when there are two waiting packets. The scheduler is age-agnostic and does not require the server to read the timestamp field in the packets and keep track of the instantaneous AoI values. The scheduling probabilities are to be chosen so as to provide AoI/PAoI differentiation. In this paper, we attempt to provide differentiation through the minimization of the weighted average AoI/PAoI. The motivation behind AoI differentiation is that in a networked control system, the information about certain input processes need to be kept relatively fresher at the control unit since this information will have profound impact on the overall performance of the control system. The studied model falls in the general framework of status update systems analytically studied in the literature; see the surveys on AoI \cite{kosta_etal_survey},\cite{survey_Yates} and the references therein for a collection of multi-source queueing models for AoI. \begin{figure}[tb] \centering \begin{tikzpicture}[scale=0.32] \draw[very thick](3,2) circle (2); \draw (3,4) node[anchor=south] {\small{source-$2$}} ; \draw[very thick] (3,9) circle (2) ; \draw (3,11) node[anchor=south] {\small{source-$1$}} ; \draw[very thick,->] (6,2) -- (10,2) ; \draw (8,2) node[anchor=south] {$\lambda_2$}; \draw[very thick,->] (6,9) -- (10,9) ; \draw (8,9) node[anchor=south] {$\lambda_1$}; \filldraw[fill=gray!50, thick] (13,1) rectangle(15,3); \draw[thick] (11,1) -- (13,1); \draw[thick] (11,3) -- (13,3); \filldraw[fill=gray!50, thick] (13,8) rectangle(15,10); \draw[thick] (11,8) -- (13,8); \draw[thick] (11,10) -- (13,10); \draw[thick,->] (15,2) -- (20,5) ; \draw[thick,->] (15,9) -- (20,6) ; \draw[thick, ->, dashed] (20,3.5) arc (270:90:2) node[anchor=south east] {$p_1$}; \filldraw (20,3.5) circle (0.01) node[anchor=north east] {$p_2$}; \draw[very thick](24,6) circle (3); \filldraw (24,6) circle (0.01) node[anchor=center] {server}; \draw[very thick,->] (28,6) -- (32,6) ; \draw[very thick](33,4) rectangle (40,8); \filldraw (36.5,6) circle (0.01) node[anchor=center] {monitor}; \end{tikzpicture} \caption{A single-hop status update system with two sources employing per-source queueing. A single-buffer queue is dedicated to each source to hold the freshest packet from that source.} \label{fig:twosource} \end{figure} Our main contributions are as follows: \begin{itemize} \item As the main contribution of this paper, under the assumption of Poisson packet arrivals, and exponentially distributed service times, we obtain the exact distributions of the AoI/PAoI processes for the two sources for the system of interest in Fig.~\ref{fig:twosource} as a function of the scheduling probabilities. The analysis is based on well-known absorbing Continuous-Time Markov Chains (CTMC) and does not employ relatively more specific tools such as Stochastic Hybrid Systems (SHS) that were recently proposed for AoI modeling \cite{yates_kaul_tit19} and used in several works. We believe that the simplicity of the tool we use to derive the AoI/PAoI distributions makes it a convenient tool for researchers and practitioners in this field. Subsequently, for given traffic parameters, the proposed analytical model is used to numerically obtain the Optimum Probabilistic Scheduling (OPS) policy which minimizes the weighted average AoI or PAoI, referred to as OPS-A and OPS-P, respectively. \item A heavy-traffic analysis is presented to obtain closed-form expressions for the average per-source AoI/PAoI values which has enabled us to write the OPS-P policy in closed-form in heavy-traffic regime. On the other hand, the OPS-A policy for the heavy-traffic regime is shown to be obtainable by solving a quartic equation. \item On the basis of the heavy-traffic analysis, we propose two age-agnostic heuristic schedulers that are quite easy to implement in comparison with age-aware schedulers and therefore they can be used in more challenging multi-hop scenarios and resource-constrained servers. \end{itemize} The paper is organized as follows. Section~\ref{section2} presents the related work. In Section~\ref{section3}, the analytical model is presented. The heavy-traffic regime is addressed in Section~\ref{section4} along with the two heavy-traffic analysis-based heuristic schedulers. Section~\ref{section5} addresses the analytical model and associated closed-form expressions for the Non-Preemptive Bufferless (NPB) variation of the same problem which is used as a benchmark in the numerical examples. In Section~\ref{section6}, we provide numerical examples for comparative evaluation of the age-agnostic schedulers of interest. We conclude in Section~\ref{section7}. \section{Related Work} \label{section2} There has been a great deal of interest on AoI modeling and optimization problems in the context of communication systems since the reference \cite{kaul_etal_infocom12} first introduced the AoI concept in a single-source, single-server queueing system setting. The existing analytical models can be classified according to one or more of the following: (i) existence of one, two, or more information sources, (ii) random access vs. scheduled access, (iii) existence of transmission errors, (iv) performance metrics used, e.g., average AoI/PAoI values, age violation probabilities, etc., (v) buffer management mechanisms, (vi) scheduling algorithms, (vii) arrival and service processes used in the models, (viii) single-hop vs. multi-hop systems, (ix) continuous-time vs. discrete-time systems. The recent references \cite{kosta_etal_survey} and \cite{survey_Yates} present exhaustive surveys on existing work on AoI and moreover describe several open problems. \subsection{Single-source Queueing Models} The average AoI is obtained for the M/M/1, M/D/1, and D/M/1 queues with infinite buffer capacity and FCFS (First Come First Serve) in \cite{kaul_etal_infocom12}. The reference \cite{costa_etal_TIT16} obtains the AoI and PAoI distributions for small buffer systems, namely M/M/1/1 and M/M/1/2 queues, as well as the non-preemptive LCFS (Last Come First Serve) M/M/1/2$^{\ast}$ queue for which the packet waiting in the queue is replaced by a fresher packet arrival. The average AoI and PAoI are obtained in \cite{najm_nasser_isit16} for the preemptive LCFS M/G/1/1 queueing system where a new arrival preempts the packet in service and the service time distribution is assumed to follow a more general gamma distribution. Average PAoI expressions are derived for an M/M/1 queueing system with packet transmission errors with various buffer management schemes in \cite{chen_huang_isit16}. Expressions for the steady-state distributions of AoI and PAoI are derived in \cite{inoue_etal_tit19} for a wide range of single-source systems. The authors of \cite{akar_etal_tcom20} obtain the exact distributions of AoI and PAoI in bufferless systems with probabilistic preemption and single-buffer systems with probabilistic replacement also allowing general phase type distributions to represent interrarival times and/or service times. \subsection{Multi-source Queueing Models} For analytical models involving multiple sources, the average PAoI for M/G/1 FCFS and bufferless M/G/1/1 systems with heterogeneous service time requirements are derived in \cite{huang_modiano} by which one can optimize the information packet generation rates from the sources. An exact expression for the average AoI for the case of multi-source M/M/1 queueing model under FCFS scheduling is provided in \cite{moltafet2020average} and three approximate expressions are proposed for the average AoI for the more general multi-source M/G/1 queueing model. The reference \cite{yates_kaul_tit19} investigates the multi-source M/M/1 model with FCFS, preemptive bufferless, and non-preemptive single buffer with replacement, using the theory of Stochastic Hybrid Systems (SHS) and obtain exact expressions for the average AoI. Hyperexponential (H$_2$) service time distribution for each source is considered in \cite{yates_etal_isit19} for an M/H$_2$/1/1 non-preemptive bufferless queue to derive an expression for the average per-source AoI per class. The authors of \cite{farazi_etal_Asilomar19} study a self-preemptive system in which preemption of a source in service is allowed by a newly arriving packet from the same source and AoI expressions are derived using the SHS technique. For distributional results, the MGF (Moment Generating Function) of AoI has been derived for a bufferless multi-source status update system using global preemption \cite{moltafet2021moment}. The work in \cite{abdelmagid2021closedform} considers a real-time status update system with an energy harvesting transmitter and derive the MGF of AoI in closed-form under certain queueing disciplines making use of SHS techniques. The authors of \cite{dogan_akar_tcom21} obtain the exact distributions of AoI/PAoI in a probabilistically preemptive bufferless multi-source M/PH/1/1 queue where non-preemptive, globally preemptive, and self-preemptive systems are investigated using a common unifying framework. In \cite{optimumpreemption}, the optimum packet generation rates are obtained for self-preemptive and global preemptive bufferless systems for weighted AoI minimization, the latter case shown to allow closed-form expressions. The most relevant existing analytical modeling work to this paper are the ones that study SBPSQ models for status update systems. The merits of SBPSQ systems are presented in \cite{pappas_etal_ICC15} in terms of lesser transmissions and AoI reduction. The authors of \cite{moltafet_isit} derive the average AoI expressions for a two-source M/M/1/2 queueing system in which a packet waiting in the queue can be replaced only by a newly arriving packet from the same source using SHS techniques. The per-source MGF of the AoI is also obtained \cite{moltafet_wcomlet} for the two-source system by using SHS under self-preemptive and non-preemptive policies, the latter being a per-source queueing system. However, in these works, the order of packets in the queue does not change based on new arrivals and therefore AoI differentiation is not possible. \subsection{Scheduling Algorithms for Random Arrivals} We now review the existing work on AoI scheduling with random arrivals that are related to the scope of the current paper. The authors of \cite{bedewy_etal_tit21} consider the problem of minimizing the age of information in a multi-source system and they show that for any given sampling strategy, the Maximum Age First (MAF) scheduling strategy provides the best age performance among all scheduling strategies. The authors of \cite{joo_eryilmaz_TNET18} propose an age-based scheduler that combines age with the interarrival times of incoming packets, in its scheduling decisions, to achieve improved information freshness at the receiver. Although the analytical results are obtained for only heavy-traffic, their numerical results reveal that the proposed algorithm achieves desirable freshness performance for lighter loads as well. The authors of \cite{kadota_tn18} and \cite{kadota_tmc21} consider an asymmetric (source weights/service times are different) discrete-time wireless network with a base station serving multiple traffic streams using per-source queueing under the assumption of synchronized and random information packet arrivals, respectively, and propose nearly optimal age-based schedulers and age-agnostic randomized schedulers. For the particular vase of random arrivals which is more relevant to the current paper, the reference \cite{kadota_tmc21} proposes a non-work-conserving stationary randomized policy for the single-buffer case with optimal scheduling probabilities depending on the source weights and source success probabilities through a square-root relationship and this policy is independent of the arrival rates. Moreover, they propose a work-conserving age-based Max-Weight scheduler for the same system whose performance is better and is close to the lower bound. We also note that similar results had been obtained in \cite{kadota_tn18} for synchronized arrivals. Our focus in this paper is on work-conserving age-agnostic schedulers that are more suitable for resource-constrained environments and multi-hop scenarios for which it is relatively difficult to keep track of per-source AoI information at the server. \section{Probabilistic Scheduling} \label{section3} \subsection{Definitions of AoI and PAoI} In a very general setting, let $T_j^{(i)}$ and $A_j^{(i)}$ for $j\geq 1$ denote the times at which the $j$th successful source-$i$ packet is received by the monitor and generated at the source, respectively. We also let $\Psi^{(i)}_j$ denote the system time of the $j$th successful source-$i$ information packet which is the sum of the packet's queue wait time and service times, i.e., $\Psi^{(i)}_j=T_j^{(i)} - A_j^{(i)}$. Fig.~\ref{fig:samplepath} depicts a sample path of the source-$i$ AoI process $\Delta^{(i)}(t)$ which increases with unit slope from the value $\Phi_{j}^{(i)}$ at $t=T_{j}^{(i)}$ until $t=T_{j+1}^{(i)}$ in cycle-$j$. The peak value in cycle-$j$ is denoted by $\Psi_{j}^{(i)}$ which represents the Peak AoI process for source-$i$. These definitions apply to general status update systems. Note that for the specific system of Fig.~\ref{fig:twosource}, successful packets are the ones which are received by the monitor, and those that are replaced by fresher incoming packets while at the waiting room are unsuccessful packets. Let $\Delta^{(i)}$ and $\Phi^{(i)}$ denote the steady-state values for the source-$i$ processes $\Delta^{(i)}(t)$ and $\Phi_j^{(i)}$, respectively. The weighted average AoI, $W_{AoI}$, and the weighted average PAoI, $W_{PAoI}$, of the system are written as \begin{equation} W_{AoI} = \sum_{i=1}^2 \omega_i E [ \Delta^{(i)}], \ W_{PAoI}= \sum_{i=1}^2 \omega_i E [ \Phi^{(i)}], \label{W} \end{equation} where $\omega_i, i=1,2,$ with $\omega_1+\omega_2=1$ are the (normalized) weighting coefficients. \subsection{System Model} In this paper, we consider a non-preemptive status update system in Fig.~\ref{fig:twosource} with two sources, a server, and a monitor. Source-$i$, $i=1,2$ generates information packets (containing time-stamped status update information) according to a Poisson process with intensity $\lambda_i$. The generated packets become immediately available at the server. The server maintains two single-buffer queues, namely $Q_i, i=1,2$, that holds the freshest packet from source-$i$. This buffer management is referred to as Single-Buffer Per-Source Queueing (SBPSQ). A newcoming source-$i$ packet receives immediate service if the server is idle and there are no waiting packets, or joins the empty $Q_i$, or replaces the existing staler source-$i$ packet at $Q_i$. The server is work-conserving as a result of which an information packet is immediately transmitted unless the system is idle. Consequently, when the system has one packet waiting at $Q_i$ for $i=1$ or $i=2$ upon the server becoming idle, then this packet from $Q_i$ will immediately be served. When there are two packets waiting at the two queues, then the server is to transmit the packet from $Q_i$ with probability $p_i$ with $p_1 + p_2 =1$. Therefore, the scheduler is age-agnostic and does not require the server to read the timestamp field in the packets and keep track of the instantaneous AoI values. The probabilities $p_i$'s are to be chosen so as to provide AoI/PAoI differentiation. At the end of a single transmission, positive/negative acknowledgments from the monitor to the server are assumed to be immediate, for the sake of convenience. The channel success probability for source-$i$ is $s_i$ and when a packet's transmission gets to start, it will be retransmitted until it is successfully received by the monitor. Therefore, if a single transmission is assumed to be exponentially distributed with parameter $\nu_i$, then the transmission time of successful source-$i$ packets from the server to the monitor are exponentially distributed with parameter $\mu_i = \nu_i s_i$ by taking into account of the retransmissions. With this choice, error-prone channels are also considered in this paper. We define the source-$i$ load as $\rho_i = \frac{\lambda_i}{\mu_i}$ and the total load $\rho = \rho_1+\rho_2$. We also define the traffic mix parameter $r_i$ so that $\rho_i =\rho r_i$, and the traffic mix ratio $r=\frac{r_1}{r_2}$. The studied model falls in the general framework of status update systems analytically studied in the literature; see the surveys on AoI \cite{kosta_etal_survey},\cite{survey_Yates} and the references therein for a collection of multi-source queueing models for AoI. \begin{figure}[t] \centering \begin{tikzpicture}[scale=0.45] \draw[thick,<->,gray] (9,13) -- (16,13); \filldraw (12.5,13) circle (0.01) node[anchor=south, thick] {cycle-$j$}; \draw[ultra thick,->] (0,0) -- (23,0) node[anchor=north] {$t$}; \draw[ultra thick,->] (0,0) -- (0,14) node[anchor=west] {$\Delta^{(i)}(t)$}; \draw[ultra thick,red] (4.5,4.5) -- (9,9); \filldraw[red] (4,4) circle (3pt); \filldraw[red] (3.5,3.5) circle (3pt) ; \filldraw[red] (3,3) circle (3pt); \draw (0,9) node[anchor=east] {$\Phi_{j+1}^{(i)}$}; \draw (0,5) node[anchor=east] {$\Psi_j^{(i)}$}; \draw[dashed,gray] (0,9) -- (23,9); \draw[dashed,gray] (0,5) -- (23,5); \draw[dashed,gray] (0,2) -- (23,2); \draw[dashed,gray] (9,12.5) -- (9,0) node[anchor=north, thick, black] {$T_{j}^{(i)}$}; \draw[dashed,very thick,gray] (9,5) -- (4,0) node[anchor=north, thick, black] {$A_{j}^{(i)}$}; \draw[dashed,very thick, gray] (16,2) -- (14,0) node[anchor=north east, thick, black] {$\quad A_{j+1}^{(i)}$}; \draw[ultra thick,red] (9,9) -- (9,5.2); \draw[ultra thick,red] (9.1,5.1) -- (16,12); \draw (0,12) node[anchor=east] {$\Phi_{j}^{(i)}$}; \draw (0,2) node[anchor=east] {$\Psi_{j+1}^{(i)}$}; \draw[dashed,gray] (16,12.5) -- (16,0) node[anchor=north, thick, black] {$T_{j+1}^{(i)}$}; \draw[dashed,gray] (0,12) -- (23,12); \draw[ultra thick,red] (16,12) -- (16,2.2); \draw[ultra thick,red] (16.1,2.1) -- (20,6); \filldraw[red] (20.5,6.5) circle (3pt); \filldraw[red] (21,7) circle (3pt) ; \filldraw[red] (21.5,7.5) circle (3pt); \draw[red] (9,5) circle (6pt); \draw[red] (16,2) circle (6pt); \end{tikzpicture} \caption{Sample path of the AoI process $\Delta^{(i)}(t)$.} \label{fig:samplepath} \end{figure} The analytical method we propose in the next subsection enables us to obtain the distribution of $\Delta^{(1)}$ and $\Phi^{(1)}$. By renumbering the sources, the distribution of $\Delta^{(2)}$ and $\Phi^{(2)}$ can also be obtained using the same method. \subsection{Queueing Model} \begin{table}[tb] \begin{center} \begin{tabular}{||c|c|c|c||} \hline State & Server & $Q_1$ & $Q_2$ \\ [0.5ex] \hline\hline 1 & I & E & E \\ \hline 2 & B1 & E & E \\ \hline 3 & B1 & F & E \\ \hline 4 & B1 & E & F \\ \hline 5 & B1 & F & F \\ \hline 6 & B2 & E & E \\ \hline 7 & B2 & F & E \\ \hline 8 & B2 & E & F \\ \hline 9 & B2 & F & F \\ [0.1ex] \hline \hline \end{tabular} \end{center} \caption{Description of the 9 states of the CTMC $\bm{X}(t)$. I, E, and F, stand for idle, empty, and full, respectively. B1 (B2) stands for the server being busy serving a source-1 (source-2) packet.} \label{step1} \end{table} The proposed method consists of two main steps. In the first step, we construct an irreducible Continuous Time Markov Chain (CTMC) denoted by $\bm{X}(t)$ with nine states each of which is described in detail in Table~\ref{step1}. The CTMC $\bm{X}(t)$ has the generator matrix $\bm{P}$ where \begin{align} \bm{P_0} & = \begin{pmatrix} 0 & \lambda_1 & 0 & 0 & 0 & \lambda_2 & 0 & 0 & 0 \\ \mu_1 & 0 & 0 & \lambda_1& \lambda_2 & 0 & 0 & 0 & 0 \\ 0 & \mu_1 & 0 & 0 & 0 & \lambda_2 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & \lambda_1 & \mu_1 & 0 & 0 & 0 \\ 0 & 0 & 0 & \mu_1 p_1 & 0 & 0 & \mu_1 p_2 & 0 & 0 \\ \mu_2 & 0 & 0 & 0 & 0 & 0 &\lambda_1 & \lambda_2 &0\\ 0& \mu_2 & 0 & 0 & 0 & 0 & 0 & 0 & \lambda_2 \\ 0& 0 & 0 & 0 & 0 & \mu_2 & 0 & 0 & \lambda_1 \\ 0& 0 & 0 & \mu_2 p_1 & 0 & 0 & \mu_2 p_2 & 0 & 0 \end{pmatrix}, \end{align} and $\bm{P}$ is the same as $\bm{P_0}$ except for its diagonal entries which are set to the corresponding row sums with a minus sign so that $\bm{P} \bm{1} =\bm{0}$ where $\bm{1}$ and $\bm{0}$ are column vectors of ones and zeros, respectively, of appropriate size. Let $\bm{\pi}$ be the stationary solution for $\bm{X}(t)$ so that \begin{align} \bm{\pi} \bm{P} = 0, \ \bm{\pi} \bm{1}=1, \end{align} with $\bm{\pi_j}$ denoting the steady-state probability of any new packet arrival finding the system in state $j$. In the second step of the proposed method, we construct an absorbing CTMC denoted by $\bm{Y}(t)$ with 14 transient states $1,2,\ldots,14$ and two absorbing states $15,16$ which starts to evolve with the arrival of a source-1 packet, say packet $n$ into the system. If this packet turns out to be unsuccessful then we transition to the absorbing state 15. If packet $n$ turns out to be successful, then we evolve until the reception of the next successful packet say $m$ at which point the absorbing state 16 is transitioned to, which is referred to as a successful absorption. The 14 transient states are described in Table~\ref{step2}. \begin{table}[tb] \begin{center} \begin{tabular}{||c|c|c|c|c||} \hline State & Server & Packet $n$ & $Q_1$ & $Q_2$ \\ [0.5ex] \hline\hline 1 & \bf{B1}& N& E & E \\ \hline 2 & \bf{B1} & N & E & E \\ \hline 3 & B1 & N & F & E \\ \hline 4 & \bf{B1} & N & E & F \\ \hline 5 & \bf{B1} & N & F & F \\ \hline 6 & B1 & N & F & F \\ \hline 7 & B2 & N & E & F \\ \hline 8 & B2 & N & F & F \\ \hline 9 & I & Y & E & E \\ \hline 10 & B1 & Y & X & X \\ \hline 11 & B2 & Y & E & E \\ \hline 12 & B2 & Y & F & E \\ \hline 13 & B2 & Y & E & F \\ \hline 14 & B2 & Y & F & F \\ [0.1ex] \hline \hline \end{tabular} \end{center} \caption{Description of the 14 states of the CTMC $\bm{Y}(t)$. I, E, and F, stand for idle, empty, and full, respectively, and B1 (B2) stands for the server being busy serving a source-1 (source-2) packet. The notation {\bf B1} means the particular packet $n$ is being served. N and Y stand for packet $n$ not successful yet and otherwise, respectively, and X is don't care.} \label{step2} \end{table} The generator for the absorbing CTMC, denoted by $\bm{Q}$ is in the form \begin{align} \bm{Q}=\begin{pmatrix} \bm{A} & \bm{u} & \bm{s} \\ \bm{0} & 0 & 0 \\ \bm{0} & 0 & 0 \end{pmatrix}, \end{align} where \begin{align} \bm{A_0} & = \left( \begin{array}{cccccccccccccc} 0 & \lambda_1 & 0 & \lambda_2 & 0 & 0 & 0 & 0 & \mu_1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & \lambda_2 & 0 & 0 & 0 & 0 & \mu_1 & 0 & 0 & 0 & 0 \\ \mu_1 & 0 & 0 & 0 & 0 & \lambda_2 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & \lambda_1 & 0 & 0 & 0 & 0 & 0 & \mu_1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \mu_1 p_1 & 0 & \mu_1 p_2 & 0 & 0 \\ 0 & 0 & 0 & \mu_1 p_1 & 0 & 0 & \mu_1 p_2 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \mu_2 & 0 & 0 & 0 & 0 & 0 & 0 & \lambda_2 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & \mu_2 p_1 & 0 & 0 & \mu_2 p_2 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \lambda_1 & \lambda_2 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \mu_2 &0 &0 & \lambda_1 & \lambda_2 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \mu_2 & 0 & 0 & 0 & \lambda_2 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \mu_2 & 0 & 0 & \lambda_1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \mu_2 p_1 & 0 & \mu_2 p_2 & 0 & 0 \\ \end{array} \right), \bm{u} = \begin{pmatrix} 0 \\ 0 \\ \lambda_1 \\ 0 \\ 0 \\ \lambda_1 \\ \lambda_1 \\ \lambda_1 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \end{pmatrix}, \bm{s} = \begin{pmatrix} 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ \mu_1 \\ 0 \\ 0 \\ 0 \\ 0 \end{pmatrix}, \bm{h} = \begin{pmatrix} 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 1 \\ 1 \\ 1 \\ 1 \\ 1 \\ 1 \end{pmatrix} \label{big} \end{align} $\bm{A}$ is the same as $\bm{A_0}$ in \eqref{big} except for its diagonal entries which are set to the corresponding row sums with a minus sign so that $\bm{A} \bm{1} + \bm{u} + \bm{s}=\bm{0}$. Note that $\bm{A}$ is the sub-generator matrix corresponding to the transient states and $\bm{u}$ and $\bm{s}$ are the transition rate vectors from the transient states to the unsuccessful and successful absorbing states, respectively. The vector $\bm{h}$ which takes the unit value for the indices 9 to 14, and zero otherwise, will be needed in deriving the AoI distribution. The initial probability vector of the CTMC $\bm{Y}(t)$ is denoted by $\bm{\alpha}$ which is given as follows: \begin{align} \bm{\alpha} & = \begin{pmatrix} \bm{\pi_1} & 0 & \bm{\pi_{23}} & \bm{0_{1 \times 2}} & \bm{\pi_{45}} & \bm{\pi_{67}} & \bm{\pi_{89}} & \bm{0_{1 \times 6}} \end{pmatrix}, \end{align} where $\bm{\pi_{ij}} := \bm{\pi_i} + \bm{\pi_j}$. In order to understand this, a new source-1 packet $n$ will find the system idle (state 1 of ${\bm X(t)}$) with probability $\bm{\pi_1}$ and therefore will be placed in service immediately, i.e., state 1 of ${\bm Y(t)}$. Similarly, packet $n$ will find the system in states 2 and 3 of ${\bm X(t)}$ with probability $\bm{\pi_{23}}$ and in either case this packet will start its journey from state 3 of ${\bm Y(t)}$ and so on. With this step, the two CTMCs ${\bm X(t)}$ and ${\bm Y(t)}$ are linked. Let us visit Fig.~\ref{fig:samplepath} and relate it to the absorbing CTMC ${\bm Y(t)}$. The instance $A_{j}^{(i)}$ is the arrival time of packet $n$ of ${\bm Y(t)}$ and $T_{j+1}^{(i)}$ is the reception time of packet $m$. Therefore, the distribution of the absorption times of ${\bm Y(t)}$ in successful absorptions enables us to write the steady-state distribution of the PAoI process. In particular, \begin{align} \Pr \{ \Phi^{(1)} \leq x \} & = \Pr \{ {\bm Y(x)} =16 \ | \ {\bm Y(\infty)} = 16\} \\ & = \frac{\Pr \{ {\bm Y(x)} =16 \}}{\Pr\{ {\bm Y(\infty)} = 16 \} } \end{align} Differentiating this expression with respect to $x$, we obtain the pdf (probability density function) of $\Phi^{(1)}$, denoted by $f_{ \Phi^{(1)}}(x)$, as follows; \begin{align} f_{\Phi^{(1)}}(x) & = \beta \ \bm{\alpha} \mathrm{e}^{\bm{A}x} \bm{s}, \end{align} where $\beta^{-1} =\Pr\{ {\bm Y(\infty)} = 16 \} = -\bm{\alpha} \bm{A^{-1}} \bm{s} $. Revisiting Fig.~\ref{fig:samplepath}, the probability $\Pr \{ x < \Delta^{(1)} \leq x + \delta x \}$ is proportional with $\Pr \{ {\bm Y(x)} \in \cal{S} \}$ with the subset $\cal{S}$ containing the six transient states 9 to 14 of ${\bm Y(t)}$ and the proportionality constant being the reciprocal of the mean holding time in $\cal{S}$ in successful absorptions. Consequently, we write \begin{align} f_{ \Delta^{(1)}}(x) & = \kappa \ \bm{\alpha} \mathrm{e}^{\bm{A}x} \bm{h}, \end{align} where $\kappa^{-1} = -\bm{\alpha} \bm{A^{-1}} \bm{h} $. The $k$th non-central moments of $\Phi^{(1)}$ and $\Delta^{(1)}$ are subsequently very easy to write: \begin{align} E \left[(\Phi^{(1)})^k\right] & = \beta \ \bm{\alpha}( -\bm{A})^{-k-1} \bm{s}, \quad E \left[ (\Delta^{(1)})^k \right] = \kappa \ \bm{\alpha}( -\bm{A})^{-k-1} \bm{h}. \label{momentsPA} \end{align} \section{Heavy-traffic Regime} \label{section4} In this section, we study the so-called heavy-traffic regime, i.e., $\lambda_i \rightarrow \infty$. We first describe the analytical model in this regime along with the closed-form average AoI/PAoI expressions. Subsequently, we propose two heuristic schedulers based on this model that are devised to operate at any load as well as an optimum probabilistic scheduler on the basis of the analytical model of the previous section. \subsection{Analytical Model} In this case, the CTMC in step 1 of the proposed method reduces to one single state corresponding to a busy server with both queues being full since in the heavy-traffic regime, neither the queues can be empty nor the server can be idle. Moreover, the absorbing CTMC with 14 transient and 2 absorbing states reduces to one with 3 transient states and 1 successful absorbing state (the state $\bm{s}$). The transient states 1 and 3 indicate that packet $n$ and packet $m$ are in service, respectively, whereas transient state 2 indicates the transmission of a source-2 packet. Consequently, the matrices characterizing this absorbing CTMC take the following simpler form: \begin{align} \bm{A} & = \left( \begin{array}{ccc} -\mu_1 & \mu_1 p_2 & \mu_1 p_1 \\ 0 & -\mu_2 p_1 & \mu_2 p_1 \\ 0 & 0 & -\mu_1 \end{array} \right), \bm{s} = \begin{pmatrix} 0 \\ 0 \\ \mu_1 \end{pmatrix}, \bm{h} = \begin{pmatrix} 0 \\ 1 \\ 1 \end{pmatrix}, {\bm \alpha}=\begin{pmatrix} 1 \\ 0 \\ 0 \end{pmatrix}^T, \label{small} \end{align} and the expressions in \eqref{momentsPA} are valid for the moments of AoI/PAoI in this heavy-traffic regime. Using the upper-triangular nature of the matrix $\bm{A}$ and \eqref{momentsPA}, it is not difficult to show that \begin{align} E [ \Phi^{(1)}] & = \frac{2}{\mu_1} + \frac{p_2}{\mu_2 p_1}, \ E [ \Phi^{(2)}] = \frac{2}{\mu_2} + \frac{p_1}{\mu_1 p_2}. \label{nail11} \end{align} Defining the probability ratio $p=\frac{p_1}{p_2}$ and the weight ratio $\omega=\frac{\omega_1}{\omega_2}$, the weighted average PAoI simplifies to \begin{align} W_{PAoI} & = \frac{\omega_2}{\mu_1 \mu_2} \left( 2 \omega (\mu_1 + \mu_2) + \omega \mu_1 p^{-1} + \mu_2 p \right) \end{align} Employing the Karush–Kuhn–Tucker (KKT) conditions on this expression and defining $\mu = \frac{\mu_1}{\mu_2}$, the optimum probability ratio that yields the minimum $W_{PAoI}$, denoted by $p_{PAoI}^*$, can easily be shown to satisfy the following: \begin{align} p_{PAoI}^* & \; {\propto } \; \sqrt{\omega \mu}. \label{HL} \end{align} The expression for the average AoI is somewhat more involved: \begin{align} E [ \Delta^{(1)}] & = \frac{1}{\mu_1} + \frac{\mu_2 p_1 + \mu_1}{\mu_1 \mu_2 p_1} - \frac{1}{\mu_2 p_1 + \mu_1 p_2}. \label{nail10} \end{align} A similar expression for $E [ \Delta^{(2)}]$ is easy to write due to symmetry. However, in this case, the KKT conditions for the expression for $W_{AoI}$ give rise to a quartic equation, i.e, 4th degree polynomial equation, for the roots of which closed-form expressions are not available. However, numerical techniques can be used to find the optimum probability ratio minimizing $W_{AoI}$, denoted by $p_{AoI}^*$, in this case. However, for the special case $\mu_1 = \mu_2 = u$, the expression \eqref{nail10} reduces to \begin{align} E [ \Delta^{(1)}] & = \frac{1}{u} + \frac{1}{u p_1}, \ E [ \Delta^{(2)}] = \frac{1}{u} + \frac{1}{u p_2}, \end{align} which are identical to the expressions for $E [ \Phi^{(1)}]$ and $E [ \Phi^{(2)}]$ in \eqref{nail11}, respectively, for the special case $\mu_1 = \mu_2 = u$. Employing KKT conditions on $W_{AoI}$, it is obvious to show that \begin{align} p_{AoI}^* & \; {\propto } \; \sqrt{\omega}. \label{HL2} \end{align} When $\mu_1 \neq \mu_2$, we use exhaustive search to obtain $p_{AoI}^*$ throughout the numerical examples of this paper. \subsection{Proposed Heuristic Schedulers} The focus of this paper is on work-conserving schedulers that are neither age- or timestamp-aware, i.e., the schedulers make a decision only on the source indices of packets in the waiting room, and not on the timestamp information in the packets or the instantaneous ages of the source processes. This allows us to use simple-to-implement scheduling policies without the server having to process the timestamp information included in the information packets. Given the traffic parameters $\lambda_i, \mu_i,$ and the weights $\omega_i$, for $i=1,2$, we first introduce the OPS-P (Optimum Probabilistic Scheduling for PAoI) policy that minimizes the weighted average PAoI of the system given in \eqref{W}. OPS-A (Optimum Probabilistic Scheduling for PAoI) is defined similarly so as to minimize the weighted average AoI in \eqref{W}. We use the analytical model and exhaustive search to obtain OPS-P and OPS-A. Although the analytical model is computationally efficient, one needs to resort to simpler heuristics which may be beneficial especially in situations where the traffic parameters may vary in time and the server may need to update its scheduling policy without having to perform extensive computations. For this purpose, we propose a generic heuristic probabilistic scheduler called H1$(p)$ that employs the probability ratio $p=\frac{p_1}{p_2}, p_1=\frac{p}{1+p}, p_2=\frac{1}{1+p},$ using the information about $\omega$ and $\mu$ only but not the actual arrival rates $\lambda_i, i=1,2$. The second heuristic scheduler we propose is called H2$(p)$ which is obtained by determinizing the probabilistic policy H1$(p)$ as described below. In H2$(p)$, each source-$i$ maintains a bucket $b_i$ so that $b_1 + b_2=0$ at all times. Initially, $b_i=0, i=1,2$. When there are two packets in the waiting room, the source with the larger bucket value $b_i$ is selected for transmission. Every time a source-$1$ packet is transmitted, $b_1$ is decremented by $(1 - p_1)$ and $b_2$ is incremented by $p_2$. Similarly, when a source-$2$ packet is transmitted, $b_2$ is decremented by $(1 - p_2)$ and $b_1$ is incremented by $p_1$. In order for the bucket values not to grow to infinity (which may occur if there are no packet arrivals from a specific source for an extended duration of time), we impose a limit on the absolute values of the buckets, i.e., $| b_i | < B$ where $B$ is called the bucket limit. Note that in the heavy-traffic regime, H2$(p)$ is the determinized version of H1$(p)$. To see this, let $p=1,p_1=p_2=0.5$. In H1$(p)$, a geometrically distributed (with parameter 0.5) number of source-1 packets will be transmitted followed with the transmission of a geometrically distributed (again with parameter 0.5) number of source-2 packets. On the other hand, in H2$(1)$, an alternating pattern arises where a single source-1 packet transmission is to be followed by a single packet-2 transmission, i.e., round-robin scheduling. For both heuristic schedulers, the ratio of source-1 transmissions to source-2 transmissions is kept at $p$ in the heavy-traffic regime, but H2$(p)$ manages to maintain this ratio using deterministic patterns as opposed to being probabilistic. The bucket-based nature of the algorithm enables one to obtain this deterministic pattern for all values of the ratio parameter $p$ which is advantageous especially for average AoI. Moreover, in H2$(p)$, we seek to maintain a probability ratio $p$ of transmissions between the two sources throughout the entire operation of the system whereas this probability ratio is maintained in H1$(p)$ only during times when there are two packets in the waiting room. When we choose $p=p_{PAoI}^*$ with $p_{PAoI}^*$ being the optimum probability ratio in the heavy-traffic regime (see Eqn.~\eqref{HL}), we obtain our two proposed schedulers H1-P (Heuristic 1 Scheduler for PAoI) and H2-P (Heuristic Scheduler 2 for PAoI) for average weighted PAoI minimization, i.e., \begin{align} \text{H1-P} & \equiv \text{H1}(p_{PAoI}^*), \ \text{H2-P} \equiv \text{H2}(p_{PAoI}^*), \end{align} where the notation $\equiv$ is used to denote equivalence. Similarly, we propose two schedulers for average weighted AoI minimization, namely H1-A (Heuristic 1 Scheduler for AoI) and H2-A (Heuristic Scheduler 2 for AoI) , i.e., \begin{align} \text{H1-A} &\equiv \text{H1}(p_{AoI}^*), \ \text{H2-A} \equiv \text{H2}(p_{AoI}^*). \end{align} For two-source networks with $\mu=1$, H1-P $\equiv$ H1-A, and H2-P $\equiv$ H2-A. \section{Analytical Model for the Non-preemptive Bufferless Server} \label{section5} Up to now, we have considered SBPSQ servers with scheduling. In this section, we also study the Non-Preemptive Bufferless (NPB) server for the purpose of using it as a benchmark against the per-source queueing systems of our interest. In the NPB scenario, the newcoming source-$i$ packet is served immediately if the server is idle or is otherwise discarded since there is no waiting room. Actually, an analytical model for AoI and PAoI is recently proposed in \cite{dogan_akar_tcom21} for servers serving a general number of sources with more general phase-type distributed service times, also allowing arbitrary preemption probabilities. In this section, we make use of the model introduced by \cite{dogan_akar_tcom21} to provide closed-form expressions for the average AoI/PAoI for the specific case of two sources, no preemption, and exponentially distributed service times. While doing so, we use absorbing CTMCs as opposed to Markov Fluid Queues (MFQ) used in \cite{dogan_akar_tcom21}. Both yield the same results but ordinary CTMCs of absorbing type are more commonly known and established than MFQs. In this case, the CTMC in step 1 is not needed due to the bufferless nature of the system. Moreover, the absorbing CTMC with 14 transient and 2 absorbing states reduces to one with 4 transient states and 1 absorbing state. The transient states 1 and 4 indicate that packet $n$ and packet $m$ are in service, respectively, whereas in transient state 2, we wait for a packet arrival, and in transient state 3, a source-2 packet is in service. Consequently, the matrices characterizing this absorbing CTMC are written as: \begin{align} \bm{A} & = \left( \begin{array}{cccc} -\mu_1 & \mu_1 & 0 & 0 \\ 0 & -(\lambda_1+\lambda_2) & \lambda_2 & \lambda_1 \\ 0 & \mu_2 & -\mu_2 & 0 \\ 0 & 0 & 0 & -\mu_1 \end{array} \right), \ \bm{s} = \begin{pmatrix} 0 \\ 0 \\ 0 \\ \mu_1 \end{pmatrix},\ \bm{h} = \begin{pmatrix} 0 \\ 1 \\ 1 \\ 1 \end{pmatrix}, \ {\bm \alpha} =\begin{pmatrix} 1 \\ 0 \\ 0 \\ 0 \end{pmatrix}^T, \label{bufferless} \end{align} and the expressions \eqref{momentsPA} can be used for obtaining the moments of AoI/PAoI for the bufferless system. Using \eqref{momentsPA}, for the average per-source PAoI, one can easily show that \begin{align} E [ \Phi^{(1)}] & = \frac{1}{\mu_1} + \frac{(1+\rho)}{\lambda_1}, \ E [ \Phi^{(2)}] = \frac{1}{\mu_2} + \frac{(1+\rho)}{\lambda_2}. \end{align} Recalling the definition of the traffic mix parameter $r_i$ and the traffic mix ratio $r=\frac{r_1}{r_2}$, the weighted average PAoI can be written in terms of $r_1$ as follows: \begin{align} W_{PAoI} & = \frac{\omega_1}{\mu_1} + \frac{\omega_2}{\mu_2} + \frac{\omega_1(1+\rho)}{\rho r_1 \mu_1} + \frac{\omega_2(1+\rho)}{\rho (1-r_1) \mu_2}. \end{align} Fixing $\rho$ and employing the KKT conditions for this expression, the optimum traffic mix ratio, denoted by $r_{PAoI}^*$, is given as: \begin{align} r_{PAoI}^* & \; {\propto } \; \sqrt{\frac{\omega}{\mu}}. \label{optimum_mix_ratio} \end{align} Note that the above ratio does not depend on the load parameter $\rho$. If we define the arrival rate ratio $\lambda = \frac{\lambda_1}{\lambda_2}$, then the optimum arrival rate ratio, denoted by $\lambda_{PAoI}^*$, can be written as: \begin{align} \lambda_{PAoI}^* & \; {\propto } \; \sqrt{{\omega}{\mu}}. \label{optimum_arrivalrate_ratio} \end{align} The expression for the average AoI can be written as: \begin{align} E [ \Delta^{(1)}] & = \frac{1}{\mu_1 \mu_2} \left( {\mu_2} + \frac{\mu_2}{\rho_1} + \frac{\lambda_2}{\rho_1} + \frac{\mu_2 \rho_1 + \mu_1 \rho_2}{(1+\rho)} \right) . \end{align} A similar expression for $E [ \Delta^{(2)}]$ is again very easy to write due to symmetry. However, in this case, the KKT conditions for the expression for $W_{AoI}$ again result in a quartic equation in which case numerical techniques can be used to find the optimum traffic mix ratio denoted by $r_{AoI}^*$. \section{Numerical Examples} \label{section6} \subsection{Heavy-traffic Scenario} In the first numerical example, we study the heavy-traffic regime and we depict the corresponding optimum probability ratio parameters $p_{PAoI}^*$ and $p_{AoI}^*$ as a function of the square root of the weight ratio parameter, $\sqrt{\omega}$, for three values of the service rate ratio parameter $\mu$ in Fig.~\ref{fig:ornek1}. When the service rates of the two sources are identical, then these probability ratios are the same for both AoI and PAoI. However, when the service rate ratio starts to deviate from unity, then the optimum probability ratio parameters for PAoI and AoI turn out to deviate from each other. More specifically, $p_{AoI}^* < p_{PAoI}^*$ when $\mu < 1$ and $p_{AoI}^* > p_{PAoI}^*$ when $\mu > 1$. Subsequently, we study whether one can use the easily obtainable $p_{PAoI}^*$ in Eqn.~\eqref{HL} in place of $p_{AoI}^*$ when the minimization of weighted AoI is sought. Fig.~\ref{fig:ornek1b} depicts the ratio of $W_{AoI}$ obtained with the use of the probability ratio $p_{PAoI}^*$ to that obtained using $p_{AoI}^*$ as a function of the weight ratio $\omega$. We observe that $p_{PAoI}^*$ can be used in place of $p_{AoI}^*$ only when the rate ratio $\mu$ and the weight ratio $w$ are both close to unity. It is clear that when $\mu=1$, the depicted ratio in Fig.~\ref{fig:ornek1b} is always one irrespective of $\omega$; also see \eqref{HL2}. \begin{figure}[bth] \centering \includegraphics[width=0.7\linewidth]{ornek1.pdf} \caption{The probability ratio parameters $p_{PAoI}^*$ and $p_{AoI}^*$ as a function of the square root of the weight ratio parameter, $\sqrt{\omega}$, for three values of the service rate ratio parameter $\mu$. } \label{fig:ornek1} \end{figure} \begin{figure}[bth] \centering \includegraphics[width=0.7\linewidth]{ornek1b.pdf} \caption{The ratio of $W_{AoI}$ obtained with the use of $p_{PAoI}^*$ to that using $p_{AoI}^*$ as a function of the weight ratio parameter, ${\omega}$, for five values of the service rate ratio parameter $\mu$. } \label{fig:ornek1b} \end{figure} \subsection{Numerical Study of the Proposed Schedulers} A two-source network is called symmetric when $\omega=1, \ \mu=1$ in \cite{kadota_tmc21} and is asymmetric otherwise. We first present our numerical results for symmetric networks and subsequently, asymmetric network results are presented first for weighted average PAoI minimation, and then for weighted average AoI minimization. We fix $\mu_2=1$ in all the numerical examples. Thus, one time unit is taken as the average service time of source-2 packets. All the results are obtained through the analytical models developed in this paper except for the bucket-based H2-P and H2-A for which an analytical model is cumbersome to build for all values of the probability parameter $p$ and therefore we resorted to simulations. \subsection{Symmetric Network} The weighted average PAoI or AoI are depicted in Fig.~\ref{fig:symmetricexample} as a function of the traffix mix parameter $r$ on a log-log scale for two values of the load $\rho$ using the four schedulers OPS-P(A), NPB, H1-P(A), and H2-P(A) and note that H1-P $\equiv$ H1-A and H2-P $\equiv$ H2-A for symmetric networks. We have the following observations about symmetric networks: \begin{itemize} \item For symmetric networks, the optimum traffic mix should be unity due to symmetry. The discrepancy between NPB and the other SBPSQ systems is reduced as $r \rightarrow 1$ and it vanishes as $r \rightarrow 1$ and $\rho \rightarrow \infty$. However, for moderate loads and when $r$ deviates from unity, SBPSQ has substantial advantages compared to NPB. \item The proposed heuristic schedulers are developed without the knowledge of load and traffic mix using only heavy-traffic conditions. However, we observe through numerical results that the heuristic schedulers perform very close to that obtained by the computation-intensive optimum probabilistic scheduler. This observation is in line with those made in \cite{joo_eryilmaz_TNET18}. \item H2-P (H2-A) presents very similar performance to OPS-P (OPS-A) for all the load and traffic mix values we have obtained whereas H1-P and H1-A are slightly outperformed by them except for light and heavy loads. We also note that there are even cases when H2-A outperforms OPS-A in the high load regime when $r \rightarrow 1$. This stems from the fact that in the heavy-traffic regime, determinized source scheduling strategies perform better than their corresponding probabilistic counterparts for AoI. However, this observation does not necessarily apply to PAoI. \end{itemize} \begin{figure} \centering \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$W_{PAoI}$ ($\rho=1$)} \vspace*{-0.3cm} \includegraphics[width=\textwidth]{SymmetricExample1} \label{fig:symmetric1} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$W_{AoI}$ ($\rho=1$)} \vspace*{-0.3cm} \includegraphics[width=\textwidth]{SymmetricExample2} \label{fig:symmetric2} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$W_{PAoI}$ ($\rho=10$)} \vspace*{-0.3cm} \includegraphics[width=\textwidth]{SymmetricExample3} \label{fig:symmetric3} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$W_{AoI}$ ($\rho=10$)} \vspace*{-0.3cm} \includegraphics[width=\textwidth]{SymmetricExample4} \label{fig:symmetric4} \end{subfigure} \caption{The weighted average PAoI or AoI as a function the traffic mix parameter $r$ for two values of the load $\rho$.} \label{fig:symmetricexample} \end{figure} \subsection{Asymmetric Network - Weighted Average PAoI Minimization} In this numerical example, we depict $W_{PAoI}$ as a function of the load $\rho$ (on a log-log scale) employing four different buffer management/scheduling mechanisms, namely OPS-P, NPB, H1-P, and H2-P in Fig.~\ref{fig:PAoIexample} for which we fix $\omega=4$ and $\mu=4$. In Fig.~\ref{fig:PAoIexample1}, for given load $\rho$, we choose $\rho_i = \rho r_{PAoI}^*$ where the traffic mix ratio $r_{PAoI}^*=1$ as given in \eqref{optimum_mix_ratio}. This choice ensures that source-$i$ packet generation intensities are chosen such that NBP performance is maximized in terms of $W_{PAoI}$. On the other hand, for Fig.~\ref{fig:PAoIexample2}, we fix $r=1/4$, a choice which is quite different than the choice $r_{PAoI}^*=1$ giving rise to a scenario for which the arrival rate selections are not as consistent with the weights and average service rates as in Fig.~\ref{fig:PAoIexample1}. The following observations are made for this example. \begin{itemize} \item If the per-source packet arrival rates are chosen to optimize NBP as in Fig.~\ref{fig:PAoIexample1}, then the discrepancy between NPB and the other three SBPSQ systems is reduced especially for light and heavy loads. For this scenario, there are moderate load values at which NPB outperformed H1-P but OPS-P and H2-P always outperformed NPB in all the cases we had investigated. \item When the arrival rates deviate from the the optimum values derived for NPB as in Fig.~\ref{fig:PAoIexample2}, then the advantage of using SBPSQ with respect to NBP is magnified. Therefore, one can conclude that the sensitivity of the performance of SBPSQ systems to the specific choice of the arrival rates are lower than that of NPB. \item The performance of H2-P is quite similar to that of OPS-P for all the values we had tried both of which slightly outperform H1-P. We conclude that H2-P depends only on the knowledge on $\omega$ and $\mu$ and does not use the load and traffic mix. However, H2-P can safely be used at all loads and all traffic mixes as a simple-to-implement alternative to OPS-P for weighted PAoI minimization. \end{itemize} \begin{figure} \centering \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$\omega=4, \ \mu=4, \ r=1$}\vspace*{-0.2cm} \includegraphics[width=\textwidth]{PAoIexample1} \label{fig:PAoIexample1} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$\omega=4, \ \mu=4, \ r=1/4$} \vspace*{-0.2cm} \includegraphics[width=\textwidth]{PAoIexample2} \label{fig:PAoIexample2} \end{subfigure} \caption{$W_{PAoI}$ depicted as a function of the total load $\rho$ obtained with the algorithms OPS-P, NPB, H1-P, and H2-P for two different scenarios.} \label{fig:PAoIexample} \end{figure} \subsection{Asymmetric Network - Weighted Average AoI Minimization} In this example, we continue with the same example of the previous subsection but we focus on $W_{AoI}$ which is plotted as a function of the load $\rho$ (on a log-log scale) under the policies OPS-A, NPB, H1-A, and H2-A, in Fig.~\ref{fig:AoIexample} with $\omega=4$ and $\mu=4$. The traffic mix parameter $r$ is fixed to $r=1$ and $r=1/4$ in Fig.~\ref{fig:AoIexample1} and Fig.~\ref{fig:AoIexample2}, respectively. We have the following observations: \begin{itemize} \item The OPS-A curve is not monotonically decreasing with respect to load $\rho$ as in OPS-P for the two values of the traffic mix parameter $r$ we have studied; it first decreases until a certain load threshold is reached but then it slightly rises up to its heavy-traffic limit obtained with the probability ratio $p_{AoI}^*$. The corresponding load threshold value appears to depend on the traffic mix. \item The H2-P policy tracks the performance of OPS-A until the load threshold is reached but when the load ranges between the load threshold and infinity, H2-P outperforms OPS-A. This observation does not pertain to the results obtained for weighted average PAoI minimization. \end{itemize} \begin{figure} \centering \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$\omega=4, \ \mu=4, \ r=1$}\vspace*{-0.2cm} \includegraphics[width=\textwidth]{AoIexample1} \label{fig:AoIexample1} \end{subfigure} \hfill \begin{subfigure}[b]{0.48\textwidth} \centering \caption{$\omega=4, \ \mu=4, \ r=1/4$} \vspace*{-0.2cm} \includegraphics[width=\textwidth]{AoIexample2} \label{fig:AoIexample2} \end{subfigure} \caption{$W_{AoI}$ depicted as a function of the total load $\rho$ obtained with the algorithms OPS-A, NPB, H1-A, and H2-A for two different scenarios.} \label{fig:AoIexample} \end{figure} \section{Conclusions} \label{section7} We studied a two-source SBPSQ-based status update system with probabilistic scheduling and we proposed a method to obtain the distributions and moments of AoI and PAoI numerically using CTMCs of absorbing-type. The proposed technique is quite simple to implement making it amenable to use for a wider range of analytical modeling problems regarding AoI/PAoI distributions. Moreover, we performed heavy-traffic analysis for the same scenario to obtain closed form expressions for the per-source average AoI/PAoI values from which we have proposed two simple-to-implement age-agnostic heuristic schedulers. The proposed heuristic schedulers are developed without the knowledge of load and traffic mix using only heavy-traffic conditions. However, we observed through numerical results that the heuristic schedulers perform very close to that obtained by their computation-intensive optimum probabilistic scheduler counterparts and at all loads and traffic mixes. In particular, for weighted AoI minimization, our proposed heuristic scheduler H2-A's performance tracked that of the optimum probabilistic scheduler OPS-A except for heavy loads where it even outperformed OPS-A. For weighted PAoI minimization, our proposed heuristic scheduler H2-P's performance tracked that of the optimum probabilistic scheduler OPS-P. Therefore, H2-A and H2-P are promising candidates for scheduling in SBPSQ systems stemming from their performance and age-agnostic nature. Future work will be on extending the results to general number of sources and non-exponentially distributed service times, and also to discrete-time. \bibliographystyle{unsrtnat}
{'timestamp': '2021-10-22T02:39:29', 'yymm': '2110', 'arxiv_id': '2110.10992', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.10992'}
arxiv
\section{Introduction} With an abundance of user-generated multimodal content, such as videos, multimodal learning has become an important area of research \cite{wei2020multi, rahman2020integrating, atri2021see}. Unlike traditional unimodal learning on isolated modalities (such as vision, language, or acoustic), multimodal learning aims to aggregate complementary sources of information into a unified system. Understanding sarcasm from multimodal dialogues is a specialized form of sentiment analysis, where the speaker creatively experiments with words (language), gestures (vision), prosody (acoustic) to deliver incongruity across modalities. Humor is also a closely related quintessential sentiment often manifested using exaggeration or irony across modalities, such as a sudden twist of tone or a funny gesture. These two forms of subtle human sentiments are crucial to removing barriers in conversations, building trust \cite{vartabedian1993humor} and creating a positive impact on mental health \cite{lefcourt2012humor}. However, existing deep neural systems often struggle to understand such fine-grained multimodal sentiments. \noindent \textbf{Motivation:} The most common form of sarcasm and humor has traditionally been delivered using text. However, sarcasm in multimodal data often requires precise inter-modal cues to reveal the speaker’s intentions. For instance, it can often be expressed using a combination of verbal and non-verbal cues, such as a change of tone, overemphasis in a word, a drawn-out syllable, or a straight-looking face. Consider the example shown in Figure \ref{fig:mustard_example} - the seemingly applauding utterance \textit{"It's just a privilege to watch your mind in work"} becomes sarcastic when delivered with a straight face and clinical tone, overall expressing a negative connotation. Humans can naturally integrate all this simultaneous information subconsciously. However, building an algorithm that can potentially do the same requires appropriate representation of all these disparate sources of information and thus, gained immense research interest. \begin{figure}[t] \centering \hspace*{0cm} \includegraphics[scale=0.090]{Figures/MUStARD_example.png} \caption{Sample sarcastic utterance from the MUStARD dataset along with its transcript. Sheldon's comment (text) with a straight face (visual) and a clinical tone (acoustic) makes the instance sarcastic.} \label{fig:mustard_example} \vspace{-0.5cm} \end{figure} \noindent \textbf{Challenges:} Despite being regularly used in movies and sitcom shows, sarcastic conversational utterances are hard to collect, mainly because of the manual effort required in detecting and annotating raw videos with sarcasm labels. The only publicly available corpus, MUStARD, contains $690$ video samples with an even number of sarcastic and non-sarcastic labels. As a consequence, off-the-shelf multimodal transformer-based systems \cite{sun2019videobert, pan2020modeling, huang2020multimodal, rahman2020integrating} with a large number of parameters often tend to overfit this dataset. In this work, we propose \texttt{MuLOT}, which utilizes multi-head self-attention and optimal transport (OT) - \cite{villani2008optimal} based domain adaptation to learn strong intra- and cross-modal dependencies using a small number of training samples. In order to embed asynchronous unimodal features in a common subspace, we use optimal transport kernel (OTK) Embedding \cite{mialon2021trainable}. Lastly, the self and cross-attended features are fused using an attention fusion module. \noindent \textbf{Contributions:} In summary, our contributions are three-fold. $(i)$ We propose a new multimodal learning method that uses multi-head self-attention and optimal transport (OT) - \cite{villani2008optimal} based domain adaptation to learn strong intra- and cross-modal dependencies using a small number of training samples. $(ii)$ We evaluate the proposed system on three different multimodal sarcasm and humor detection datasets and obtain $2.1-2.4\%$ improvements over the previous state-of-the-art. $(iii)$ We reduce the training corpus of two large multimodal datasets and demonstrate the superiority of our system over multimodal transformers in a resource-constrained training setup. On limited training samples, the proposed system outperforms state-of-the-art by an accuracy margin of $4.2-5.8\%$. \section{Related Work} The proliferation of multimedia data on the Internet has resulted in multimodal systems gaining an increasing interest in recent years. One of the fundamental challenges in a multimodal framework is to fuse different unimodal features, which are asynchronous and have varying dimensions. Poria et al. \cite{poria2017review} presented an outline of various fusion techniques and potential performance improvements with multiple modalities. \noindent \textbf{Multimodal Fusion:} Similar to human behavior, multimodal frameworks aim to integrate and correlate simultaneous multiple resources, such as acoustic, visual, and textual information \cite{castro-etal-2019-towards, hazarika2020misa, atri2021see, pramanick2021detecting}. There are mainly three types of fusion strategies – early, late, and hybrid. Early fusion methods \cite{poria2016convolutional, zadeh2017tensor} integrates different sources of data into a single feature vector and uses a single classifier. On the other hand, late fusion \cite{cambria2017affective, cao2016cross} aggregates the outputs of different classifiers trained on different modalities. However, none of these techniques consider the interdependence among the different modalities and hence perform poorly on real applications. In contrast, hybrid fusion \cite{zadeh2018memory, akhtar2019multi, wang2019words, pham2019found, pramanick2021exercise, pramanick2021momenta} jointly learns from various modality-specific sources by employing an intermediate shared representation layer and has been most prominent in the literature. Recently following the success of transformers \cite{vaswani2017attention, howard2018universal, peters2018deep, devlin-etal-2019-bert, yang2019xlnet, liu2019roberta}, several works have extended it to multimodal applications by capturing both unimodal and cross-modal interactions via fine-tuning \cite{tsai-etal-2019-multimodal, lu2019vilbert, sun2019videobert, pan2020modeling, huang2020multimodal, kant2020spatially, rahman2020integrating}. For example, Rahman et al. \cite{rahman2020integrating} integrate acoustic and visual information in pre-trained transformers like BERT \cite{devlin-etal-2019-bert} and XLNet \cite{yang2019xlnet}. However, all the multimodal transformers require a large number of training samples for good performance. \noindent \textbf{Multimodal Sarcasm \& Humor Detection:} Humor and sarcasm are two closely related sentiments - while humor is often expressed using exaggeration and irony, sarcasm mostly generates from incongruity. Unimodal humor and sarcasm detection are well-studied in literature \cite{tepperman2006yeah, woodland2011context, riloff2013sarcasm, yang2015humor, chandrasekaran2016we, liu2018modeling, chen2018humor, kolchinski2018representing}. However, the multimodal counterpart is more subtle as the irony or incongruity is often present in different modalities. Hasan et al. \cite{hasan-etal-2019-ur} introduced the first large-scale multimodal dataset (UR-FUNNY) for humor detection. Castro et al. \cite{castro-etal-2019-towards} collected a multimodal conversational dataset (MUStARD) for sarcasm detection from popular sitcom TV shows. Cai et al. \cite{cai-etal-2019-multi} developed another dataset to detect multimodal sarcasm in Twitter posts. Recently, Han et al. \cite{han2021bi} proposed an end-to-end network that performs fusion (relevance increment) and separation (difference increment) on pairwise modality representations for humor detection. Another closely related work, MISA \cite{hazarika2020misa} aggregates modality-invariant and modality-specific representations and has been applied to predict humor in the UR-FUNNY dataset. However, multimodal sarcastic video samples are hard to collect, and the existing neural systems struggle to perform well on MUStARD. In this paper, we utilize self-attention to capture intra-modal correspondence and optimal transport for cross-modal correspondence in a low-resource training setup. \section{\texttt{MuLOT}: Proposed System} This section describes our proposed system, \texttt{MuLOT}\, for sarcasm and humor detection in videos and images by leveraging multimodal signals. Each video consists of multiple utterances\footnote{An utterance is a unit of speech bounded by breaths or pauses \cite{olson1977utterance}}, where each utterance - a smaller video by itself, is considered to contain sarcastic/humorous dialogues for positive samples. These utterances are a multimodal source of data - we preprocess the input utterances to extract fine-grained unimodal features from three modalities - visual $(v)$, language $(l)$, and acoustic $(a)$. Additionally, every utterance is accompanied by a context - which is also a short video helping to discern the background of the utterance. We concatenate the context with the utterance so that the utterance can be modeled in light of the context and the resulting video is treated as the input to the system. Consequently, our system is generalizable to images. Each input image is associated with a caption and a piece of text on it\footnote{We employ Google OCR Vision API to extract this text}, which we consider as visual $(v)$, caption text $(t_c)$ and OCR text $(t_{ocr})$ modalities. Features corresponding to these modalities are represented as $U_m \in \mathbb{R}^{L_m \times d_m}$, where $L_m$ denotes the sequence length for modality $m$ and $d_m$ is the respective feature dimension. The details of these features are discussed in Section \ref{sec:feature_extraction}. Given these unimodal feature sequences $U_{m \in \{v, l/t_c, a/t_{ocr}\}}$, the task is to predict the affective orientation of the input in a binary classification setup - sarcastic/humorous or non-sarcastic/non-humorous. As shown in Figure \ref{fig:model}, \texttt{MuLOT}\ consists of two modules, the self-attention module and the cross-attention module, shown in red and blue dashed blocks, respectively. First, the modality-specific fine-grained features are fed into the self-attention module which aims to learn intra-modality correspondence by emphasizing the most relevant tokens in the entire feature sequence. In parallel, the cross-attention module maps pairwise unimodal modalities into a common feature space, and thus learns inter-modality interaction. By taking both intra-modality and inter-modality relationships into consideration, the system gains the ability to synchronize across different modalities over various time and learns the correlation among them \cite{wei2020multi}. Finally, the self-attended unimodal features and cross-attended shared features are fused by using an attention fusion mechanism. It is important to observe that \texttt{MuLOT}\ achieves the same objective as multimodal transformers \cite{tsai-etal-2019-multimodal, lu2019vilbert, sun2019videobert, pan2020modeling, huang2020multimodal, kant2020spatially, rahman2020integrating}, but has significantly fewer trainable parameters, and thus works better in low-resource training setup. \begin{figure*}[t!] \centering \hspace*{0cm} \includegraphics[scale=0.058]{Figures/WACV_Model_2.png} \vskip-5pt\caption{The architecture of the proposed model, \texttt{MuLOT}. The features from each modality are passed through multi-head self-attention module (\textcolor{red}{red dashed}) and optimal transport-based cross-attention module (\textcolor{blue}{blue dashed}). Finally, the attended features are fused using Multimodal Attention Fusion (MAF).} \label{fig:model} \vspace{-0.5cm} \end{figure*} \subsection{Unimodal Feature Extraction} \label{sec:feature_extraction} In the proposed multimodal learning setup, we leverage three modalities, e.g., video, audio and text. Initially we extract fine-grained unimodal features from these modalities as described below. \noindent \textbf{Visual Features:} The video features are extracted using a pre-trained action recognition model, $I3D$ \cite{carreira2017quo} trained on the Kinetics dataset \cite{kay2017kinetics} to recognize $400$ different human actions. All the frames, computed at a rate of $5$ FPS, are first preprocessed by resizing, center-cropping, and normalization to have a resolution of $112 \times 112$. For every $16$ non-overlapping frames in a video, $I3D$ extracts a $2048$ dimensional feature vector. Therefore, the final unimodal feature dimension for every video is $L_v \times 2048$, where $L_v$ is the number of sets $16$ non-overlapping frames. For images, we employ ResNet-101 \cite{he2016deep} pre-trained on ImageNet \cite{deng2009imagenet}. Specifically, we extract $7\times 7\times 2048$ feature maps from the last pooling layer (pool5) of ResNet-101 and reshape it into a dimension of $49 \times 2048$. Hence, for the images, $L_v = 49$. \noindent \textbf{Language Features:} Traditionally, language modality features have been GloVe \cite{pennington2014glove} or Word2Vec \cite{mikolov2013efficient} embeddings for each token. However, following recent works \cite{castro-etal-2019-towards, sun2020learning, hazarika2020misa, pan2020modeling}, we utilize the pre-trained BERT \cite{devlin-etal-2019-bert} as the feature extractor for textual utterances. In particular, we input the raw text to a pre-trained uncased BERT-base model to get a $768$-dimensional dynamic feature representation for every token in the utterance. Hence, the resulting language feature dimension is $L_l \times 768$, where $L_l$ is the number of tokens in the utterance. \noindent \textbf{Acoustic Features:} The acoustic modality is expected to contribute information related to pitch, intonation, and other tonal-specific details of the speaker \cite{tepperman2006yeah}. To achieve this, we obtain low-level features from the audio stream for each video. Following state-of-the-art, we use COVAREP \cite{degottex2014covarep} to extract the audio features. These low-level features include but not limited to $12$ Mel-frequency cepstral coefficients, Voiced/Unvoiced segmenting features (VUV) \cite{drugman2011joint}, glottal source parameters \cite{drugman2011detection}\footnote{For the full set of features, please refer to \cite{zadeh2018multimodal, hasan-etal-2019-ur}}. The resulting acoustic feature dimension is $L_a \times 81$, where $L_a$ depends on the length of the video. Note that we use the OT kernel module in our system to align all three temporal sequences within an utterance to be of equal length, i.e. $L_v = L_l = L_a$. \subsection{Intra-Modality Attention} Now we introduce the self-attention module used to model the intra-modal correspondence among three different modalities. Typically, an attention module can be described as a tuple of key, query and value, where the output is a weighted sum of the values and the weight matrix is determined by query and its corresponding key. In case of self-attention, the key, query and value are equal. Following the philosophy of \cite{vaswani2017attention}, the recent trend is to apply transformers for modeling self-attention. However, a transformer module consists of multiple sub-layers and is often difficult to train from scratch. In our low-resource training setup, we simplify the structure of a transformer module by utilizing the multi-head attention layers. We compute the multi-head self-attention as follows. Given the unimodal feature matrices $U_m \in \mathbb{R}^{L_m \times d_m}$, where $m \in \{v, l/t_c, a/t_{ocr}\}$, we aim to extract $k$ distinct set of relevant features corresponding to the input representation, where $k$ is a hyper-parameter denoting the number of attention heads. The multi-head attention mechanism takes $U_m$ as an input, and outputs an attention weight matrix $W_m \in \mathbb{R}^{k\times L_m}$, respective to the modality-specific representation as follows \setlength{\belowdisplayskip}{0pt} \setlength{\belowdisplayshortskip}{0pt} \setlength{\abovedisplayskip}{0pt} \setlength{\abovedisplayshortskip}{0pt} \begin{equation} \label{equ:weight_self_attention} W_m = softmax(W_{h2} \tanh(W_{h1} U_m^\top)), \end{equation} where, ${W_{h1}} \in \mathbb{R}^{r \times d_m}$ and ${W_{h2}} \in \mathbb{R}^{k\times r}$ are parameter matrices to be learned during training. The $softmax(\cdot)$ is performed along the second dimension of its input, and $r$ is a hyper-parameter we can set arbitrarily. The resulting modality-specific embedding matrices $U_{mm}$ are computed using their respective attention weights and unattended features as follows \begin{equation} U_{mm} = W_m U_m, \end{equation} where, $U_{mm}\in \mathbb{R}^{k\times d_m}$ are the resulting self-attended features for modality $m$. \subsection{Cross-Modality Attention} Although the self-attention module effectively exploits the intra-modality correspondence, the inter-modality relationship, i.e. the interdependence across three different modalities is not deployed. Motivated by the success of Transformers \cite{vaswani2017attention, howard2018universal, peters2018deep, devlin-etal-2019-bert, yang2019xlnet, liu2019roberta}, several recent works have extended it to learn multimodal association by adding additional vision and speech modules to the Transformer framework \cite{tsai-etal-2019-multimodal, lu2019vilbert, sun2019videobert, pan2020modeling, huang2020multimodal, kant2020spatially, rahman2020integrating}. Although multimodal transformers rely on a language-pretrained BERT \cite{devlin-etal-2019-bert}, which is fixed throughout, the vision and acoustic components have to be trained from scratch, which often requires hundreds of thousands of training samples. To this end, instead of using a transformer-based cross-attention module, we exploit a recently proposed technique viz., optimal transport kernel (OTK) \cite{mialon2021trainable} for modelling the inter-modality association. OTK combines the idea of kernel methods and optimal transport to fuse the unimodal features with varying dimension and dependencies into a same reference frame. The complete cross-attention module consists of two steps -- unimodal feature transform and domain adaptation using optimal transport. \begin{table*}[t!] \centering \resizebox{0.95\textwidth}{!} { \begin{tabular}{c | c || c c c || c c c || c c c} \multirow{2}{*}{Dataset} & \multirow{2}{*}{\#Samples} & \multicolumn{3}{c}{Train} & \multicolumn{3}{c}{Dev} & \multicolumn{3}{c}{Test}\\ \cline{3-11} & & \#Sar & \#Non-Sar & Total & \#Sar & \#Non-Sar & Total & \#Sar & \#Non-Sar & Total \\ \hline \textbf{MUStARD} & 690 & 275 & 275 & 550 & 35 & 35 & 70 & 35 & 35 & 70 \\ \textbf{MST} & 24635 & 8642 & 11174 & 19816 & 959 & 1451 & 2410 & 959 & 1450 & 2409 \\ \textbf{Tiny MST} & 7819 & 2000 & 2000 & 4000 & 959 & 1451 & 2410 & 959 & 1450 & 2409 \\ \hline \hline & & \#Hum & \#Non-Hum & Total & \#Hum & \#Non-Hum & Total & \#Hum & \#Non-Hum & Total \\ \cline{3-11} \textbf{UR-FUNNY} & 16514 & 5306 & 5292 & 10598 & 1313 & 1313 & 2626 & 1638 & 1652 & 3290 \\ \textbf{Tiny UR-F} & 8916 & 1500 & 1500 & 3000 & 1313 & 1313 & 2626 & 1638 & 1652 & 3290 \\ \hline \end{tabular}} \caption{Statistics about the five datasets used in our experiments. We have reduced the training set of MST and UR-FUNNY to generate Tiny MST and Tiny UR-F, respectively. However, the corresponding dev and test sets remain unchanged.} \vspace{-0.3cm} \label{tab:dataset} \end{table*} \noindent {\bf{Unimodal Feature Transform:}} Since the visual, language and acoustic features have different dimensions with varying sizes and dependencies, mapping those into a same reference frame is necessary yet challenging. In the OTK approach, the unimodal feature vectors are embedded into a reproducing kernel Hilbert space (RKHS) and then a weighted pooling operation is performed based on attention with weights provided by the transport plan between the set and a trainable reference. The primary motivation for using kernels is to provide non-linear transformation of the input features. Afterward, optimal transport aligns the features on a trainable reference frame. Suppose we want to compute an optimal transport plan from $x$ to $x'$. Let $a$ and $b$ be defined as $a = \sum_{i} a_i\delta_{i}$ and $b = \sum_{i} b_i\delta_{i}$ and $C$ be the pairwise costs for aligning the elements $x$ to $x'$. Then the entropic regularized Kantorovich relaxation of OT from $x$ to $x'$ is~\cite{villani2008optimal}: \begin{equation} \min_{P \in U(a,b)} \sum_{ij} C_{ij} P_{ij} - \epsilon H(P), \label{eq:OT} \end{equation} where $H(P) = - \sum_{ij} P_{ij}(\log(P_{ij}-1))$, is the entropic regularization with parameter $\epsilon$, which controls the sparsity of $P$ and $U$ is the subspace of admissible coupling between $a$ and $b$ defined as follows \begin{equation} U(a,b) = \{ P \in R_{+}: P1_{n} = a \text{ and } P^T1_{n'} = b \}. \end{equation} Now, suppose $x = (x_1, x_2, .., x_n)$ be input feature vector and $z = (z_1, z_2, .., z_k)$ be the reference set with $k$ elements. Let $\kappa$ be a positive definite kernel and $\phi$ its corroesponding kernel embedding. The $\kappa$ matrix contains the values of $\kappa(x_i,z_i)$ before alignment and the transportation plan between $x$ and $z$ is denoted as $P(x,z)$, which is defined by the unique solution of Eq.~\eqref{eq:OT} when choosing cost $C = -\kappa$. The embedding is defined as: $\Phi_{z}(x) = \sqrt{p} P(x,z)^T\phi(x)$, where $\phi(x) = [\phi(x_1), .., \phi(x_n)]^T$. $\Phi_{z}(x)$ can also be represented as a positive semidefinite kernel as follows~\cite{mialon2021trainable} \begin{equation} \nonumber K_z(x, x') = \sum P_z(x,x')_{ij} \kappa(x_{i}, x_{j}) = \langle \Phi_{z}(x), \Phi_{z}(x'), \rangle \end{equation} where, $K_z$ is the OTK. Using OTK, we transform $L_m \times d_m$ dimensional unimodal features to a uniform reference frame with length $L_{uni}$ and feature dimension $d_{uni}$, where $L_{uni}$ and $d_{uni}$ are chosen by experiments. The transformed features are represented as $\widetilde{U_m} \in \mathbb{R}^{L_{uni} \times d_{uni}}$, where $m \in \{v, l/t_c, a/t_{ocr}\}$. \noindent \textbf{Domain Adaptation using Optimal Transport:} After transforming the varying dimensional unimodal features into a uniform reference frame, we finally embed pairwise unimodal features into a common subspace, using the OT-based domain adaptation. To implement OT as part of a larger learning model, we use the recently released Python optimal transport library \cite{flamary2021pot} in our experiments. We transport among each pair of modalities, which can be interpreted as domain adaptation across two modalities and the transported features are then concatenated to obtain the final adapted features. $U_{n \to m}$ denotes the transported features from modality $n$ to modality $m$, i.e. \begin{equation} U_{n \to m} = OT(\widetilde{U_n} \to \widetilde{U_m}). \end{equation} We then concatenate transported features to the self-attended features $U_{mm}$ to obtain the final adopted features as follows \begin{equation} U^m_{shared} = U_{mm} \oplus U_{n \to m} \oplus U_{p \to m}, \end{equation} where, $m,n,p \in \{v, l/t_c, a/t_{ocr}\}$, $m \neq n \neq p$, and $\oplus$ denotes simple concatenation. \subsection{Multimodal Attention Fusion (MAF)} MAF utilizes an attention-based mechanism to fuse three set of features, $U^m_{shared}$, corresponding to the three modalities. For some samples, the visual modality is relevant, while for others, the language or acoustic modality plays more crucial role. Hence, the MAF module aims to model the relative important of different modalities. Motivated by \cite{gu2018hybrid, pramanick2021exercise}, we design our MAF module with two major parts -- modality attention generation and weighted feature concatenation. In the first part, a sequence of dense layers followed by a softmax layer is used to generate the attention scores $[w_v, w_l, w_a]$ for the three modalities. In the second part, the adopted features are weighted using their respective attention scores and concatenated together as follows \begin{equation} U^{v}_{final} = (1 + w_v)U^v_{shared} \end{equation} \vspace{-0.22cm} \begin{equation} U^{l}_{final} = (1 + w_l)U^l_{shared} \end{equation} \vspace{-0.2cm} \begin{equation} U^{a}_{final} = (1 + w_a)U^a_{shared} \end{equation} \vspace{-0.2cm} \begin{equation} U^{v,l,a}_{final} = {W_U}\otimes [U^{v}_{final}, U^{l}_{final}, U^{a}_{final}] \end{equation} We also use residual connections for better gradient flow. The final multimodal representation, $U^{v,l,a}_{final}$, is fed into a series of fully-connected layers for the final binary classification. \section{Experiments} In this section, we present details of the datasets used, unimodal feature extraction steps, baselines, and training methodologies. \subsection{Datasets} We evaluate \texttt{MuLOT} on three different benchmark datasets for multimodal sarcasm and humor detection. Additionally, we access the effectiveness of \texttt{MuLOT}\ in a low-resource setup by shrinking the large training sets of two datasets. \noindent \textbf{MUStARD:} Multimodal Sarcasm Detection Dataset (MUStARD) \cite{castro-etal-2019-towards} is the only available resource to enable sarcasm detection in conversational videos. This dataset is curated from popular TV shows like Friends, The Big Bang Theory and consists of audiovisual utterances annotated with sarcasm labels. Each target utterance in this dataset is associated with historical dialogues as context, which is key to understanding the backdrop of sarcastic remarks. The primary challenge in using MUStARD is its small size, which limits the performance of heavy transformer-based systems on this corpus. \noindent \textbf{MST:} Multimodal Sarcasm in Twitter Posts (MST) \cite{cai-etal-2019-multi} consists of sarcastic and non-sarcastic image-text pairs collected from Twitter. This dataset is primarily bimodal, as there is no acoustic modality. However, we notice that a significant amount of samples contains textual information on the image. We employ Google OCR Vision API\footnote{\url{https://cloud.google.com/vision/docs/ocr}} to extract this text and treat this as the third modality. We further reduce the training set of MST and name the resulting corpus Tiny MST. \noindent \textbf{UR-FUNNY:} For multimodal humor detection, we use the UR-FUNNY dataset \cite{hasan-etal-2019-ur} which is collected from TED talk videos and therefore has three modalities. Similar to MUStARD, this dataset consists of context preceding the target punchline. We further create a tiny variant of UR-FUNNY by truncating its training set. The split statistics of all these datasets are presented in Table \ref{tab:dataset}. \subsection{Baselines} For unified comparison across videos and images, we use the following baselines. Furthermore, we remove various modalities and modules at a time from the proposed \texttt{MuLOT}\ system to observe the effect in performance. Baselines on MUStARD and UR-FUNNY include - \textbf{Support Vector Machines (SVM)}~\cite{cortes1995support}, \textbf{DFF-ATMF} \cite{chen2019complementary}, \textbf{CIM-MTL} \cite{akhtar2019multi}, \textbf{Tensor Fusion Network (TFN)} \cite{zadeh2017tensor}, \textbf{Contextual Memory Fusion Network (CMFN)} \cite{hasan-etal-2019-ur}, \textbf{MISA} \cite{hazarika2020misa}, \textbf{MAG-XLNet} \cite{rahman2020integrating}. MAG-XLNet introduced Multimodal Adaption Gate (MAG) to fuse acoustic and visual information in pre-trained language transformers, and is the SOTA on both MUStARD and UR-FUNNY. Baselines on MST include- \textbf{Concat BERT} (concatenates the features extracted by pre-trained unimodal ResNet-152 \cite{he2016deep} and Text BERT \cite{devlin-etal-2019-bert} and uses a simple perceptron as the classifier), \textbf{Supervised Multimodal Bitransformer (MMBT)} \cite{kiela2020supervised}, \textbf{Vision and Language BERT (ViLBERT)} \cite{lu2019vilbert}, \textbf{Hierarchical Fusion Model (HFM)} \cite{cai-etal-2019-multi}, \textbf{D\&R Net} \cite{xu2020reasoning}, \textbf{MsdBERT} \cite{pan2020modeling}. \textbf{MsdBERT}, which exploits a co-attention network to exploit intra- and inter-modality incongruity between text and image, is the SOTA method on the MST dataset. More details on the baselines are provided in supplementary document. \subsection{Training} We train \texttt{MuLOT}\ using Pytorch framework \cite{paszke2019pytorch} on Nvidia-RTX 2080Ti GPUs, with 24 GB dedicated memory in each GPU. As described in Section \ref{sec:feature_extraction}, we use pre-trained unimodal feature extraction models, and fine-tune them during training. All other weights are randomly initialized with a zero-mean Gaussian distribution with standard deviation 0.02. Although MUstARD and UR-FUNNY are balanced datasets, Table \ref{tab:dataset} shows label imbalance for the MST dataset. Therefore, when training on MST dataset, we assign larger weight ($[w_{sar},w_{non-sar}]=[1.2, 1]$) for minority class to minimize label imbalance. We train our model using the Adam \cite{loshchilov2018decoupled} optimizer and the binary cross-entropy loss as the objective function. The initial learning rate is $0.005$ and the network is trained for $300$ epoches. The detailed hyper-parameters used for the training is provided in the supplementary material. \section{Results, Discussion and Analysis} In this section, we compare the performance of \texttt{MuLOT}\ system with different multimodal baselines, conduct a detailed ablation study to demonstrate the importance of different modalities and modules in our system. Furthermore, we visualize the interpretability of \texttt{MuLOT}\ using Grad-CAM \cite{selvaraju2017grad}. Since the test sets of MUStARD and UR-FUNNY are balanced, we use binary accuracy as the evaluation metric. However, since the test set of MST is imbalanced, we also consider F1 scores when evaluating on this dataset. \begin{table}[t] \centering \resizebox{1\columnwidth}{!} { \begin{tabular}{l | c c || c | c | c} \multirow{2}{*}{\bf Algorithm} & \multirow{2}{*}{\bf Context} & \multirow{2}{*}{\bf Target} & \multicolumn{1}{c|}{\bf MUStARD} & \multicolumn{1}{c|}{\bf UR-FUNNY} & \multicolumn{1}{c}{\bf Tiny UR-F} \\ & & & Acc $\uparrow$ & Acc $\uparrow$ & Acc $\uparrow$ \\ \hline SVM & \xmark & \cmark & 73.55 & - & - \\ DFF-ATMF & \xmark & \cmark & 64.45 & 62.55 & 56.35\\ CIM-MTL & \xmark & \cmark & 67.14 & 63.20 & 56.71\\ TFN & \xmark & \cmark & 68.57 & 64.71 & 57.23\\ \hline CMFN (GloVe) & \xmark & \cmark & 67.14 & 64.47 & 57.10\\ CMFN (GloVe) & \cmark & \cmark & 70.00 & 65.23 & 59.25\\ \hline MISA (BERT) & \xmark & \cmark & 66.18 & 70.61 & 62.66\\ BBFN & \cmark & \cmark & 71.42 & 71.68 & 63.20\\ MAG-XLNet & \cmark & \cmark & 74.72 & 72.43 & 67.22\\ \hline \hline \texttt{MuLOT} & \xmark & \cmark & 74.52 & 73.22 & 70.74\\ \texttt{MuLOT} & \cmark & \cmark & \bf 76.82$^\dagger$ & \bf 73.97$^\dagger$ & \bf 71.46$^\dagger$\\ \hline \multicolumn{3}{c||}{\bf {$\Delta_{\texttt{MuLOT}-baseline}$}} & \textcolor{blue}{$\uparrow$ 2.10} & \textcolor{blue}{$\uparrow$ 1.54} & \textcolor{blue}{$\uparrow$ 4.24} \\ \hline \end{tabular}} \vspace{-0.2cm} \caption{Performances of multimodal models on the MUStARD, UR-FUNNY and Tiny UR-F datasets. Since the test sets are balanced (c.f. Table \ref{tab:dataset}), only binary classification accuracy is reported. $^\dagger$ indicates the results have experienced paired t-test with $p < 0.01$ and demonstrate significant improvement over MAG-XLNet, the best baseline model.} \label{tab:results_video} \end{table} \begin{table}[t] \centering \resizebox{0.95\columnwidth}{!} { \begin{tabular}{l | c || c c | c c} \multirow{2}{*}{\bf Algorithm} & \multirow{2}{*}{\bf OCR} & \multicolumn{2}{c|}{\bf MST} & \multicolumn{2}{c}{\bf Tiny MST} \\ & & Acc $\uparrow$ & F1 $\uparrow$ & Acc $\uparrow$ & F1 $\uparrow$ \\ \hline Concat BERT & \xmark & 81.08 & 79.56 & 76.21 & 73.48\\ HFM & \xmark & 83.44 & 80.18 & 77.80 & 74.07\\ D\&R Net & \xmark & 84.02 & 80.60 & 79.43 & 76.72\\ \hline MMBT & \xmark & 83.46 & 80.74 & 79.48 & 76.09\\ MMBT & \cmark & 84.87 & 82.66 & 80.57 & 77.20\\ \hline ViLBERT & \xmark & 84.21 & 82.49 & 79.42 & 75.95\\ ViLBERT & \cmark & 86.90 & 84.22 & 80.68 & 77.24\\ \hline MsdBERT & \xmark & 86.05 & 82.92 & 80.14 & 77.53\\ MsdBERT & \cmark & 88.75 & 86.18 & 82.30 & 79.90\\ \hline \hline \texttt{MuLOT} & \xmark & 87.41 & 86.33 & 84.46 & 82.62\\ \texttt{MuLOT} & \cmark & \textbf{90.82$^\dagger$} & \textbf{88.52$^\dagger$} &\textbf{88.04$^\dagger$} & \textbf{85.93$^\dagger$}\\ \hline \multicolumn{2}{c||}{\bf {$\Delta_{\texttt{MuLOT}-baseline}$}} & \textcolor{blue}{$\uparrow$ 2.07} & \textcolor{blue}{$\uparrow$ 2.34} & \textcolor{blue}{$\uparrow$ 5.74} & \textcolor{blue}{$\uparrow$ 6.03}\\ \hline \end{tabular}} \caption{Performance of multimodal models on the MST and Tiny MST datasets. Since the test set is imbalanced (c.f. Table \ref{tab:dataset}), both binary classification accuracy and macro F1 scores are reported. $^\dagger$ indicates the results have experienced paired t-test with $p < 0.01$ and demonstrate significant improvement over MsdBERT, the state-of-the-art model.} \label{tab:results_image} \vspace{-0.5cm} \end{table} \begin{table*} \centering \resizebox{1.9\columnwidth}{!} { \begin{tabular}{c | l || c | c | c || l || c c | c c} \multirow{2}{*}{\bf Modality} & \multirow{2}{*}{\bf Algorithm} & \multicolumn{1}{c|}{\bf MUStARD} & \multicolumn{1}{c|}{\bf UR-FUNNY} & \multicolumn{1}{c||}{\bf Tiny UR-F} & \multirow{2}{*}{\bf Algorithm} & \multicolumn{2}{c|}{\bf MST} & \multicolumn{2}{c}{\bf Tiny MST} \\ & & Acc $\uparrow$ & Acc $\uparrow$ & Acc $\uparrow$ & & Acc $\uparrow$ & F1 $\uparrow$ & Acc $\uparrow$ & F1 $\uparrow$ \\ \hline \tt Trimodal & \bf \texttt{MuLOT} & \bf 78.57 & \bf 73.97 & \bf 71.46 & \bf \texttt{MuLOT} & \bf 90.82 & \bf 88.52 & \bf 88.04 & \bf 85.93 \\ \hline \multirow{3}{*}{\tt Unimodal} & \texttt{visual} only & 73.30 & 60.72 & 58.80 & \texttt{visual} only & 82.65 & 81.22 & 78.56 & 77.70 \\ & \texttt{language} only & 73.54 & 69.58 & 67.32 & \texttt{caption} only & 83.40 & 82.14 & 80.06 & 78.85 \\ & \texttt{acoustic} only & 64.00 & 64.35 & 55.44 & \texttt{OCR} only & 78.64 & 77.39 & 76.22 & 75.31 \\ \hline \multirow{3}{*}{\tt Bimodal} & \texttt{visual} + \texttt{language} & 77.18 & 70.40 & 69.40 & \texttt{visual} + \texttt{caption} & 87.35 & 85.93 & 83.94 & 82.45 \\ & \texttt{visual} + \texttt{acoustic} & 75.54 & 69.23 & 69.82 & \texttt{visual} + \texttt{OCR} & 85.66 & 84.37 & 82.30 & 81.38 \\ & \texttt{language} + \texttt{acoustic} & 75.72 & 72.10 & 69.12 & \texttt{caption} + \texttt{OCR} & 85.10 & 83.79 & 81.87 & 81.00 \\ \hline \multirow{3}{*}{\tt Trimodal} & \texttt{MuLOT}\ w/o self-att$^n$ & 71.60 & 64.46 & 63.22 & \texttt{MuLOT}\ w/o self-att$^n$ & 86.24 & 84.80 & 83.69 & 82.84 \\ & \texttt{MuLOT}\ w/o cross-att$^n$ & 63.88 & 60.08 & 57.15 & \texttt{MuLOT}\ w/o cross-att$^n$ & 82.32 & 80.20 & 80.07 & 79.28 \\ & \texttt{MuLOT}\ w/o MAF & 75.23 & 71.22 & 68.84 & \texttt{MuLOT}\ w/o MAF & 87.94 & 86.73 & 85.55 & 84.38 \\ \hline \end{tabular}} \caption{Ablation Study. Role of different modalities and various modules in our proposed \texttt{MuLOT}\ system on five datasets. } \label{tab:results_ablation} \vspace{-0.5cm} \end{table*} \subsection{Comparison with Baselines} \noindent \textbf{Multimodal Sarcasm Detection:} Table \ref{tab:results_video} presents the comparative classification performances on the MUStARD dataset. Since this corpus is relatively small, complex neural models with a large number of parameters often overfit when trained from scratch. The authors of the MUStARD paper reported the best accuracy of $71.60\%$ when using a simple SVM as classifier \cite{castro-etal-2019-towards}. However, they used framewise ResNet features as the visual modality, which does not consider the temporal dynamics of the videos. We retrain an SVM using I3D features and produce $73.55\%$ accuracy to indicate the effectiveness of I3D features for videos. Transformer-based inter-utterance contextual baselines, DFF-ATMF and CIM-MTL, perform poorly on this dataset. We also observe the role of historical context dialogues to model sarcasm. The same CMFN baseline yields $2.86\%$ better accuracy after using context. Nevertheless, baselines like MISA and TFN do not improve from context. As described by the respective authors, these models suffer in encoding the long sequence and thus, lose crucial information during fusion. MAG-XLNet, which is the current state-of-the-art model in CMU-MOSI and CMU-MOSEI datasets for multimodal sentiment analysis, also performs well on MUStARD. Unlike other multimodal transformers, MAG-XLNet makes no change to the original structure of XLNet, but rather comes as an attachment to utilize multimodal information and hence proves relatively more effectual in a low resource setup. Our proposed system, \texttt{MuLOT}, improves on MAG-XLNet by $2.10\%$. It is important to note that, \texttt{MuLOT}\ has only $21$M trainable parameters, which is almost $8$ times smaller than MAG-XLNet. Domain adaptation using OT and low-number of parameters helps \texttt{MuLOT}\ in achieving the best results. Table \ref{tab:results_image} shows the performance of baselines and \texttt{MuLOT}\ on the MST dataset. Since a significant amount of the image samples of this dataset have text on it, the state-of-the-art system, MsdBERT utilizes OCR extracted texts to improve its F$1$ score by $3.26\%$. MMBT and ViLBERT also show a very similar trend. Since the MST dataset has a large training corpus, sophisticated transformer-based systems significantly outperform simple models like Concat BERT and HFM. Our proposed system, \texttt{MuLOT}\ beats the SOTA on MST by an F1 score of $2.34\%$, demonstrating its effectiveness on large corpus as well. Furthermore, in order to evaluate \texttt{MuLOT}\ on a low amount of training data, we randomly reduce the training set of MST to have only $2000$ samples in each class and call it Tiny MST. When trained on Tiny MST, the performance of MMBT, ViLBERT, and MsdBERT drops drastically. However, \texttt{MuLOT}\ is able to maintain an F1 score of $85.93\%$ and beats the best baseline by a substantial margin of $6.03\%$. The low number of trainable parameters and optimal transport-based domain adaptation setup in \texttt{MuLOT}\ again proves helpful when trained with limited data. \noindent \textbf{Multimodal Humor Detection:} For humor detection, we present the classification performances of baselines and \texttt{MuLOT}\ in Table \ref{tab:results_video}. Similar to MUStARD, MAG-XLNet produces the best baseline performance on the UR-FUNNY dataset. The inclusion of context also helps many baselines to boost their performance by a few points. \texttt{MuLOT}\ beats MAG-XLNet marginally on UR-FUNNY. However, when the training corpus size is reduced, MAG-XLNet drops its performance by $5.21\%$ compared to \texttt{MuLOT}'s $2.51\%$. Thus, on all three low-resource setups, \texttt{MuLOT}\ consistently outperforms all the baselines by a large margin, demonstrating that multimodal transformers are not good enough in the absence of ample training samples. \begin{figure*}[ht!] \centering \subfloat{ \includegraphics[width=0.21\textwidth, height=0.16\textwidth]{Figures/Unimodal_Correlation/mustard_unimodal_correlation.png}}\hspace{0.1em} \subfloat{ \includegraphics[width=0.178\textwidth, height=0.16\textwidth]{Figures/Unimodal_Correlation/mst_unimodal_correlation.png}} \subfloat{ \includegraphics[width=0.178\textwidth, height=0.16\textwidth]{Figures/Unimodal_Correlation/tiny_mst_unimodal_correlation.png}}\hspace{0.1em} \subfloat{ \includegraphics[width=0.178\textwidth, height=0.16\textwidth]{Figures/Unimodal_Correlation/ur-funny_unimodal_correlation.png}} \subfloat{ \includegraphics[width=0.178\textwidth, height=0.16\textwidth]{Figures/Unimodal_Correlation/tiny_ur-f_unimodal_correlation.png}}\hspace{0.1em} \caption{Pearson correlation calculated among the prediction outputs (dev \& test combined) of unimodal models.} \label{fig:unimodal_pearson} \vspace{-0.5cm} \end{figure*} \subsection{Ablation Study} \noindent \textbf{Role of Modalities:} In Table \ref{tab:results_ablation}, we retrain our system after removing one modality at a time to observe the effect in performance. First, we see that the trimodal system produces the best performance compared to all bimodal/unimodal systems, indicating that each modality contains complementary information. In the case of MUStARD, we observe similar drop in performance by removing either visual or language modalities, while for UR-FUNNY, the removal of language hurts the most. Since the cameras move a lot and seldom focuses on the faces in the TED videos of UR-FUNNY, the videos in this dataset carry a lot of noise. Next, we retrain the \texttt{MuLOT}\ system using only one modality at a time to observe how much modality-specific information our unimodal encoders can capture. Following previous results, for MUStARD, both visual and language modality performs equally well, and for UR-FUNNY, the language modality proves to be the best. Audio modality alone can not yield good results because the audio features only capture the tonal-specific details of the speaker, such as pitch and intonation, which only makes sense when the transcript is present. For the MST dataset, the image and caption together perform the best. The OCR text is only present in around $57.2\%$ of the samples and thus contributes less than other modalities. Figure \ref{fig:unimodal_pearson} shows the complementarity of different modalities in each dataset. We extract the predictions from each unimodal encoder and calculate the Pearson correlation among them. The low correlation values, shown in lighter shades, indicate that each modality covers different aspects of information. The trimodal \texttt{MuLOT}\ system integrates all these modalities in a unified framework and proves its efficacy. \noindent \textbf{Role of Intra- \& Cross-modal Attention:} Incorporating intra- and cross-modal attention significantly improves the performance, as shown in Table \ref{tab:results_ablation}. Since the incongruity, irony, and exaggeration of sarcasm and humor can generate from different modalities, cross-modal learning becomes the key, as illustrated in Figure \ref{fig:mustard_example}. \noindent \textbf{Role of MAF:} Since the importance of three modalities can vary for different samples, we utilize an attention-based mechanism (MAF) to fuse three different sets of features. As shown in Table \ref{tab:results_ablation}, we observe that compared to a simple concatenation of the modalities, MAF improves the performance by $2-4\%$ across the five datasets. We also find that a $3$-layer MAF network is sufficient to provide the best performance. \subsection{Interpretability of \texttt{MuLOT}} In this section, we comprehend the interpretability of \texttt{MuLOT}\ by generating the visual explanations over the videos and images by using Grad-CAM \cite{selvaraju2017grad} and visualize the attention distribution over text. Figure \ref{fig:mustard_example_attention} shows three different frames of a sarcastic utterance (video id: $1\textunderscore60$) from the MUStARD dataset. \texttt{MuLOT}\ focuses on the facial expression (straight face) of the speaker for all frames. In the language modality, the system focuses on words like "privilege" and thus, can detect the incongruity across the modalities. Figure \ref{fig:MST_example_attention} shows a sarcastic tweet from the MST dataset. In this sample, OCR successfully detects the text present on the image and the system perceives the irony between the OCR extracted text and the caption. Moreover, the class-discriminative regions on the image are properly identified by \texttt{MuLOT}, as shown by Grad-CAM. \begin{figure}[h] \centering \hspace*{0cm} \includegraphics[scale=0.09]{Figures/MUStARD_example_attention.png} \caption{Visual explanations and textual attention map for a sarcastic utterance from the MUStARD dataset.} \label{fig:mustard_example_attention} \vspace{-0.5cm} \end{figure} \begin{figure}[h] \centering \hspace*{0cm} \includegraphics[scale=0.05]{Figures/MST_attention_visualization.png} \caption{Visual explanations and textual attention maps for a sarcastic tweet from the MST dataset.} \label{fig:MST_example_attention} \vspace{-0.5cm} \end{figure} \section{Conclusion} In this paper, we deal with the task of detecting multimodal sarcasm and humor from conversational videos and image-text pairs. Capturing the intra- and inter-modal dynamics for these actions, which are highly dependent on the synchronization and aggregation of different modalities, is quite challenging with limited training data. To this end, we propose \textbf{\texttt{MuLOT}}, which captures intra-modal dynamics using multi-head self-attention and cross-modal dynamics using optimal transport. Finally, multimodal attention fusion across the modalities has been performed, which further improves the performance. Experimental results on three benchmark datasets- MUStARD (video, audio, text), UR-FUNNY (video, audio, text), MST (image, text) shows \textit{2.1\%}, \textit{1.54\%} and \textit{2.34\%} performance improvements compared to the state-of-the-art using our proposed method. \section*{Acknowledgement} The authors would like to thank Prof. Rama Chellappa for his helpful suggestions. Aniket Roy was supported by an ONR MURI grant N00014-20-1-2787 and Vishal M. Patel was supported by the NSF grant 1910141. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2021-10-22T02:38:16', 'yymm': '2110', 'arxiv_id': '2110.10949', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.10949'}
arxiv
\section{Introduction} Minimizing functionals with respect to probability measures is an ubiquitous problem in machine learning. Important examples are generative models such as GANs \citep{goodfellow2014generative, arjovsky2017wasserstein}, VAEs \citep{kingma2013auto} or normalizing flows \citep{papamakarios2019normalizing}. To that aim, one can rely on Wasserstein gradient flows (WGF) \citep{ambrosio2008gradient} which are curves decreasing the functional as fast as possible~\citep{santambrogio2017euclidean}. For particular functionals, these curves are known to be characterized by the solution of some partial differential equation (PDE) \citep{jordan1998variational}. Hence, to solve Wasserstein gradient flows numerically, we can solve the related PDE when it is available. Another way to solve it numerically is to approximate the curve in discrete time by the so-called JKO scheme introduced in \citep{jordan1998variational}, which is analogous in probability space to the well-known proximal operator \citep{parikh2014proximal} in Hilbertian space. It has for example been used by \citet{lin2021wasserstein} in order to train GANs. However, as a nested minimization problem, it is a difficult problem to handle numerically. Some works use a discretization in space (\emph{e.g.} a grid) and the entropic regularization of the Wasserstein distance~\citep{peyre2015entropic, carlier2017convergence}, which benefits from specific resolution strategies. However, those approaches do not scale to high dimensions, as the discretization of space scales exponentially with the dimension. Another line of work proposes to use particle schemes which are derived from the stochastic differential equation (SDE) related to the PDE followed by the gradient flow or from the forward Euler scheme. Such schemes have been derived for diverse functionals such as the Kullback-Leibler divergence \citep{feng2021relative, wang2021projected}, the Sliced-Wasserstein distance \citep{liutkus2019sliced}, the maximum mean discrepancy \citep{arbel2019maximum}, the kernel Stein discrepancy \citep{korbaKSD2021} or KALE \citep{glaser2021kale}. \citet{salim2020wasserstein} propose instead a forward-backward discretization scheme analogously to the proximal gradient algorithm \citep{bauschke2011convex}. Yet, these methods only provide samples approximately following the gradient flow, but without any information about the underlying density. Very recently, it was proposed in several concomitant works \citep{alvarezmelis2021optimizing, mokrov2021largescale, bunne2021jkonet} to take advantage of Brenier's theorem \citep{brenier1991polar} and model the optimal transport map (Monge map) as the gradient of a convex function with Input Convex Neural Networks (ICNN) \citep{amos2017input}. These models are called JKO-ICNN and handle well higher dimension problems. Yet, a drawback of JKO-ICNN is the training time due to a number of evaluations of the gradient of each ICNN that is quadratic in the number of JKO iterations. It also requires to backpropagate through the gradient which is challenging in high dimension, even though stochastic methods were proposed in \citep{huang2020convex} to alleviate it. Moreover, it has also been observed in several works that ICNNs have a poor expressiveness \citep{rout2021generative, korotin2019wasserstein, korotin2021neural} and that we should rather directly estimate the gradient of convex functions by neural networks \citep{saremi2019approximating, richterpowell2021input}. Other recent works proposed to use the JKO scheme by either exploiting variational formulations of functionals in order to avoid the evaluation of densities and allowing to use more general neural networks in \citep{fan2021variational}, or by learning directly the density in \citep{hwang2021deep}. \textbf{Contributions.} In the following, we propose to study the JKO scheme in the space of probability distributions endowed with the sliced-Wasserstein (SW) distance \citep{rabin2011wasserstein}. This novel and simple modification of the original problem comes with several benefits, mostly linked to the fact that this distance is easily differentiable and computationally more tractable than the Wasserstein distance. We first derive some properties of this new class of flows. Then, we show that it is possible to minimize functionals and learn the stationary distributions in high dimensions, on toy datasets as well as real image datasets, using \emph{e.g.} neural networks. In particular, we propose to use normalizing flows for functionals which involve the density, such as the negative entropy. Finally, we exhibit several examples for which our strategy performs better than state-of-the-art methods, either \emph{w.r.t.} to computation times and/or \emph{w.r.t.} the quality of the final solutions. \section{Background} The goal of this paper is to minimize a functional with respect to probability measures. Let $\mathcal{P}(\mathbb{R}^d)$ bet the set of probability measures on $\mathbb{R}^d$ and $\mathcal{F}$ be such functional, then the problem can be formalized as \begin{equation} \min_{\mu\in\mathcal{P}(\mathbb{R}^d)}\ \mathcal{F}(\mu). \end{equation} To solve this problem, we can rely on Wasserstein gradient flows (WGF) that we introduce in this section. \subsection{Gradient Flows in Euclidean Spaces} Let $F:\mathbb{R}^d\to\mathbb{R}$ be a functional. A gradient flow of $F$ is a curve (\emph{i.e.} a continuous function from $\mathbb{R}_+$ to $\mathbb{R}^d$) which decreases $F$ as much as possible along it. If $F$ is differentiable, then a gradient flow $x:[0,T]\to\mathbb{R}^d$ solves the following Cauchy problem \citep{santambrogio2017euclidean} \begin{equation} \begin{cases} \frac{\mathrm{d}x(t)}{\mathrm{d}t} = -\nabla F(x(t)), \\ x(0) = x_0. \end{cases} \end{equation} Under conditions on $F$ (\emph{e.g.} $\nabla F$ Lipschitz continuous, $F$ convex or semi-convex), this problem admits a unique solution which can be approximated using numerical schemes for ordinary differential equations such as the explicit or the implicit Euler scheme. For the former, we recover the regular gradient descent, and for the latter, we recover the proximal point algorithm \citep{parikh2014proximal}: let $\tau>0$, \begin{equation} \label{prox} x_{k+1}^\tau \in \argmin_{x}\ \frac{\|x-x_k^\tau\|_2^2}{2\tau}+F(x) = \mathrm{prox}_{\tau F}(x_k^\tau). \end{equation} This formulation does not use any gradient, and can therefore be used in any metric space by replacing $\|\cdot\|_2$ with the right distance. \subsection{Gradient Flows in Probability Spaces} To define gradient flows in the space of probability measures, we first need a metric. We restrict our analysis to probability measures with moments of order 2: $\mathcal{P}_2(\mathbb{R}^d)=\{\mu\in\mathcal{P}(\mathbb{R}^d),\ \int \|x\|^2 \mathrm{d}\mu(x)<+\infty\}$. Then, a possible distance on $\mathcal{P}_2(\mathbb{R}^d)$ is the Wasserstein distance \citep{villani2008optimal}, let $\mu,\nu\in\mathcal{P}_2(\mathbb{R}^d)$, \begin{equation} \label{wasserstein} W_2^2(\mu,\nu) = \min_{\gamma\in\Pi(\mu,\nu)}\ \int \|x-y\|_2^2\ \mathrm{d}\gamma(x,y), \end{equation} where $\Pi(\mu,\nu)$ is the set of probability measures on $\mathbb{R}^d\times\mathbb{R}^d$ with marginals $\mu$ and $\nu$. Now, by endowing the space of measures with $W_2$, we can define the Wasserstein gradient flow of a functional $\mathcal{F}:\mathcal{P}_2(\mathbb{R}^d)\to\mathbb{R}$ by plugging $W_2$ in (\ref{prox}) which becomes \begin{equation} \label{jko} \mu_{k+1}^\tau \in \argmin_{\mu\in \mathcal{P}_2(\mathbb{R}^d)}\ \frac{W_2^2(\mu,\mu_k^\tau)}{2\tau}+\mathcal{F}(\mu). \end{equation} The gradient flow is then the limit of the sequence of minimizers when $\tau\to0$. This scheme was introduced in the seminal work of \citet{jordan1998variational} and is therefore referred to as the JKO scheme. In this work, Authors showed that gradient flows are linked to PDEs, and in particular with the Fokker-Planck equation when the functional $\mathcal{F}$ is of the form \begin{equation} \label{FokkerPlanckFunctional} \mathcal{F}(\mu)=\int V\mathrm{d}\mu + \mathcal{H}(\mu) \end{equation} where $V$ is some potential function and $\mathcal{H}$ is the negative entropy: let $\sigma$ denote the Lebesgue measure, \begin{equation} \mathcal{H}(\mu) = \begin{cases} \int \rho(x)\log(\rho(x))\ \mathrm{d}x \ \text{ if $\mathrm{d}\mu=\rho\mathrm{d}\sigma$} \\ +\infty \ \text{otherwise}. \end{cases} \end{equation} Then, the limit of $(\mu^\tau)_\tau$ when $\tau\to 0$ is a curve $t\mapsto\mu_t$ such that for all $t>0$, $\mu_t$ has a density $\rho_t$. The curve $\rho$ satisfies (weakly) the Fokker-Planck PDE \begin{equation} \label{FokkerPlanck} \frac{\partial \rho}{\partial t} = \mathrm{div}(\rho\nabla V)+\Delta \rho. \end{equation} For more details on gradient flows in metric space and in Wasserstein space, we refer to \citep{ambrosio2008gradient}. \subsection{Numerical Methods to solve the JKO Scheme} Solving (\ref{jko}) is not an easy problem as it requires to solve an optimal transport problem at each step. Moreover, it is composed of two nested minimization problems. There are several strategies which were used to tackle this problem. For example, \citet{laborde2016interacting} rewrites (\ref{jko}) as a convex minimization problem using the Benamou-Brenier dynamic formulation of the Wasserstein distance \citep{benamou2000computational}. \citet{peyre2015entropic} approximates the JKO scheme by using the entropic regularization and rewrite the problem with respect to the Kullback-Leibler proximal operator. The problem becomes easier to solve using Dykstra's algorithm \citep{dykstra1985iterative}. This scheme was proved to converge to the right PDE in \citep{carlier2017convergence}. It was proposed to use the dual formulation in other works such as \citep{caluya2019proximal} or \citep{frogner2020approximate}. More recently, \citet{alvarezmelis2021optimizing} and \citet{mokrov2021largescale} proposed to exploit Brenier's theorem by rewriting the JKO scheme as \begin{equation} \begin{aligned} u_{k+1}^\tau\in\argmin_{u\ \mathrm{convex}}\ \frac{1}{2\tau}\int\|\nabla u(x)-x\|_2^2\ \mathrm{d}\mu_k^\tau(x) \\ + \mathcal{F}\big((\nabla u)_\#\mu_k^\tau\big) \end{aligned} \end{equation} and model the probability measures as $\mu_{k+1}^\tau = (\nabla u_{k+1}^\tau)_\#\mu_k^\tau$ where $\#$ is the push forward operator, defined as $(\nabla u)_\#\mu_k^\tau(A) = \mu_k^\tau((\nabla u)^{-1}(A))$ for all $A\in\mathcal{B}(\mathbb{R}^d)$. Then, to solve it numerically, they model convex functions using ICNNs \citep{amos2017input}: \begin{equation} \begin{aligned} \theta_{k+1}^\tau\in\argmin_{\theta\in\{\theta,u_\theta\in\mathrm{ICNN}\}}\ \frac{1}{2\tau}\int\|\nabla_x u_\theta(x)-x\|_2^2\ \mathrm{d}\mu_k^\tau(x) \\ + \mathcal{F}\big((\nabla_x u_\theta))_\#\mu_k^\tau\big). \end{aligned} \end{equation} In the remainder, this method is denoted as JKO-ICNN. \citet{bunne2021jkonet} also proposed to use ICNNs into the JKO scheme, but with a different objective of learning the functional from samples trajectories along the timesteps. Lastly, \citet{fan2021variational} proposed to learn directly the Monge map $T$ by solving at each step the following problem: \begin{equation} T_{k+1}^\tau \in \argmin_T\ \frac{1}{2\tau} \int \|T(x)-x\|_2^2\ \mathrm{d}\mu_k^\tau(x) + \mathcal{F}(T_\#\mu_k^\tau) \end{equation} and using variational formulations of functionals involving the density. This formulation requires only to use samples from the measure. However, it needs to be derived for each functional, and involves minimax optimization problems which are notoriously hard to train \citep{arjovsky2017towards,bond2021deep}. \section{Sliced-Wasserstein Gradient Flows} \label{SWGFs} As seen in the previous section, solving numerically (\ref{jko}) is a challenging problem. To tackle high-dimensional settings, one could benefit from neural networks, such as generative models, that are known to model accurately high-dimensional distributions. The problem being not directly differentiable, previous works relied on Brenier's theorem and modeled convex functions through ICNNs, which results in JKO-ICNN. However, this method is very costly to train. For a diffusion of length $k$, it requires $O(k^2)$ evaluations of gradients \citep{mokrov2021largescale} which can be a huge price to pay when the diffusion is very long. Moreover, it requires to backpropagate through gradients, and to compute the determinant of the Jacobian when we need to evaluate the likelihood (assuming the ICNN is strictly convex). The method of \citet{fan2021variational} also requires $O(k^2)$ evaluations of neural networks, as well as well as to solve a minimax optimization problem at each step. Here, we propose instead to use the space of probability measures endowed with the sliced-Wasserstein (SW) distance by modifying adequately the JKO scheme. Surprisingly enough, this class of gradient flows, which are very easy to compute, has never been considered numerically in the literature. Close to our work, {\bf Wasserstein} gradient flows using SW as a functional (called Sliced-Wasserstein flows) have been considered in \citep{liutkus2019sliced}. Our method differs significantly from this work, since we propose to compute {\bf sliced-Wasserstein} gradient flows of different functionals. We first introduce SW along with motivations to use this distance. We then study some properties of the scheme and discuss links with Wasserstein gradient flows. Since this metric is known in closed-form, the JKO scheme is more tractable numerically and can be approximated in several ways that we describe in Section \ref{swjko_practice}. \subsection{Motivations} \paragraph{Sliced-Wasserstein Distance.} The Wasserstein distance (\ref{wasserstein}) is generally intractable. However, in one dimension, for $\mu,\nu\in\mathcal{P}_2(\mathbb{R})$, we have the following closed-form \citep{peyre2019computational}[Remark 2.30] \begin{equation} W_2^2(\mu,\nu) = \int_0^1 \big(F_\mu^{-1}(u)-F_\nu^{-1}(u)\big)^2\ \mathrm{d}u \end{equation} where $F_\mu^{-1}$ (resp. $F_\nu^{-1}$) is the quantile function of $\mu$ (resp. $\nu$). It motivated the construction of the sliced-Wasserstein distance \citep{rabin2011wasserstein, bonnotte2013unidimensional}, as for $\mu,\nu\in\mathcal{P}_2(\mathbb{R}^d)$, \begin{equation} \label{sw} SW_2^2(\mu,\nu)=\int_{S^{d-1}} W_2^2(P^\theta_\#\mu,P^\theta_\#\nu)\mathrm{d}\lambda(\theta) \end{equation} where $P^\theta(x)=\langle x,\theta\rangle$ and $\lambda$ is the uniform distribution on $S^{d-1}=\{\theta\in\mathbb{R}^d,\ \|\theta\|_2=1\}$. \paragraph{Computational Properties.} Firstly, $SW_2$ is very easy to compute by a Monte-Carlo approximation (see Appendix \ref{approximation_sw}). It is also differentiable, and hence using \emph{e.g.} the Python Optimal Transport (POT) library \citep{flamary2021pot}, we can backpropagate \emph{w.r.t.} parameters or weights parametrizing the distributions (see Section \ref{swjko_practice}). Moreover, contrary to $W_2$, its sample complexity does not depend on the dimension \citep{nadjahi2020statistical} which is important to overcome the curse of dimensionality. However, it is known to be hard to approximate in high-dimension \citep{deshpande2019max} since the error of the Monte-Carlo estimates is impacted by the number of projections in practice \citep{nadjahi2020statistical}. Nevertheless, there exist several variants which could also be used. Moreover, a deterministic approach using a concentration of measure phenomenon (and hence being more accurate in high dimension) was recently proposed by \citet{nadjahi2021fast} to approximate $SW_2$. \paragraph{Link with Wasserstein.} The sliced-Wasserstein distance has also many properties related to the Wasserstein distance. First, they actually induce the same topology \citep{nadjahi2019asymptotic, bayraktar2021strong}. Moreover, as showed in Chapter 5 of \citep{bonnotte2013unidimensional}, they can be related on compact sets by the following inequalities, let $R>0$, for all $\mu,\nu\in\mathcal{P}(B(0,R))$, \begin{equation} SW_2^2(\mu,\nu) \le c_{d}^2 W_2^2(\mu,\nu)\le C_{d}^2 SW_2^{\frac{1}{d+1}}(\mu,\nu), \end{equation} with $c_d^2 = \frac{1}{d}$ and $C_d$ some constant. Hence, from these properties, we can wonder whether their gradient flows are related or not. Some previous works started to gather some hints on this question. For example, \citet{candau_tilh} showed that, while $(\mathcal{P}_2(\mathbb{R}^d),SW_2)$ is not a geodesic space, the minimal length (in metric space, Definition 2.4 in \citep{santambrogio2017euclidean}) connecting two measures is $W_2$ up to a constant (which is actually $c_{d}$). \subsection{Definition and Properties of Sliced-Wasserstein Gradient Flows} \label{section:discussion_swgf} Instead of solving the regular JKO scheme (\ref{jko}), we propose to introduce a SW-JKO scheme, let $\mu_0\in\mathcal{P}_2(\mathbb{R}^d)$, \begin{equation} \label{swjko} \forall k\ge 0,\ \mu_{k+1}^\tau \in \argmin_{\mu\in\mathcal{P}_2(\mathbb{R}^d)}\ \frac{SW_2^2(\mu,\mu_k^\tau)}{2\tau}+\mathcal{F}(\mu) \end{equation} in which we replaced the Wasserstein distance by $SW_2$. To study gradient flows and show that they are well defined, we first have to check that discrete solutions of the problem (\ref{swjko}) indeed exist. Then, we have to check that we can pass to the limit $\tau\to 0$ and that the limit satisfies gradient flows properties. These limit curves will be called Sliced-Wasserstein gradient flows (SWGFs). In the following, we restrain ourselves to measures on $\mathcal{P}_2(K)$ where $K\subset \mathbb{R}^d$ is a compact set. We report some properties of the scheme (\ref{swjko}) such as existence and uniqueness of the minimizer, and refer to Appendix \ref{Proofs} for the proofs. \begin{proposition} \label{prop:minimizer} Let $\mathcal{F}:\mathcal{P}_2(K)\to \mathbb{R}$ be a lower semi continuous functional, then the scheme (\ref{swjko}) admits a minimizer. Moreover, it is unique if $\mu_k^\tau$ is absolutely continuous and $\mathcal{F}$ convex or if $\mathcal{F}$ is strictly convex. \end{proposition} This proposition shows that the problem is well defined for convex lower semi continuous functionals since we can find at least a minimizer at each step. The assumptions on $\mathcal{F}$ are fairly standard and will apply for diverse functionals such as for example \eqref{FokkerPlanckFunctional}. \begin{proposition} \label{prop:nonincreasing} The functional $\mathcal{F}$ is non increasing along the sequence of minimizers $(\mu_k^\tau)_k$. \end{proposition} As the ultimate goal is to find the minimizer of the functional, this proposition assures us that the solution will decrease $\mathcal{F}$ along it at each step. If $\mathcal{F}$ is bounded below, then the sequence $(\mathcal{F}(\mu_k^\tau))_k$ will converge (since it is non increasing). More generally, by defining the piecewise constant interpolation as $\mu^\tau(0)=\mu_0$ and for all $k\ge 0$, $t\in]k\tau,(k+1)\tau]$, $\mu^\tau(t)=\mu_{k+1}^\tau$, we can show that for all $t<s$, $SW_2(\mu^\tau(t),\mu^\tau(s))\le C\big(|t-s|^\frac12 + \tau^\frac12\big)$ \citep{santambrogio2017euclidean}. By the Ascoli-Arzelà theorem \citep{santambrogio2015optimal}[Box 1.7], at least informally, we can extract a converging subsequence. However, the limit is possibly not unique and has a priori no relation with $\mathcal{F}$. Since $(\mathcal{P}_2(\mathbb{R}^d), SW_2)$ is not a geodesic space, but rather a ``pseudo-geodesic'' space whose true geodesics are $c_d W_2$ \citep{candau_tilh}, we cannot directly apply the theory introduced in \citep{ambrosio2008gradient}. We leave for future works the study of the theoretical properties of the limit. Nevertheless, we conjecture that in the limit $t\to\infty$, SWGFs converge toward the same measure as for WGFs. We will study it empirically in Section \ref{section:xps} by showing that we are able to find as good minima as WGFs for different functionals. \paragraph{Limit PDE.} \label{paragraph:limit_pde} We discuss here some possible links between SWGFs and WGFs. \citet{candau_tilh} shows that the Euler-Lagrange equation of the functional (\ref{FokkerPlanckFunctional}) has a similar form (up to the first variation of the distance). Hence, he conjectures that there is a correlation between the two gradient flows. We first notice that for one dimensional supported measures, $W_2$ and $SW_2$ are the same up to a constant $\sqrt{d}$, \emph{i.e.} let $\mu,\nu\in\mathcal{P}_2(\mathbb{R}^d)$ be supported on the same line, then $SW_2^2(\mu,\nu)=W_2^2(\mu,\nu)/d$. Interestingly enough, this is the same constant as between geodesics. This property is actually still true in any dimension for isotropic Gaussians sharing the same variance. Therefore, we argue that for these class of measures, provided that the minimum at each step stays in the same class, we would have a dilation of factor $d$ between the WGF and the SWGF. Hence, by correcting the SW-JKO scheme as \begin{equation} \label{sw_jko_d} \mu_{k+1}^\tau \in \argmin_{\mu\in\mathcal{P}_2(\mathbb{R}^d)}\ \frac{d}{2\tau} SW_2^2(\mu,\mu_k^\tau)+\mathcal{F}(\mu), \end{equation} we would have the same dynamic. For more general measures, it is not the case anymore. But, by rewriting $SW_2^2$ and $W_2^2$ \emph{w.r.t.} the centered measures $\Bar{\mu}$ and $\Bar{\nu}$, as well as the means $m_\mu=\int x \ \mathrm{d}\mu(x)$ and $m_\nu=\int x\ \mathrm{d}\nu(x)$, we have: \begin{equation} \begin{cases} W_2^2(\mu,\nu) = \|m_\mu-m_\nu\|_2^2 + W_2^2(\Bar{\mu},\Bar{\nu}) \\ SW_2^2(\mu,\nu) = \frac{\|m_\mu-m_\nu\|_2^2}{d} + SW_2^2(\Bar{\mu}, \Bar{\nu}). \end{cases} \end{equation} Hence, for measures characterized by their mean and variance (\emph{e.g.} Gaussians), there will be a constant $d$ between the optimal mean of the SWGF and of the WGF. However, such a direct relation is not available between variances, even on simple cases like Gaussians. We report in Appendix \ref{appendix:sw} the details of the calculations. We also report in Appendix \ref{appendix_dynamic_swgf} evolutions along the approximated WGF and SWGF of different functionals. In particular, for the interaction functional studied in Section \ref{section:agg_eq}, we do not observe the dilation of factor $d$, which tends to suggest that the relation between the limit PDEs, if any, is more subtle and complex. \subsection{Solving the SW-JKO Scheme in Practice} \label{swjko_practice} As a Monte-Carlo approximate of SW can be computed in closed-form, \eqref{swjko} is not a nested minimization problem anymore and is differentiable. We present here a few possible parameterizations of probability distributions which we can use in practice through SW-JKO to approximate the gradient flow. We further state how to approximate the Fokker-Planck functional (\ref{FokkerPlanckFunctional}). Then, from these parameterizations, we can apply gradient-based optimization algorithms by using backpropagation over the loss at each step. \paragraph{Discretized Grid.} \label{discrete_grid} A first proposition is to model the distribution on a regular fixed grid, as it is done \emph{e.g.} in \citep{peyre2015entropic}. If we approximate the distribution by a discrete distribution with a fixed grid on which the different samples are located, then we only have to learn the weights. Let us denote $\mu_k^\tau = \sum_{i=1}^N \rho_i^{(k)}\delta_{x_i}$ where we use $N$ samples located at $(x_i)_{i=1}^N$, and $\sum_{i=1}^N\rho_i=1$. Let $\Sigma_N$ denote the simplex, then the optimization problem (\ref{swjko}) becomes: \begin{equation} \min_{(\rho_i)_i\in\Sigma_N}\ \frac{SW_2^2(\sum_{i=1}^N\rho_i\delta_{x_i},\mu_k^\tau)}{2\tau}+\mathcal{F}(\sum_{i=1}^N\rho_i\delta_{x_i}). \end{equation} The entropy is only defined for absolutely continuous distributions. However, following \citep{carlier2017convergence,peyre2015entropic}, we can approximate the Lebesgue measure as: $L=l\sum_{i=1}^N\delta_{x_i}$ where $l$ represents a volume of each grid point (we assume that each grid point represents a volume element of uniform size). In that case, the Lebesgue density can be approximated by $(\frac{\rho_i}{l})_i$. Hence, for the Fokker-Planck (\ref{FokkerPlanckFunctional}) example, we approximate the potential and internal energies as \begin{equation} \begin{aligned} \mathcal{V}(\mu) &= \int V(x)\rho(x)\mathrm{d}x \approx \sum_{i=1}^N V(x_i)\rho_i \\ \mathcal{H}(\mu) &= \int \log(\rho(x))\rho(x)\mathrm{d}x \approx \sum_{i=1}^N \log\big(\frac{\rho_i}{l}\big)\rho_i. \end{aligned} \end{equation} To stay on the simplex, we use a projected gradient descent \citep{condat2016fast}. A drawback of discretizing the grid is that it becomes intractable in high dimension. \paragraph{With Particles.} \label{particles_scheme} We can also optimize over the position of a set of particles, assigning them uniform weights: $\mu_k^\tau=\frac{1}{N}\sum_{i=1}^N \delta_{x_i^{(k)}}$. The problem (\ref{swjko}) becomes: \begin{equation} \min_{(x_i)_i}\ \frac{SW_2^2(\frac{1}{N}\sum_{i=1}^N \delta_{x_i}, \mu_k^\tau)}{2\tau}+\mathcal{F}(\frac{1}{N}\sum_{i=1}^N \delta_{x_i}). \end{equation} In that case however, we do not have access to the density and cannot directly approximate $\mathcal{H}$ (or more generally internal energies). A workaround is to use nonparametric estimators \citep{beirlant1997nonparametric}, which is however impractical in high dimension. \paragraph{Generative Models.} \label{generative_models} Another solution to model the distribution is to use generative models. Let us denote $g_\theta:\mathcal{Z}\to \mathcal{X}$ such a model, with $\mathcal{Z}$ a latent space, $\theta$ the parameters of the model that will be learned, and let $p_Z$ be a simple distribution (\emph{e.g.} Gaussian). Then, we will denote $\mu_{k+1}^\tau = (g_\theta^{k+1})_\# p_Z$. The SW-JKO scheme (\ref{swjko}) will become in this case \begin{equation} \min_\theta\ \frac{SW_2^2\big((g_\theta^{k+1})_\# p_Z,\mu_k^\tau\big)}{2\tau} + \mathcal{F}\big((g_\theta^{k+1})_\# p_Z\big). \end{equation} To approximate the negative entropy, we have to be able to evaluate the density. A straightforward choice that we use in our experiments is to use invertible neural networks with tractable density such as normalizing flows \citep{papamakarios2019normalizing, kobyzev2020normalizing}. Another solution could be to use the variational formulation as in \citep{fan2021variational} as we only need samples in that case, but at the cost of solving a minimax problem. To perform the optimization, we can sample points of the different distributions at each step and use a Monte-Carlo approximation in order to approximate the integrals. Let $z_i\sim p_Z$ i.i.d, then $g_\theta(z_i)\sim (g_\theta)_\# p_Z = \mu $ and \begin{equation} \begin{aligned} \mathcal{V}(\mu) &\approx \frac{1}{N}\sum_{i=1}^N V(g_\theta(z_i)) \\ \mathcal{H}(\mu) &\approx \frac{1}{N}\sum_{i=1}^N \big(\log(p_Z(z_i))-\log|\det(J_{g_\theta}(z_i))|\big) \end{aligned} \end{equation} using the change of variable formula in $\mathcal{H}$. We sum up the procedure when modeling distributions with generative models in Algorithm \ref{alg:swjko_generativ_model}. We provide the algorithms for the discretized grid and for the particles in Appendix \ref{algorithms_swjko}. \begin{algorithm}[tb] \caption{SW-JKO with Generative Models} \label{alg:swjko_generativ_model} \begin{algorithmic} \STATE {\bfseries Input:} $\mu_0$ the initial distribution, $K$ the number of SW-JKO steps, $\tau$ the step size, $\mathcal{F}$ the functional, $N_e$ the number of epochs to solve each SW-JKO step, $N$ the batch size \FOR{$k=1$ {\bfseries to} $K$} \STATE Initialize a neural network $g_\theta^{k+1}$ \emph{e.g.} with $g_\theta^k$ \FOR{$i=1$ {\bfseries to} $N_e$} \STATE Sample $z_j^{(k)},z_j^{(k+1)}\sim p_Z$ i.i.d \STATE $x_j^{(k)}=g_\theta^k(z_j^{(k)})$, $x_j^{(k+1)}=g_\theta^{k+1}(z_j^{(k+1)})$ \STATE // Denote $\hat{\mu}_k^\tau = \frac{1}{N}\sum_{j=1}^{N} \delta_{x_j^{(k)}}$ \STATE // Denote $\hat{\mu}_{k+1}^\tau = \frac{1}{N}\sum_{j=1}^{N} \delta_{x_j^{(k+1)}}$ \STATE $J(\hat{\mu}_{k+1}^\tau) = \frac{1}{2\tau} SW_2^2(\hat{\mu}_k^\tau, \hat{\mu}_{k+1}^\tau)+\mathcal{F}(\hat{\mu}_{k+1}^\tau)$ \STATE Backpropagate through $J$ \emph{w.r.t.} $\theta$ \STATE Perform a gradient step using \emph{e.g.} Adam \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \section{Experiments} \label{section:xps} In this section, we show that by approximating sliced-Wasserstein gradient flows using the SW-JKO scheme \eqref{swjko}, we are able to minimize functionals as well as Wasserstein gradient flows approximated by the JKO-ICNN scheme and with a better computational complexity. We first evaluate the ability to learn the stationary density for the Fokker-Planck equation \eqref{FokkerPlanck} in the Gaussian case, and in the context of Bayesian Logistic Regression. Then, we evaluate it on an Aggregation equation. Finally, we use SW as a functional with image datasets as target, and compare the results with Sliced-Wasserstein flows introduced in \citep{liutkus2019sliced}. For these experiments, we mainly use generative models. When it is required to evaluate the density (\emph{e.g.} to estimate $\mathcal{H}$), we use Real Non Volume Preserving (RealNVP) normalizing flows \citep{dinh2016density}. Our experiments were conducted using PyTorch \citep{pytorch}. \subsection{Convergence to Stationary Distribution for the Fokker-Planck Equation} \label{section:xp_stationary_FKP} \paragraph{Gaussian Case.} The solution of a PDE of the form of \eqref{FokkerPlanck} converges toward a unique stationary measure $\mu^*\propto e^{-V}$ \citep{risken1996fokker}. Taking $V$ of the form \begin{equation} \forall x\in\mathbb{R}^d,\ V(x) = \frac12(x-m)^T A (x-b) \end{equation} with $A$ a symmetric positive definite matrix, and $m\in\mathbb{R}^d$, then the stationary distribution is $\mu^* = \mathcal{N}(m,A^{-1})$. We plot in Figure \ref{fig:unstabilities_jkoicnn} the symmetric Kullback-Leibler (SymKL) divergence over dimensions between approximated distributions and the true stationary distribution. We choose $\tau=0.1$ and performed 80 SW-JKO steps. We take the mean over 15 random gaussians for dimensions $d\in\{2,\dots,12\}$ for randomly generated positive semi-definite matrices $A$ using ``make\_spd\_matrix'' from scikit-learn \citep{scikit-learn}. Moreover, we use RealNVPs in SW-JKO. We see that the results are better than the particle schemes obtained with the Unadjusted Langevin Algorithm (ULA) \cite{roberts1996exponential}, called Euler-Maruyama (EM) since it is the EM scheme of the Langevin equation, with a step size of $10^{-3}$ and with either $10^3$, $10^4$ or $5\cdot 10^4$ particles in dimension higher than 2. We do not plot the results for JKO-ICNN as we observe unstabilities and very long training time (right plot in Figure \ref{fig:unstabilities_jkoicnn}). We add more details in Appendix \ref{appendix_cv_stationary}. \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{Figures/QuantitativeXp/SymKL_stationary_d10.pdf} \caption{On the left, SymKL divergence between solutions at time $t=8d$ (using $\tau=0.1$ and 80 steps in \eqref{swjko}) and stationary measure. On the right, SymKL between the true WGF $\mu_t$ and the approximation with JKO-ICNN $\hat{\mu_t}$, run through 3 Gaussians with $\tau=0.1$. We observe unstabilities at some point.} \label{fig:unstabilities_jkoicnn} \end{figure} \paragraph{Curse of Dimensionality.} Even though the sliced-Wasserstein distance sample complexity does not suffer from the curse of dimensionality, it appears through the Monte-Carlo approximation \citep{nadjahi2020statistical}. Here, since SW plays a regularizer role, the objective is not necessarily to approximate it well but rather to minimize the given functional. Nevertheless, the number of projections can still have an impact on the minimization, and we report on Figure \ref{fig:impact_projs} the evolution of the found minima \emph{w.r.t.} the number of projections, averaged over 15 random Gaussians. We observe that we do not need much projections to have fairly good results, even in higher dimension. \begin{figure}[htpb] \centering \includegraphics[width=\columnwidth]{Figures/QuantitativeXp/impact_projs_all_d.pdf} \caption{Impact of the number of projections for a fixed number of epochs.} \label{fig:impact_projs} \vspace{-8pt} \end{figure} \paragraph{Bayesian Logistic Regression.} Following the experiment of \cite{mokrov2021largescale} in Section 4.3, we propose to tackle the Bayesian Logistic Regression problem using SWGFs. For this task, we want to sample from $p(x|D)$ where $D$ represent data and $x=(w,\log \alpha)$ with $w$ the regression weights on which we apply a Gaussian prior $p_0(w|\alpha)=\mathcal{N}(w;0,\alpha^{-1})$ and with $p_0(\alpha)=\Gamma(\alpha;1,0.01)$. In that case, we use $V(x)=-\log p(x|D)$ to learn $p(x|D)$. We refer to Appendix \ref{Appendix_BLR} for more details on the experiments, as well as hyperparameters. We report in Table \ref{tab:blr} the accuracy results obtained on different datasets with SWGFs and compared with JKO-ICNN. We also report the training time and see that SWGFs allow to obtain results as good as with JKO-ICNN but for shorter training times which underlines the better complexity of our scheme. \begin{table}[htpb] \caption{Accuracy and Training Time for Bayesian Logistic Regression over 5 runs} \label{tab:blr} \begin{center} \small \resizebox{\columnwidth}{!}{ \begin{tabular}{ccccc} & \multicolumn{2}{c}{JKO-ICNN} & \multicolumn{2}{c}{SWGF+RealNVP} \\ \toprule Dataset & Acc & t & Acc & t \\ \midrule covtype & 0.755 $\pm 5\cdot 10^{-4}$ & 33702s & 0.755 $\pm 3\cdot 10^{-3}$ & 103s\\ german & 0.679 $\pm 5\cdot 10^{-3}$ & 2123s & \textbf{0.68 $\pm 5\cdot 10^{-3}$} & 82s \\ diabetis & 0.777 $\pm 7\cdot 10^{-3}$ & 4913s & \textbf{0.778 $\pm 2\cdot 10^{-3}$} & 122s \\ twonorm & 0.981 $\pm 2\cdot 10^{-4}$ & 6551s & 0.981 $\pm 6\cdot 10^{-4}$ & 301s \\ ringnorm & 0.736 $\pm 10^{-3}$ & 1228s & \textbf{0.741 $\pm 6\cdot 10^{-4}$} & 82s \\ banana & 0.55 $\pm 10^{-2}$ & 1229s & \textbf{0.559 $\pm 10^{-2}$} & 66s \\ splice & 0.847 $\pm 2\cdot 10^{-3}$ & 2290s & \textbf{0.85 $\pm 2\cdot 10^{-3}$} & 113s \\ waveform & \textbf{0.782 $\pm 8\cdot 10^{-4}$} & 856s & 0.776 $\pm 8\cdot 10^{-4}$ & 120s \\ image & \textbf{0.822 $\pm 10^{-3}$} & 1947s & 0.821 $\pm 3\cdot 10^{-3}$ & 72s \\ \bottomrule \end{tabular} } \end{center} \end{table} \subsection{Convergence to Stationary Distribution for an Aggregation Equation} \label{section:agg_eq} \begin{figure*}[htpb] \centering \hspace*{\fill} \subfloat[Steady state on the discretized grid]{\label{a}\includegraphics[scale=0.3]{Figures/Aggregation/aggregation_density_discretized.png}} \hfill \subfloat[Steady state for the fully connected neural network]{\label{b}\includegraphics[scale=0.3]{Figures/Aggregation/aggregation_density_mlp.png}} \hfill \subfloat[Steady state for particles]{\label{c}\includegraphics[scale=0.3]{Figures/Aggregation/aggregation_density_particles.png}} \hfill \subfloat[Steady state for JKO-ICNN (with $\tau=0.1$)]{\label{d:JKO-ICNN_density}\includegraphics[scale=0.3]{Figures/Aggregation/aggregation_density_jkoicnn_kde.png}} \hspace*{\fill} \caption{Steady state of the aggregation equation for $a=4$, $b=2$. From left to right, we plot it for the discretized grid, for the FCNN, for particles and for JKO-ICNN. We observe that JKO-ICNN does not recover well the ring as the particles are not evenly distributed on it.} \label{fig:aggregation_equation1} \end{figure*} We also show the possibility to solve different PDEs than Fokker-Planck. For example, using an interaction functional of the form \begin{equation} \label{eq:interaction_functional} \mathcal{W}(\mu) = \frac12 \iint W(x-y)\mathrm{d}\mu(x)\mathrm{d}\mu(y). \end{equation} In that case, the Wasserstein gradient flow is the aggregation equation \citep{santambrogio2015optimal}[Chapter 8] \begin{equation} \frac{\partial\rho}{\partial t} = \mathrm{div}(\rho(\nabla W*\rho)), \end{equation} where $*$ denotes the convolution operation. We notice here that we do not need to evaluate the density. Therefore, we can apply any neural network. For example, in the following, we will use a simple fully connected neural network (FCNN) and compare the results obtained with JKO-ICNN. We also show the results when learning directly over the particles and when learning weights over a grid. \citet{carrillo2021primal} use a repulsive-attractive interaction potential $W(x) = \frac{\|x\|_2^4}{4}-\frac{\|x|^2_2}{2}$. In this case, they showed empirically that the solution is a Dirac ring with radius 0.5 and centered at the origin. Starting from $\mu_0=\mathcal{N}(0,0.25^2 I_2)$, with $\tau=0.05$, we show on Figure \ref{fig:aggregation_equation1} that we recover this result with SWGFs for different parametrizations of the probabilities. More precisely, we first use a discretized grid of $50\times 50$ samples of $[-1,1]^2$. Then, we show the results when directly learning the particles and when using a FCNN. We also compare with the results obtained with JKO-ICNN. The densities reported for the last three methods are obtained through a kernel density estimator (KDE) with a bandwidth manually chosen since we either do not have access to the density, or we observed for JKO-ICNN that the likelihood exploded (see Appendix \ref{Aggregation}). It may be due to the fact that the stationary solution does not admit a density with respect to the Lebesgue measure. For JKO-ICNN, we observe that the ring shape is recovered, but the samples are not evenly distributed on it We report the solution at time $t=10$, and used $\tau=0.05$ for SW-JKO and $\tau=0.1$ for JKO-ICNN. As JKO-ICNN requires $O(k^2)$ evaluations of gradients of ICNNs, the training is very long for such a diffusion. Here, the training took around 5 hours on a RTX 2080 TI (for 100 steps), versus 20 minutes for the FCNN and 10 minutes for 1000 particles (for 200 steps). To sum up, an advantage of the SW-JKO scheme is to be able to use easier, yet powerful enough, architectures to learn the diffusion. This is cheaper in training time and less memory costly. Furthermore, we can tune the architecture with respect to the characteristics of the problem and add inductive biases (\emph{e.g.} using CNN for images) or learn directly over the particles. \subsection{Application on Real Data} In what follows, we show that the SW-JKO scheme can generate real data, and perform better than the associated particle scheme. We focus on the functional \begin{equation} \label{eq:swf} \mathcal{F}(\mu) = \frac12 SW_2^2(\mu,\nu)+\lambda\mathcal{H}(\mu) \end{equation} where $\nu$ is some target distribution, for which we should have access to samples. This functional was introduced in \citep{bonnotte2013unidimensional} for $\lambda=0$, and in \citep{liutkus2019sliced} with the negative entropy term. \citet{liutkus2019sliced} showcased a particle scheme called SWF (Sliced Wasserstein Flow) to approximate the WGF of \eqref{eq:swf}. Applied on images such as MNIST \citep{lecun-mnisthandwrittendigit-2010}, FashionMNIST \citep{xiao2017fashion} or CelebA \citep{liu2015deep}, SWFs need a very long convergence due to the curse of dimensionality and the trouble approximating SW. Hence, they used instead a pretrained autoencoder (AE) and applied the particle scheme in the latent space. Likewise, we use the AE proposed by \citet{liutkus2019sliced} with a latent space of dimension $d=48$, and we perform SW-JKO steps on thoses images. We report on Figure \ref{fig:mnist_AE} samples obtained with RealNVPs and on Table \ref{tab:table_FID} the Fréchet Inception distance (FID) \citep{heusel2017gans} obtained. We denote ``golden score'' the FID obtained with the pretrained autoencoder. Hence, we cannot obtain better results than this. We compared the results in the latent and in the ambient space with SWFs and see that we obtain fairly better results using generative models within the SW-JKO scheme, especially in the ambient space, although the results are not really competitive with state-of-the-art methods. This may be due more to the curse of dimensionality in approximating the objective SW than in approximating the regularizer SW. \begin{figure}[h] \centering \hspace*{\fill} \subfloat{\label{a_MNIST}\includegraphics[width=0.32\columnwidth]{Figures/SWF/SWF_MNIST_AE.png}} \hfill \subfloat{\label{b_FashionMNIST}\includegraphics[width=0.32\columnwidth]{Figures/SWF/SWF_FashionMNIST_AE.png}} \hfill \subfloat{\label{b_FashionMNIST}\includegraphics[width=0.32\columnwidth]{Figures/SWF/SWF_CelebA_AE.png}} \hspace*{\fill} \caption{Generated sample obtained through a pretrained decoder + RealNVP.} \label{fig:mnist_AE} \end{figure} \begin{table}[h] \caption{FID scores on some datasets (lower is better)} \label{tab:table_FID} \begin{center} \small \resizebox{\columnwidth}{!}{ \begin{tabular}{p{0.1\columnwidth}p{0.5\columnwidth}p{0.15\columnwidth}p{0.15\columnwidth}p{0.15\columnwidth}p{0.15\columnwidth}} & \textbf{Methods} &\textbf{MNIST} & \textbf{Fashion} & \textbf{CelebA}\\ \toprule \multirow{4}{*}{\rotcell{\scriptsize Ambient \\ Space}} & SWF \citep{liutkus2019sliced} & 225.1 & 207.6 & - \\ & SWGF + RealNVP & 88.1 & {\bf 95.5} & - \\ & SWGF + CNN & {\bf 69.3} & 102.3 & -\\ & & & \\ \midrule \multirow{4}{*}{\rotcell{Latent \\ Space}} & AE (golden score) & 15.55 & 31 & 77 \\ \cmidrule{2-5} & SWGF + AE + RealNVP & {\bf 17.8} & {\bf 40.6} & 90.9 \\ & SWGF + AE + FCNN & 18.3 & 41.7 & \textbf{88} \\ & SWF & 22.5 & 56.4 & 91.2 \\ \bottomrule \end{tabular} } \end{center} \end{table} \section{Conclusion} In this work, we derive a new class of gradient flows in the space of probability measures endowed with the sliced-Wasserstein metric, and the corresponding algorithms. To the best of our knowledge, and despite its simplicity, this is the first time that this class of flows is proposed in a machine learning context. We showed that it has several advantages over state-of-the-art approaches such as the recent JKO-ICNN. Aside from being less computationally intensive, it is more versatile \emph{w.r.t.} the different practical solutions for modeling probability distributions, such as normalizing flows, generative models or sets of evolving particles. Regarding the theoretical aspects, several challenges remain ahead: First, its connections with Wasserstein gradient flows are still unclear. Second, one needs to understand if, regarding the optimization task, convergence speeds or guarantees are changed with this novel formulation, revealing potentially interesting practical properties. Lastly, it is natural to study if popular variants of the sliced-Wasserstein distance such as Max-sliced \citep{deshpande2019max}, Distributional sliced \citep{nguyen2020distributional}, Subspace robust \citep{paty2019subspace}, generalized sliced \citep{kolouri2019generalized} or projection Wasserstein distances \citep{rowland2019orthogonal} can also be used in similar gradient flow schemes. The study of higher-order approximation schemes such as BDF2 \cite{matthes2019variational, plazotta2018bdf2} could also be of interest. \section{PROOFS} \label{Proofs} \subsection{Proof of Proposition \ref{prop:minimizer}} We refer to the proposition 3.7 in \citep{candau_tilh}. Let $\tau>0$,\ $k\in\mathbb{N}$,\ $\mu_k^\tau\in\mathcal{P}_2(K)$. Let's note $J(\mu)=\frac{SW_2^2(\mu,\mu_k^\tau)}{2\tau}+\mathcal{F}(\mu)$. According to Proposition 3.4 in \citep{candau_tilh}, $\mu\mapsto SW_2^2(\mu,\mu_k^\tau)$ is continuous with respect to the weak convergence. Indeed, let $\mu\in\mathcal{P}_2(K)$ and let $(\mu_n)_n$ converging weakly to $\mu$, \emph{i.e.} $\mu_n\xrightarrow[n\to\infty]{\mathcal{L}} \mu$. Then, by the reverse triangular inequality, we have \begin{equation} |SW_2^2(\mu_n,\mu_k^\tau)-SW_2^2(\mu,\mu_k^\tau)|\le SW_2^2(\mu_n,\mu) \le W_2^2(\mu_n,\mu). \end{equation} Since the Wasserstein distance metrizes the weak convergence, we have that $W_2^2(\mu_n,\mu)\to 0$. And therefore, $\mu\mapsto SW_2^2(\mu,\mu_k^\tau)$ is continuous \emph{w.r.t.} the weak convergence. By hypothesis, $\mathcal{F}$ is lower semi continuous, hence $\mu\mapsto J(\mu)$ is lower semi continuous. Moreover, $\mathcal{P}_2(K)$ is compact for the weak convergence, thus we can apply the Weierstrass theorem (Box 1.1 in \citep{santambrogio2015optimal}) and there exists a minimizer $\mu_{k+1}^\tau$ of $J$. By Proposition 3.5 in \citep{candau_tilh}, $\mu\mapsto SW_2^2(\mu,\nu)$ is convex and strictly convex whenever $\nu$ is absolutely continuous \emph{w.r.t.} the Lebesgue measure. Hence, for the uniqueness, if $\mathcal{F}$ is strictly convex then $\mu\mapsto J(\mu)$ is also strictly convex and the minimizer is unique. And if $\rho_k^\tau$ is absolutely continuous, then according to Proposition 3.5 in \citep{candau_tilh}, $\mu\mapsto SW_2^2(\mu,\mu_k^\tau)$ is strictly convex, and hence $\mu\mapsto J(\mu)$ is also strictly convex since $\mathcal{F}$ was taken convex by hypothesis. \subsection{Proof of Proposition \ref{prop:nonincreasing}} Let $k\in\mathbb{N}$, then since $\mu_{k+1}^\tau$ is the minimizer of \eqref{swjko}, \begin{equation} \mathcal{F}(\mu_{k+1}^\tau)+\frac{SW_2^2(\mu_{k+1}^\tau,\mu_k^\tau)}{2\tau} \le \mathcal{F}(\mu_{k}^\tau)+\frac{SW_2^2(\mu_{k}^\tau,\mu_k^\tau)}{2\tau} = \mathcal{F}(\mu_k^\tau). \end{equation} Hence, as $SW_2^2(\mu_{k+1}^\tau,\mu_k^\tau)\ge 0$, \begin{equation} \mathcal{F}(\mu_{k+1}^\tau)\le\mathcal{F}(\mu_k^\tau). \end{equation} \subsection{Upper Bound on the Errors} Following \cite{hwang2021deep}, we can also derive an upper bound on the error made at each step. \begin{proposition} \label{bound_error} Let $k\in\mathbb{N}$, $\mu_0\in\mathcal{P}_2(\mathbb{R}^d)$, $C$ some constant, and assume that $\mathcal{F}$ admits a lower bound, then \begin{equation} \begin{aligned} SW_2\big((g_\theta^{k+1,\tau})_\# p_Z,\mu_{k+1}^\tau\big) &\le SW_2\big((g_\theta^{k,\tau})_\# p_Z,\mu_k^\tau\big) + C\tau^{\frac12} \\ &\le (k+1) C \tau^{\frac12} + SW_2(\mu_0, \mu_1^\tau). \end{aligned} \end{equation} \end{proposition} \begin{proof} The bound can be found by applying Theorem 3.1 in \citep{hwang2021deep} with $X=(\mathcal{P}_2(\mathbb{R}^d, SW_2)$, and then by applying a straightforward induction. We report here the proof for the sake of completeness. Let $k\in\mathbb{N}$, then since $\mu_{k+1}^\tau$ is the minimizer of \eqref{swjko}, \begin{equation} \mathcal{F}(\mu_{k+1}^\tau)+\frac{SW_2^2(\mu_{k+1}^\tau,\mu_k^\tau)}{2\tau} \le \mathcal{F}(\mu_{k}^\tau)+\frac{SW_2^2(\mu_{k}^\tau,\mu_k^\tau)}{2\tau} = \mathcal{F}(\mu_k^\tau). \end{equation} Therefore, using that $\mathcal{F}$ is non increasing along $(\mu_k^\tau)_k$ (Proposition \ref{prop:nonincreasing}), we have $\mathcal{F}(\mu_k^\tau)\le \mathcal{F}(\mu_0)$. Moreover, using that $\mathcal{F}$ admits an infimum, we find \begin{equation} SW_2^2(\mu_k^\tau, \mu_{k+1}^\tau) \le 2\tau \big(\mathcal{F}(\mu_k^\tau)-\mathcal{F}(\mu_{k+1}^\tau)\big) \le 2\tau \big(\mathcal{F}(\mu_0)-\inf_\mu \mathcal{F}(\mu)\big). \end{equation} Let $A=\mathcal{F}(\mu_0)-\inf_\mu \mathcal{F}(\mu)$. By the same reasoning, we have that \begin{equation} SW_2^2\big((g_\theta^{k+1,\tau})_\# p_Z, (g_\theta^{k,\tau})_\# p_Z\big) \le 2\tau A. \end{equation} Now, using the triangular inequality, we have that \begin{equation} \begin{aligned} SW_2\big((g_\theta^{k+1,\tau})_\#p_Z,\mu_{k+1}^\tau\big) &\le SW_2\big((g_\theta^{k+1,\tau})_\#p_Z, (g_\theta^k)_\#p_Z\big) + SW_2\big((g_\theta^k)_\# p_Z, \mu_k^\tau\big) + SW_2(\mu_k^\tau, \mu_{k+1}^\tau) \\ &= 2\sqrt{2\tau A} + SW_2\big((g_\theta^{k,\tau})_\#p_Z,\mu_k^\tau\big). \end{aligned} \end{equation} Let $C = 2\sqrt{2A}$, then by induction we find \begin{equation} SW_2\big((g_\theta^{k+1,\tau})_\#p_Z,\mu_{k+1}^\tau\big) \le (k+1)C\sqrt{\tau} + SW_2(\mu_0,\mu_1^\tau). \end{equation} \end{proof} \iffalse \subsection{RCDT/Proofs of Theorem \ref{RCDT_grad_flow}} \emph{A ENLEVER ?} Let $\mu_0,\mu_1,\nu\in\mathcal{P}(K)$ \emph{(ou $\mathbb{R}^d$?)} with respective densities $f_0$, $f_1$ and $f_\nu$. Let's define the curve \begin{equation} \forall t\in[0,1],\ \mu_t = \mathrm{iRCDT}\big((1-t)\mathrm{RCDT}(f_0)+t\mathrm{RCDT}(f_1)\big). \end{equation} Then, $\mu_t$ is well interpolating between $\mu_0$ and $\mu_1$. Using the fact that $SW_2$ is a Hilbertian metric, we get \begin{equation} \begin{aligned} SW_2^2(\mu_t,\nu) &= \|\mathrm{RCDT}(\mu_t) - \mathrm{RCDT}(\nu)\|_2^2 \\ &= \|(1-t)\mathrm{RCDT}(f_0)+t\mathrm{RCDT}(f_1)-\mathrm{RCDT}(\nu)\|_2^2 \\ & \labelrel={parallelogram} (1-t) \|\mathrm{RCDT}(f_0)-\mathrm{RCDT}(\nu)\|_2^2 + t\|\mathrm{RCDT}(\mu_1)-\mathrm{RCDT}(\nu)\|_2^2 \\ &\ -t(1-t)\|\mathrm{RCDT}(\mu_0)-\mathrm{RCDT}(\mu_1)\|_2^2 \\ &= (1-t)SW_2^2(\mu_0,\nu) + t SW_2^2(\mu_1,\nu) -t(1-t)SW_2^2(\mu_0,\mu_1) \end{aligned} \end{equation} using the parallelogram rule in $\mathbb{R}$ in equation (\ref{parallelogram}) (as (\ref{parallelogram}) = $\int_{S^{d-1}}\int_\mathbb{R}\big((1-t) \hat{T_0}(s,\theta)+t\hat{T_1}(s,\theta)-\hat{T_\nu}(s,\theta)\big)^2 \hat{f_0}(s,\theta)\mathrm{d}s\mathrm{d}\theta$). Hence, we deduce that $\frac12 SW_2^2(\cdot,\nu)$ is 1-convex along $\mu_t$. Now, as $\mathcal{F}$ is supposed $\lambda$-convex along $\mu_t$, i.e. \begin{equation} \mathcal{F}(\mu_t) \le (1-t)\mathcal{F}(\mu_0)+t\mathcal{F}(\mu_1)-\frac{\lambda}{2}t(1-t)SW_2^2(\mu_0,\mu_1), \end{equation} we have \begin{equation} J(\mu_t) = \frac{1}{2\tau}SW_2^2(\mu_t,\nu) + \mathcal{F}(\mu_t) \le (1-t)J(\mu_0)+tJ(\mu_1)-\frac12\left(\frac{1}{\tau}+\lambda\right)SW_2^2(\mu_0,\mu_1). \end{equation} Therefore, as $\mu\mapsto J(\mu)$ is $\left(\frac{1}{\tau}+\lambda\right)$-convex, applying Theorem 3.3 of \citet{daneri2010lecture}, we can conclude that $\mathcal{F}$ admits a gradient flow. Moreover, the minimizing movement admits a unique solution $(\rho_k^\tau)_k$. \fi \subsection{Sliced-Wasserstein Results} \label{appendix:sw} \paragraph{Link for 1D Supported Measures.} Let $\mu,\nu\in\mathcal{P}(\mathbb{R}^d)$ supported on a line. For simplicity, we suppose that the measures are supported on an axis, \emph{i.e.} $\mu(x)=\mu_1(x_1)\prod_{i=2}^d \delta_0(x_i)$ and $\nu(x) = \nu_1(x_1)\prod_{i=2}^d \delta_0(x_i)$. In this case, we have that \begin{equation} W_2^2(\mu,\nu) = W_2^2(P^{e_1}_\#\mu,P^{e_1}_\#\nu) = \int_0^1 |F_{P^{e_1}_\#\mu}^{-1}(x) - F_{P^{e_1}_\#\nu}^{-1}(x)|^2\ \mathrm{d}x. \end{equation} On the other hand, let $\theta\in S^{d-1}$, then we have \begin{equation} \begin{aligned} \forall y\in\mathbb{R},\ F_{P^\theta_\#\mu}(y) &= \int_{\mathbb{R}} \mathbb{1}_{]-\infty,y]}(x)\ P^\theta_\#\mu(\mathrm{d}x) \\ &= \int_{\mathbb{R}^d} \mathbb{1}_{]-\infty, y]}(\langle \theta,x\rangle)\ \mu(\mathrm{d}x) \\ &= \int_{\mathbb{R}} \mathbb{1}_{]-\infty, y]}(x_1\theta_1)\ \mu_1(\mathrm{d}x_1) \\ &= \int_{\mathbb{R}} \mathbb{1}_{]-\infty, \frac{y}{\theta_1}]}\ \mu_1(\mathrm{d}x_i) \\ &= F_{P^{e_1}_\#\mu}\big(\frac{y}{\theta_1}\big). \end{aligned} \end{equation} Therefore, $F_{P^\theta_\#\mu}^{-1}(z) = \theta_1 F_{P^{e_1}_\#\mu}^{-1}(z)$ and \begin{equation} \begin{aligned} W_2^2(P^\theta_\#\mu,P^\theta_\#\nu) &= \int_0^1 |\theta_1 F_{P^{e_1}_\#\mu}^{-1}(z) - \theta_1 F_{P^{e_1}_\#\nu}^{-1}(z)|^2 \ \mathrm{d}z \\ &= \theta_1^2 \int_0^1 |F_{P^{e_1}_\#\mu}^{-1}(z) - F_{P^{e_1}_\#\nu}^{-1}(z)|^2 \ \mathrm{d}z \\ &= \theta_1^2 W_2^2(\mu,\nu). \end{aligned} \end{equation} Finally, using that $\int_{S^{d-1}}\theta\theta^T \mathrm{d}\lambda(\theta) = \frac{1}{d} I_d$, we can conclude that \begin{equation*} SW_2^2(\mu,\nu) = \int_{S^{d-1}} \theta_1^2 W_2^2(\mu,\nu) \mathrm{d}\theta = \frac{W_2^2(\mu,\nu)}{d}. \end{equation*} \paragraph{Closed-form between Gaussians.} \label{sw_gaussians} It is well known that there is a closed-form for the Wasserstein distance between Gaussians \citep{givens1984class}. If we take $\alpha=\mathcal{N}(\mu,\Sigma)$ and $\beta=\mathcal{N}(m,\Lambda)$ with $m,\mu\in\mathbb{R}^d$ and $\Sigma,\Lambda\in\mathbb{R}^{d\times d}$ two symmetric positive definite matrices, then \begin{equation} W_2^2(\alpha,\beta) = \|m-\mu\|_2^2 + \mathrm{Tr}\big(\Sigma+\Lambda - 2(\Sigma^{\frac12}\Lambda\Sigma^{\frac12})^{\frac12}\big). \end{equation} Let $\alpha=\mathcal{N}(\mu,\sigma^2 I_d)$ and $\beta=\mathcal{N}(m,s^2 I_d)$ two isotropic Gaussians. Here, we have \begin{equation} \begin{aligned} W_2^2(\alpha,\beta) &= \|\mu-m\|^2_2 + \mathrm{Tr}(\sigma^2 I_d + s^2 I_d - 2(\sigma s^2\sigma I_d)^\frac12) \\ &= \|\mu-m\|^2_2 + (\sigma-s)^2\ \mathrm{Tr}(I_d) \\ &= \|\mu-m\|^2_2 + d(\sigma-s)^2. \end{aligned} \end{equation} On the other hand, \citet{nadjahi2021fast} showed (Equation 73) that \begin{equation} SW_2^2(\alpha,\beta) = \frac{\|\mu-m\|_2^2}{d} + (\sigma-s)^2 = \frac{W_2^2(\alpha,\beta)}{d}. \end{equation} In that case, the dilation of factor $d$ between WGF and SWGF clearly appears. For more complicated gaussians, we may not have this equality. For example, let $\alpha=\mathcal{N}(\mu,D)$, $\beta=\mathcal{N}(m,\Delta)$ with $D$ and $\Delta$ diagonal. Then, $P^\theta_\#\alpha = \mathcal{N}(\langle \mu,\theta\rangle,\sum_{i=1}^N \theta_i^2 D_i)$, $P^\theta_\#\beta = \mathcal{N}(\langle m,\theta\rangle,\sum_{i=1}^N \theta_i^2 \Delta_i)$ and \begin{equation} W_2^2(P^\theta_\#\Bar{\alpha},P^\theta_\#\Bar{\beta}) = \left(\sqrt{\sum_i \theta_i^2 D_i} - \sqrt{\sum_i\theta_i^2 \Delta_i}\right)^2 \end{equation} with $\Bar{\alpha}$, $\Bar{\beta}$ the centered measures (noting $T^\alpha:x\mapsto x-\mu$, then $\Bar{\alpha}=T^\alpha_\#\alpha$). Hence, we have \begin{equation} \begin{aligned} SW_2^2(\alpha,\beta) &= \frac{\|\mu-m\|_2^2}{d}+SW_2^2(\Bar{\alpha},\Bar{\beta}) \\ &= \frac{\|\mu-m\|^2_2}{d}+\int_{S^{d-1}} \left(\sqrt{\sum_i \theta_i^2 D_i} - \sqrt{\sum_i\theta_i^2 \Delta_i}\right)^2\ \mathrm{d}\lambda(\theta) \\ &= \frac{\|\mu-m\|^2_2}{d} + \int_{S^{d-1}} \left(\sum_{i=1}^d \theta_i^2 D_i + \sum_{i=1}^d \theta_i^2 \Delta_i - 2 \sqrt{\sum_{i,j}\theta_i^2 \theta_j^2 D_i \Delta_j} \right)^2 \mathrm{d}\lambda(\theta) \\ &= \frac{\|\mu-m\|^2_2}{d} + \sum_{i=1}^d D_i \int_{S^{d-1}}\theta_i^2 \mathrm{d}\lambda(\theta) + \sum_{i=1}^D \Delta_i \int_{S^{d-1}} \theta_i^2 \mathrm{d}\lambda(\theta) - 2 \int_{S^{d-1}} \sqrt{\sum_{i,j}\theta_i^2 \theta_j^2 D_i\Delta_j}\mathrm{d}\lambda(\theta) \\ &= \frac{\|\mu-m\|^2_2}{d} + \frac{1}{d} \sum_{i=1}^d (D_i+\Delta_i) - 2 \int_{S^{d-1}}\sqrt{\sum_{i,j}\theta_i^2\theta_j^2 D_i\Delta_j}\mathrm{d}\lambda(\theta), \end{aligned} \end{equation} using that $\int_{S^{d-1}}\theta\theta^T \mathrm{d}\lambda(\theta) = \frac{1}{d} I_d$ and by applying Proposition 2 in \citep{nadjahi2021fast} to decompose $SW_2^2(\alpha,\beta)=\frac{\|\mu-m\|_2^2}{d}+SW_2^2(\Bar{\alpha},\Bar{\beta})$. On the other hand, we have \begin{equation} \begin{aligned} W_2^2(\alpha,\beta) &= \|\mu-m\|^2_2 + \mathrm{Tr}\big(D+\Delta-2(D^\frac12\Delta D^\frac12)^\frac12 \big) \\ &= \|\mu-m\|^2_2 + \mathrm{Tr}(D+\Delta-2(D\Delta)^\frac12) \\ &= \|\mu-m\|^2_2 + \sum_{i=1}^d (D_i+\Delta_i-2 D_i^\frac12 \Delta_i^\frac12) \\ &= \|\mu-m\|^2_2 + \sum_{i=1}^d (D_i^\frac12 - \Delta_i^\frac12)^2. \end{aligned} \end{equation} Since $SW_2^2(\alpha,\beta)\le \frac{1}{d}W_2^2(\alpha,\beta)$, we have $\sum_{i=1}^d \sqrt{D_i\Delta_i}\le d\int_{S^{d-1}}\sqrt{\sum_{i,j}\theta_i^2\theta_j^2 D_i \Delta_j}\mathrm{d}\lambda(\theta)$. Let $d=2$, $\sigma, s>0$ and $D=\mathrm{diag}(\sigma^2,\frac{\sigma^2}{2})$, $\Delta = \mathrm{diag}(\frac{s^2}{2},s^2)$. In this case, on the one hand, we have \begin{equation} \sum_{i=1}^2 \sqrt{D_i\Delta_i} = \sqrt{2}\sigma s. \end{equation} On the other hand, \begin{equation} \begin{aligned} 2\int_{S^{1}}\sqrt{\sum_{i,j}\theta_i^2\theta_j^2 D_i \Delta_j}\mathrm{d}\lambda(\theta) &= \sqrt{2}\sigma s \int_{S^1} \sqrt{(\theta_1^2+\theta_2^2)^2 + \frac12 \theta_1^2\theta_2^2}\ \mathrm{d}\lambda(\theta) \\ &= \sqrt{2}\sigma s \int_{S^1\cap \{\theta_1\neq 0,\theta_2\neq 0\}}\sqrt{(\theta_1^2 + \theta_2^2)^2 + \frac12 \theta_1^2\theta_2^2}\ \mathrm{d}\lambda(\theta) \\ &> \sqrt{2}\sigma s \int_{S^1} (\theta_1^2 + \theta_2^2) \ \mathrm{d}\lambda(\theta) \\ &= \sqrt{2}\sigma s, \end{aligned} \end{equation} using that $\lambda$ is absolutely continuous with respect to the Lebesgue measure and hence $\lambda(\{\theta_1=0\}\cup \{\theta_2=0\})=0$ and the fact that for every $\theta\in S^1\cap \{\theta_1\neq 0,\theta_2\neq 0\}$, $\sqrt{(\theta_1^2+\theta_2^2)^2 + \frac12 \theta_1^2\theta_2^2}>\sqrt{(\theta_1^2+\theta_2^2)^2}=\theta_1^2 + \theta_2^2$. From this strict inequality, we deduce that $W_2$ and $d\cdot SW_2$ are not always equal, even in this restricted case. \section{COMPUTATION OF THE SW-JKO SCHEME IN PRACTICE} \subsection{Approximation of SW} \label{approximation_sw} For each inner optimization problem \begin{equation} \mu_{k+1}^\tau\in\argmin_{\mu\in\mathcal{P}_2(\mathbb{R}^d)}\ \frac{SW_2^2(\mu,\mu_k^\tau)}{2\tau} + \mathcal{F}(\mu), \end{equation} we need to approximate the sliced-Wasserstein distance. To do that, we used Monte-Carlo approximate by sampling $n_\theta$ directions $(\theta_i)_{i=1}^{n_\theta}$ following the uniform distribution on the hypersphere $S^{d-1}$ (which can be done by using the stochastic representation, \emph{i.e.} let $Z\sim\mathcal{N}(0,I_d)$, then $\theta=\frac{Z}{\|Z\|_2}\sim \mathrm{Unif}(S^{d-1})$ \citep{fang2018symmetric}). Let $\mu,\nu\in\mathcal{P}(\mathbb{R}^d)$, we approximate the sliced-Wasserstein distance as \begin{equation} \widehat{SW}_2^2(\mu,\nu) = \frac{1}{n_\theta}\sum_{i=1}^{n_\theta} W_2^2(P^{\theta_i}_\#\mu,P^{\theta_i}_\#\nu). \end{equation} In practice, we compute it for empirical distributions $\hat{\mu}_n$ and $\hat{\nu}_m$, and we approximate the one dimensional Wasserstein distance \begin{equation} W_2^2(P^\theta_\#\hat{\mu}_n, P^\theta_\#\hat{\nu}_m) = \int_0^1 | F_{P^\theta_\#\hat{\mu}_n}^{-1}(u)- F_{P^\theta_\#\hat{\nu}_m}^{-1}(u)|^2\ \mathrm{d}u \end{equation} by the rectangle method. \subsection{Algorithms to Solve the SW-JKO Scheme} \label{algorithms_swjko} We provide here the algorithms used to solve the SW-JKO scheme (\ref{swjko}) for the discrete grid (Section \ref{discrete_grid}) and for the particles (Section \ref{particles_scheme}). \paragraph{Discrete Grid.} We recall that in that case, we model the distributions as $\mu_k^\tau = \sum_{i=1}^N \rho_i^{(k)}\delta_{x_i}$ where we use $N$ samples located at $(x_i)_{i=1}^N$ and $(\rho_i^{(k)})_{i=1}^N$ belongs to the simplex $\Sigma_n$. Hence, the SW-JKO scheme at step $k+1$ rewrites \begin{equation} \min_{(\rho_i)_i\in\Sigma_N}\ \frac{SW_2^2(\sum_{i=1}^N\rho_i\delta_{x_i},\mu_k^\tau)}{2\tau}+\mathcal{F}(\sum_{i=1}^N\rho_i\delta_{x_i}). \end{equation} We report in Algorithm \ref{alg:swjko_discrete} the whole procedure. \begin{algorithm}[htpb] \caption{SW-JKO with Discrete Grid} \label{alg:swjko_discrete} \begin{algorithmic} \STATE {\bfseries Input:} $\mu_0$ the initial distribution with density $\rho_0$, $K$ the number of SW-JKO steps, $\tau$ the step size, $\mathcal{F}$ the functional, $N_e$ the number of epochs to solve each SW-JKO step, $(x_j)_{j=1}^N$ the grid \STATE Let $\rho^{(0)}=\left(\frac{\rho_0(x_j)}{\sum_{\ell=1}^N\rho_0(x_\ell)}\right)_{j=1}^N$ \FOR{$k=1$ {\bfseries to} $K$} \STATE Initialize the weights $\rho^{(k+1)}$ (with for example a copy of $\rho^{(k)}$) \STATE // Denote $\mu_{k+1}^\tau = \sum_{j=1}^N \rho_j^{(k+1)}\delta_{x_j}$ and $\mu_k^\tau = \sum_{j=1}^N \rho_j^{(k)} \delta_{x_j}$ \FOR{$i=1$ {\bfseries to} $N_e$} \STATE Compute $J(\mu_{k+1}^\tau) = \frac{1}{2\tau} SW_2^2(\mu_k^\tau, \mu_{k+1}^\tau)+\mathcal{F}(\mu_{k+1}^\tau)$ \STATE Backpropagate through $J$ with respect to $\rho^{(k+1)}$ \STATE Perform a gradient step \STATE Project on the simplex $\rho^{(k+1)}$ using the algorithm of \citet{condat2016fast} \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \paragraph{Particle Scheme.} In this case, we model the distributions as empirical distributions and we try to optimize the positions of the particles. Hence, we have $\mu_k^\tau=\frac{1}{N}\sum_{i=1}^N \delta_{x_i^{(k)}}$ and the problem (\ref{swjko}) becomes \begin{equation} \min_{(x_i)_i}\ \frac{SW_2^2(\frac{1}{N}\sum_{i=1}^N \delta_{x_i}, \mu_k^\tau)}{2\tau}+\mathcal{F}(\frac{1}{N}\sum_{i=1}^N \delta_{x_i}). \end{equation} In this case, we provide the procedure in Algorithm \ref{alg:swjko_particles}. \begin{algorithm}[htpb] \caption{SW-JKO with Particles} \label{alg:swjko_particles} \begin{algorithmic} \STATE {\bfseries Input:} $\mu_0$ the initial distribution, $K$ the number of SW-JKO steps, $\tau$ the step size, $\mathcal{F}$ the functional, $N_e$ the number of epochs to solve each SW-JKO step, $N$ the batch size \STATE Sample $(x^{(0)}_j)_{j=1}^N\sim \mu_0$ i.i.d \FOR{$k=1$ {\bfseries to} $K$} \STATE Initialize $N$ particles $(x^{(k+1)}_j)_{j=1}^N$ (with for example a copy of $(x^{(k)}_j)_{j=1}^N$) \STATE // Denote $\mu_{k+1}^\tau = \frac{1}{N}\sum_{j=1}^N \delta_{x_j^{(k+1)}}$ and $\mu_k^\tau = \frac{1}{N}\sum_{j=1}^N \delta_{x_j^{(k)}}$ \FOR{$i=1$ {\bfseries to} $N_e$} \STATE Compute $J(\mu_{k+1}^\tau) = \frac{1}{2\tau} SW_2^2(\mu_k^\tau, \mu_{k+1}^\tau)+\mathcal{F}(\mu_{k+1}^\tau)$ \STATE Backpropagate through $J$ with respect to $(x_j^{(k+1)})_{j=1}^N$ \STATE Perform a gradient step \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \section{ADDITIONAL EXPERIMENTS} \subsection{Dynamic of Sliced-Wasserstein Gradient Flows} \label{appendix_dynamic_swgf} The Fokker-Planck equation (\ref{FokkerPlanck}) is the Wasserstein gradient flow of the functional (\ref{FokkerPlanckFunctional}). Moreover, it is well-known to have a counterpart stochastic differential equation (SDE) (see \emph{e.g.} \citep{mackey2011time}[Chapter 11]) of the form \begin{equation} \mathrm{d}X_t=-\nabla V(X_t)\mathrm{d}t+\sqrt{2\beta}\ \mathrm{d}W_t \end{equation} with $(W_t)_t$ a Wiener process. This SDE is actually the well-known Langevin equation. Hence, by approximating it using the Euler-Maruyama scheme, we recover the Unadjusted Langevin Algorithm (ULA) \citep{roberts1996exponential,wibisono2018sampling}. For \begin{equation} V(x)=\frac12 (x-m)^TA(x-m), \end{equation} with $A$ symmetric and definite positive, we obtain an Ornstein-Uhlenbeck process \citep{le2016brownian}[Chapter 8]. If we choose $\mu_0$ as a Gaussian $\mathcal{N}(m_0,\Sigma_0)$, then we know the Wasserstein gradient flow $\mu_t$ in closed form \citep{wibisono2018sampling,vatiwutipong2019alternative}, for all $t>0$, $\mu_t=\mathcal{N}(m_t,\Sigma_t)$ with \begin{equation} \begin{cases} m_t = m + e^{-tA}(m_0-m) \\ \Sigma_t = e^{-tA}\Sigma_0 (e^{-tA})^T + A^{-\frac12}(I-e^{-2tA})(A^{-\frac12})^T. \end{cases} \end{equation} \paragraph{Comparison of the Evolution of the Diffusion between SWGFs and WGFs.} For this experiment, we model the density using RealNVPs \citep{dinh2016density}. More precisely, we use RealNVPs with 5 affine coupling layers, using FCNN for the scaling and shifting networks with 100 hidden units and 5 layers. In both experiments, we always start the scheme with $\mu_0=\mathcal{N}(0,I)$ and take $n_\theta=1000$ projections to approximate the sliced-Wasserstein distance. We randomly generate a target Gaussian (using ``make\_spd\_matrix'' from scikit-learn \citep{scikit-learn} to generate a random covariance with 42 as seed). We look at the evolution of the distributions learned between $t=0$ and $t=4$ with a time step of $\tau=0.1$. We compare it with the true Wasserstein gradient flow. On Figure \ref{a_F_NonIsotropicGaussians_appendix}, we observe that they do not seem to match. However, they do converge to the same stationary value. On Figure \ref{b_F2_NonIsotropicGaussians_appendix}, we plot the functional along the true WGF dilated of a factor $d=2$. We see here that the two curves are matching and we observed the same behaviour in higher dimension. Even though we cannot conclude on the PDE followed by SWGFs, this reinforces the conjecture that the SWGF obtained with a step size of $\frac{\tau}{d}$ (\emph{i.e.} using the scheme (\ref{sw_jko_d})) is very close to the WGF obtained with a step size of $\tau$. We also report here the evolution of the mean (Fig. \ref{fig:means_gaussians_appendix}) and of the variance (Fig. \ref{fig:var_gaussians}). For the mean, it follows as expected the same diffusion. For the variance, it is less clear but it is hard to conclude since there are potentially optimization errors. \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat[Without dilation]{\label{a_F_NonIsotropicGaussians_appendix}\includegraphics[width={0.48\columnwidth}]{Figures/Gaussians/F_NonisotropicGaussians.pdf}} \hfill \subfloat[With dilation]{\label{b_F2_NonIsotropicGaussians_appendix}\includegraphics[width={0.48\columnwidth}]{Figures/Gaussians/F2_NonisotropicGaussians.pdf}} \hspace*{\fill} \caption{Evolution of the functional \eqref{FokkerPlanckFunctional} along the WGF $\mu_t$ and the learned SWGF $\hat{\mu}_t$. We observe a dilation of parameter 2 between the WGF and the SWGF.} \label{fig_appendix:dilation} \end{figure} \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat{\label{c_mu1}\includegraphics[scale=1]{Figures/Gaussians/Mean_1st_component_dilation2.pdf}} \hfill \subfloat{\label{d_mu2}\includegraphics[scale=1]{Figures/Gaussians/Mean_2nd_component_dilation2.pdf}} \hspace*{\fill} \caption{Evolution of the mean taking into account the dilation parameter. $\mu$ denotes the true mean of WGF, $\hat{\mu}$ the mean obtained through SW-JKO (\ref{swjko}) with $\tau=0.05$ and $\mu_*$ the mean of the stationary measure. We observe that the mean of approximated measure obtained through SW-JKO seems to follow the one of the WGF.} \label{fig:means_gaussians_appendix} \end{figure} \begin{figure}[htpb] \centering \includegraphics[scale=0.5]{Figures/Gaussians/Var_NonisotropicGaussians_dilation2.pdf} \caption{Evolution of the components of the covariance matrix taking into account the dilation parameter. $\Sigma$ denotes the true covariance matrix of WGF, $\hat{\Sigma}$ the covariance matrix obtained through SW-JKO (\ref{swjko}) with $\tau=0.05$ and $\Sigma^*$ the covariance matrix of the stationary distribution. We observe some difference between WGF and SWGF.} \label{fig:var_gaussians} \end{figure} \paragraph{Comparison between JKO-ICNN and SW-JKO.} \label{appendix:cv_true_distr} Following the experiment conducted by \cite{mokrov2021largescale} in section 4.2, we plot in Figure \ref{fig:xp_lowd_gaussians} the symmetric Kullback-Leibler (SymKL) divergence over dimensions between approximated distributions and the true WGF at times $t=0.5$ and $t=0.9$. We take the mean over 15 random gaussians (generated using the scikit-learn function \citep{scikit-learn} ``make\_spd\_matrix'' for the covariance matrices, and generating the means with a standard normal distribution) for dimensions $d\in\{2,\dots,12\}$. For each target Gaussian, we run the SW-JKO dilated scheme (\ref{sw_jko_d}) with $\tau=0.05$ for a RealNVP normalizing flow. We compare it with JKO-ICNN with also $\tau=0.05$ and with Euler-Maruyama with $10^3$, $10^4$ and $5\cdot 10^4$ particles and a step size of $10^{-3}$. For JKO-ICNN, we use, as \cite{mokrov2021largescale}, DenseICNN with convex quadratic layers introduced in \citep{korotin2019wasserstein} and available at \url{https://github.com/iamalexkorotin/Wasserstein2Barycenters}. For the JKO-ICNN scheme, we use our own implementation. We compute the symmetric Kullback-Leibler divergence between the ground truth of WGF $\mu^*$ and the distribution $\hat{\mu}$ approximated by the different schemes at times $t=0.5$ and $t=0.9$. The symmetric Kullback-Leibler divergence is obtained as \begin{equation} \mathrm{SymKL}(\mu^*,\hat{\mu})=\mathrm{KL}(\mu^*||\hat{\mu}) + \mathrm{KL}(\hat{\mu}||\mu^*). \end{equation} To approximate it, we generate $10^4$ samples of each distribution and evaluate the density at those samples. If we note $g_\theta$ a normalizing flows, $p_Z$ the distribution in the latent space and $\rho=(g_\theta)_\# p_Z$, then we can evaluate the log density of $\rho$ by using the change of variable formula. Let $x=g_\theta(z)$, then \begin{equation} \log(\rho(x))=\log(p_Z(z))-\log|\det J_{g_\theta}(z)|. \end{equation} We choose RealNVPs \cite{dinh2016density} for the simplicity of the transformations and the fact that we can compute efficiently the determinant of the Jacobian (since we have a closed-form). A RealNVP flow is a composition of transformations $T$ of the form \begin{equation} \forall z\in\mathbb{R}^d,\ x = T(z) = (z^1, \exp(s(z^1))\odot z^2 + t(z^1)) \end{equation} where we write $z=(z^1,z^2)$ and with $s$ and $t$ some neural networks. To modify all the components, we use also swap transformations (\emph{i.e.} $(z^1,z^2)\mapsto (z^2,z^1)$). This transformation is invertible with $\log \det J_T(z) = \sum_i s(z^1_i)$. For JKO-ICNN, we choose strictly convex ICNNs, and can hence invert them as well as compute the density. In this case, we do not have access to a closed-form for the Jacobian. Therefore, we used backpropagation to compute it. As this experiment is in low dimension, the computational cost is not too heavy. However, there exist stochastic methods to approximate it in greater dimension. We refer to \citep{huang2020convex} and \citep{alvarezmelis2021optimizing} for more explanations. We approximate the functional by using Monte-Carlo approximation as in Section \ref{generative_models}. For Euler-Maruyama, as in \citep{mokrov2021largescale}, we use kernel density estimation in order to approximate the density. We use the scipy implementation \citep{2020SciPy-NMeth} ``gaussian\_kde'' with the Scott's rule to choose the bandwidth. Finally, we report on the Figure \ref{fig:xp_lowd_gaussians} the mean of the log of the symmetric Kullback-Leibler divergence over 15 Gaussians in each dimension and the 95\% confidence interval. For the training of the neural networks, we use an Adam optimizer \citep{kingma2014adam} with a learning rate of $10^{-4}$ for RealNVP (except for the 1st iteration where we take a learning rate of $5\cdot 10^{-3}$) and of $5\cdot 10^{-3}$ for JKO-ICNN. At each inner optimization step, we start from a deep copy of the last neural network, and optimize RealNVP for 200 epochs and ICNNs for 500 epochs, with a batch size of 1024. We see on Figure \ref{fig:xp_lowd_gaussians} that the results are better than the particle schemes obtained with Euler-Maruyama (EM) with a step size of $10^{-3}$ and with either $10^3$, $10^4$ or $5\cdot 10^4$ particles in dimension higher than 2. However, JKO-ICNN obtained better results. We hypothesize that it is due to a slightly different dynamic as discussed in Section \ref{paragraph:limit_pde}. \begin{figure*}[htpb] \centering \includegraphics[width=\columnwidth]{Figures/QuantitativeXp/gaussians_low_d_v2.pdf} \caption{On the left: SymKL divergence at time $0.5$ and $0.9$ between the groundtruth of the Fokker-Planck equation at time $t$ and the solution of the SW Gradient Flow at time $t$. On the right: Absolute error between the functionals evaluated for WGF and SWGF at time $t$.} \label{fig:xp_lowd_gaussians} \end{figure*} \paragraph{Comparison between JKO-ICNN and SW-JKO for the Aggregation Equation.} In the same setting that Section \ref{section:agg_eq}, we report on Figure \ref{fig:aggregation_dynamic} the evolution of the diffusion for the interaction functional \eqref{eq:interaction_functional}, that we recall here: \begin{equation} \mathcal{W}(\mu) = \frac12 \iint W(x-y)\mathrm{d}\mu(x)\mathrm{d}\mu(y) \end{equation} with $W(x) = \frac{\|x\|_2^4}{4}-\frac{\|x|^2_2}{2}$. We see that we seem to lose the dilation factor of 2. \begin{figure}[htpb] \centering \includegraphics[scale=0.75]{Figures/Aggregation/aggregation_dynamic.pdf} \caption{On the left: $\mathcal{W}$ along the dynamic returned by SW-JKO and JKO-ICNN. On the right, $\mathcal{W}$ along the dynamic returned by JKO-ICNN and SW-JKO dilated by a factor $d=2$.} \label{fig:aggregation_dynamic} \end{figure} \subsection{Convergence to Stationary Distribution} \label{appendix_cv_stationary} Here, we want to demonstrate that, through the SW-JKO scheme, we are able to find good minima of functionals using simple generative models. \paragraph{Gaussian.} For this experiment, we place ourselves in the same setting of Section \ref{section:xp_stationary_FKP}. We start from $\mu_0=\mathcal{N}(0,I)$ and use a step size of $\tau=0.1$ for 80 iterations in order to match the stationary distribution. In this case, the functional is \begin{equation} \mathcal{F}(\mu)=\int V(x)\mathrm{d}\mu(x)+\mathcal{H}(\mu) \end{equation} with $V(x)=-\frac12 (x-b)^T A (x-b)$, and the stationary distribution is $\rho^*(x) \propto e^{-V(x)}$, hence $\rho^* = \mathcal{N}(b,A^{-1})$. We generate 15 Gaussians for $d$ between 2 and 12, and $d\in\{20,30,40,50,75,100\}$. Due to the length of the diffusion, and to numerical unstabilities, we do not report results obtained with JKO-ICNN. In Figure \ref{fig:unstabilities_jkoicnn}, we showed the results in low dimension (for $d\in\{2,\dots,12\}$) and the unstability of JKO-ICNN. We report on Figure \ref{fig:gaussian_stationary1} the SymKL also in higher dimension. \begin{figure}[htpb] \centering \includegraphics[scale=1]{Figures/QuantitativeXp/gaussians_stationary.pdf} \caption{Symmetric KL divergence between the learned distribution at time $t=8$ and the true stationary solution on Gaussians} \label{fig:gaussian_stationary1} \end{figure} We use 200 epochs of each inner optimization and an Adam optimizer with a learning rate of $5\cdot 10^{-3}$ for the first iteration and $10^{-3}$ for the rest. We also use a batch size of 1000 sample. \paragraph{Bayesian Logistic Regression.} \label{Appendix_BLR} For the Bayesian logistic regression, we have access to covariates $s_1,\dots,s_n\in\mathbb{R}^d$ with their associated labels $y_1,\dots,y_n\in\{-1,1\}$. Following \citep{liu2016stein, mokrov2021largescale}, we put as prior on the regression weights $w$, $p_0(w|\alpha)=\mathcal{N}(w;0,\frac{1}{\alpha})$ with $p_0(\alpha)=\Gamma(\alpha;1,0.01)$. Therefore, we aim at learning the posterior $p(w,\alpha|y)$: \begin{equation*} p(w,\alpha|y) \propto p(y|w,\alpha) p_0(w|\alpha) p_0(\alpha) = p_0(\alpha) p_0(w|\alpha) \prod_{i=1}^n p(y_i|w,\alpha) \end{equation*} where $p(y_i|w,\alpha) = \sigma(w^T s_i)^{\frac{1+y_i}{2}}(1-\sigma(w^T s_i))^{\frac{1-y}{2}}$ with $\sigma$ the sigmoid. To evaluate $\mathcal{V}(\mu)=\int V(x)\ \mathrm{d}\mu(x)$, we resample data uniformly. In our context, let $V(x) = -\log\big(p_0(\alpha)p_0(w|\alpha)p(y|w,\alpha)\big)$, then using $\mathcal{F}(\mu) = \int V \mathrm{d}\mu + \mathcal{H}(\mu)$ as functional, we know that the limit of the stationary solution of Fokker-Planck is proportional to $e^{-V} = p(w,\alpha|y)$. Following \cite{mokrov2021largescale, liu2016stein}, we use the 8 datasets of \cite{mika1999fisher} and the covertype dataset (\url{https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html}). We report in Table \ref{tab:datasets} the characteristics of the different datasets. The datasets are loaded using the code of \cite{mokrov2021largescale} (\url{https://github.com/PetrMokrov/Large-Scale-Wasserstein-Gradient-Flows}). We split the dataset between train set and test set with a 4:1 ratio. \begin{table}[h] \centering \begin{tabular}{cccccccccc} & covtype & german & diabetis & twonorm & ringnorm & banana & splice & waveform & image \\ \midrule features & 54 & 20 & 8 & 20 & 20 & 2 & 60 & 21 & 18 \\ samples & 581012 & 1000 & 768 & 7400 & 7400 & 5300 & 2991 & 5000 & 2086 \\ batch size & 512 & 800 & 614 & 1024 & 1024 & 1024 & 512 & 512 & 1024 \\ \end{tabular} \caption{Number of features, of samples and batch size of each Dataset} \label{tab:datasets} \end{table} We report in Table \ref{tab:hyperparams_mine} the hyperparameters used for the results reported in Table \ref{tab:blr}. We also tuned the time step $\tau$ since for too big $\tau$, we observed bad results, which the SW-JKO scheme should be a good approximation of the SWGF only for small enough $\tau$. Moreover, we reported in Table \ref{tab:blr} the mean over 5 training. For the results obtained with JKO-ICNN, we used the same hyperparameters as \citet{mokrov2021largescale}. \begin{table}[h] \centering \begin{tabular}{cccccccccc} & covtype & german & diabetis & twonorm & ringnorm & banana & splice & waveform & image \\ \midrule nl & 2 & 2 & 2 & 2 & 2 & 2 & 5 & 5 & 2 \\ nh & 512 & 512 & 512 & 512 & 512 & 512 & 128 & 128 & 512 \\ lr & $2e^{-5}$ & $1e^{-4}$ & $5e^{-4}$ & $1e^{-4}$ & $5e^{-5}$ & $1e^{-4}$ & $5e^{-4}$ & $1e^{-4}$ & $5e^{-5}$ \\ JKO steps & 5 & 5 & 10 & 20 & 5 & 5 & 5 & 5 & 5 \\ Iters by step & 1000 & 500 & 500 & 500 & 1000 & 500 & 500 & 500 & 500 \\ $\tau$ & 0.1 & $10^{-6}$ & $5\cdot 10^{-6}$ & $10^{-8}$ & $10^{-6}$ & 0.1 & $10^{-6}$ & $10^{-8}$ & 0.1 \\ batch size & 1024 & 1024 & 1024 & 1024 & 1024 & 1024 & 1024 & 512 & 1024 \\ \end{tabular} \caption{Hyperparameters for SWGFs with RealNVPs. nl: number of coupling layers in RealNVP, nh: number of hidden units of conditioner neural networks, lr: learning rate using Adam, JKO steps: number of SW-JKO steps, Iters by step: number of epochs for each SW-JKO step, $\tau$: the time step, batch size: number of samples taken to approximate the functional.} \label{tab:hyperparams_mine} \end{table} \subsection{Influence of the Number of Projections} \label{appendix:impact_projs} It is well known that the approximation of Sliced-Wasserstein is subject to the curse of dimensionaly through the Monte-Carlo approximation \citep{nadjahi2020statistical}. We provide here some experiment to quantify this influence. However, first note that the goal is not to minimize the Sliced-Wasserstein distance, but rather the functional, SW playing mostly a regularizer role. Experiments on the influence of the number of experiments to approximate the SW have already been conducted (see \emph{e.g.} Figure 2 in \citep{nadjahi2020statistical} or Figure 1 in \citep{deshpande2019max}). Here, we take the same setting of Section \ref{section:xp_stationary_FKP}, \emph{i.e.} we generate 15 random Gaussians, and then vary the number of projections and report the Symmetric Kullback-Leibler divergence on Figure \ref{fig:appendix_impact_projs}. We observe that the results seem to improve with the number of projections until it reach a certain plateau. The plateau seems to be attained for a bigger number of dimension in high dimension. \begin{figure}[htpb] \centering \includegraphics{Figures/QuantitativeXp/impact_projs_all_d.pdf} \caption{Impact of the number of projections for a fixed number of epochs.} \label{fig:appendix_impact_projs} \end{figure} \subsection{Aggregation Equations} \label{Aggregation} Here, we use as functional \begin{equation} \mathcal{W}(\mu)=\iint W(x-y)\mathrm{d}\mu(x)\mathrm{d}\mu(y). \end{equation} \citet{carrillo2021primal} use a repulsive-attractive interaction potential, for $a>b\ge0$, \begin{equation} W(x) = \frac{\|x\|^a}{a}-\frac{\|x\|^b}{b} \end{equation} using the convention $\frac{\|x\|^0}{0}=\ln(\|x\|)$. For some values of $a$ and $b$, there is existence of stable equilibrium state \citep{balague2013nonlocal}. \paragraph{Dirac Ring.} First, for the Dirac ring example, we take $a=4$ and $b=2$. Then, $W$ is a repulsive-attractive interaction potential (repulsive in the short range, and attractive in the long range because $b<a$ \citep{balague2013nonlocal}), we show the densities over time obtained on a discrete grid (Figure \ref{fig:density_aggregation_equation}), by learning the position of the particles (Figure \ref{fig:density_aggregation_equation_particles}) and with the FCNN (Figure \ref{fig:density_aggregation_equation_mlp}). For the last two, the density reported is obtained with kernel density estimation where we chose by hand the bandwidth to match well the sampled points. We also report the evolution of the density for the JKO-ICNN scheme. In Figure \ref{fig:densities_JKO-ICNN}, we show the evolution of the density obtained by the change of variable formula. We observe that values seem to explode which may due to the fact that the stationary solution may not have a density or to numerical unstabilities. We report in Figure \ref{fig:densities_JKO-ICNN_kde} the densities obtained with a kernel density estimation. We also report the particles generated through a FCNN, the particle evolution and JKO-ICNN in Figure \ref{fig:samples_mlp_particles}. We observe that the particles match perfectly the ring. For the FCNN, there seem to be some noise. JKO-ICNN recover also well the ring but particles seem to not be uniformly distributed over the ring. For the SW-JKO scheme, we take $\tau=0.05$ and run it for 200 steps (from $t=0$ to $t=10$) starting from $\mu_0=\mathcal{N}(0,I)$. For JKO-ICNN, we choose $\tau=0.1$ and run it for 100 steps as the diffusion was really long. We take a grid of $50\times 50$ samples on $[-1,1]^2$. To optimize the weights, we used an SGD optimizer with a momentum of 0.9 with a learning rate of $10^{-4}$ for 300 epochs by inner optimization scheme. For particles, we optimized 1000 particles (sampled initially from $\mu_0$) with an SGD optimizer with a momentum of 0.9, a learning rate of 1 and 500 epochs by JKO step. We take a FCNN composed of 5 hidden layers with 64 units and leaky relu activation functions. They are optimized with an Adam optimizer with a learning rate of $10^{-4}$ (except for the first iteration where we take a learning rate of $5\cdot 10^{-3}$) for 400 epochs by JKO step. For JKO-ICNN, we choose the same parameters as for the previous experiments. In any case, we take $n_\theta=10^4$ projections to approximate $SW_2$ and a batch size of 1000. \begin{figure}[htpb] \centering \includegraphics[scale=0.4]{Figures/Aggregation/aggregation_equation_discrete_grid.png} \caption{Density over time of the solution of the aggregation equation learned over the discre grid.} \label{fig:density_aggregation_equation} \end{figure} \begin{figure}[htpb] \centering \includegraphics[scale=0.4]{Figures/Aggregation/aggregation_densities_particles.png} \caption{Density over time of the solution of the aggregation equation by learning particles.} \label{fig:density_aggregation_equation_particles} \end{figure} \begin{figure}[htpb] \centering \includegraphics[scale=0.4]{Figures/Aggregation/aggregation_densities_mlp.png} \caption{Density over time of the solution of the aggregation equation approximated with a FCNN.} \label{fig:density_aggregation_equation_mlp} \end{figure} \begin{figure}[htpb] \centering \includegraphics[scale=0.4]{Figures/Aggregation/aggregation_densities_jkoicnn.png} \caption{Density over time of the solution of the aggregation equation approximated with JKO-ICNN.} \label{fig:densities_JKO-ICNN} \end{figure} \begin{figure}[htpb] \centering \includegraphics[scale=0.4]{Figures/Aggregation/aggregation_densities_jkoicnn_KDE.png} \caption{Density over time of the solution of the aggregation equation approximated with JKO-ICNN and kernel density estimator.} \label{fig:densities_JKO-ICNN_kde} \end{figure} \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat[Samples from the FCNN]{\label{a_cpf}\includegraphics[scale=0.4]{Figures/Aggregation/aggregation_sample_mlp.png}} \hfill \subfloat[Samples learned by optimizing over particles]{\label{b_JKO-ICNN}\includegraphics[scale=0.4]{Figures/Aggregation/aggregation_sample_particles.png}} \hfill \subfloat[Samples from JKO-ICNN]{\label{b_JKO-ICNN}\includegraphics[scale=0.4]{Figures/Aggregation/aggragation_samples_jkoicnn.png}} \hspace*{\fill} \caption{Samples of the stationary distribution} \label{fig:samples_mlp_particles} \end{figure} On Figure \ref{fig:aggregation_equation_stationaries}, we plot on the two first columns the stationary density learned by the different methods. On the third column, we plot the evolution of the functional along the flows The functionals seem to converge towards the same value. However, JKO-ICNN seems to not be able to capture the right distribution. We also note that the curve for the FCNN is not very smooth, which can probably be explained by the fact that we take independent samples at each step. \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat[Steady state on the discretized grid]{\label{a}\includegraphics[scale=0.2]{Figures/Aggregation/aggregation_density_discretized_3d.png}} \hfill \subfloat[Steady state on the discretized grid]{\label{b}\includegraphics[scale=0.27]{Figures/Aggregation/aggregation_density_discretized.png}} \hfill \subfloat[Evolution of the functional]{\label{c}\includegraphics[scale=0.3]{Figures/Aggregation/functional_aggregation_equation.png}} \hspace*{\fill} \\ \hspace*{\fill} \subfloat[Steady state for the fully connected neural network]{\label{d}\includegraphics[scale=0.2]{Figures/Aggregation/aggregation_density_mlp_3d.png}} \hfill \subfloat[Steady state for the fully connected neural network]{\label{e}\includegraphics[scale=0.27]{Figures/Aggregation/aggregation_density_mlp.png}} \hfill \subfloat[Evolution of the functional]{\label{f}\includegraphics[scale=0.3]{Figures/Aggregation/functional_aggregation_equation_mlp.png}} \hspace*{\fill} \\ \hspace*{\fill} \subfloat[Steady state for particles]{\label{d}\includegraphics[scale=0.2]{Figures/Aggregation/aggregation_density_particles_3d.png}} \hfill \subfloat[Steady state for particles]{\label{e}\includegraphics[scale=0.27]{Figures/Aggregation/aggregation_density_particles.png}} \hfill \subfloat[Evolution of the functional]{\label{f}\includegraphics[scale=0.3]{Figures/Aggregation/functional_aggregation_equation_particles.png}} \hspace*{\fill} \\ \hspace*{\fill} \subfloat[Steady state for JKO-ICNN with KDE]{\label{d}\includegraphics[scale=0.2]{Figures/Aggregation/aggregation_density_jkoicnn_kde_3d.png}} \hfill \subfloat[Steady state for JKO-ICNN with KDE]{\label{e}\includegraphics[scale=0.27]{Figures/Aggregation/aggregation_density_jkoicnn_kde.png}} \hfill \subfloat[Evolution of the functional]{\label{f}\includegraphics[scale=0.3]{Figures/Aggregation/aggregation_functional_jkoicnn.png}} \hspace*{\fill} \caption{Steady state and evolution of the functional of the aggregation equation for $a=4$, $b=2$.} \label{fig:aggregation_equation_stationaries} \end{figure} On Figure \ref{fig:functionals_drift}, we show the evolution of the functionals along different learned flows. We observe that for the discretized grid, we obtain the worse results which is understandable since we have discretization error. The particle is the most stable as particle's position do not move anymore once the stationary state is reached. For the FCNN, we observe oscillations which are due to the fact that we take independent samples at each time t. Finally, the JKO-ICNN scheme seems to converge toward the same value as the SW-JKO scheme with FCNNs. \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat{\label{a_functionals_drift}\includegraphics[scale=0.5]{Figures/Aggregation/Functionals_drift.png}} \hfill \subfloat{\label{b_functionals_drift_zoom}\includegraphics[scale=0.5]{Figures/Aggregation/Functionals_drift_zoom.png}} \hspace*{\fill} \caption{Evolution of the aggregation functional along different flows.} \label{fig:functionals_drift} \end{figure} We also tried to use normalizing flows with this functional. We observed that the training seems harder than with the FCNN. Indeed, with simple flows such as RealNVP, the model has a lot of troubles of learning the Dirac ring, probably because of the hole. More generally, since normalizing flows are bijective transformations, they must preserve topological properties, and therefore do not perform well when the standard distribution and the target distribution do not share the same topology (\emph{e.g.} do not have the same number of connected components or "holes" as it is explained in \citep{cornish2020relaxing}). For CPF, it worked slightly better, but was not able to fully recover the ring (at least at time $t=5$) as we can see on Figure \ref{fig:aggregation_cpf}. Morover, the training time for CPF was really huge compared to the FCNN. \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat[Density learned by SWGF with CPF at time $t=5$]{\label{a_cpf}\includegraphics[scale=0.5]{Figures/Aggregation/aggregation_density_cpf_t5.png}} \hfill \subfloat[Density learned by JKO-ICNN at time $t=4$]{\label{b_JKO-ICNN}\includegraphics[scale=0.5]{Figures/Aggregation/aggregation_density_jkoicnn_t4.png}} \hspace*{\fill} \caption{Density learned for the aggregation equation for CPF and JKO-ICNN.} \label{fig:aggregation_cpf} \end{figure} \paragraph{Other Functionals.} As in section 3 of \cite{carrillo2021primal}, we also tried to use \begin{equation} W(x) = \frac{\|x\|^2}{2}-\log(\|x\|) \end{equation} as interaction potential with a FCNN. We find well that the steady state is an indicator function on the centered disk of radius $1$ (Figure \ref{fig:disk}). \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat[Density of the steady state]{\label{a_density_disk}\includegraphics[scale=0.2]{Figures/Aggregation/aggregation_disk_3d.png}} \hfill \subfloat[Density of the steady state]{\label{b_density_disk}\includegraphics[scale=0.27]{Figures/Aggregation/aggregation_disk.png}} \hfill \subfloat[Evolution of the functional over time]{\label{c_functional_disk}\includegraphics[scale=0.3]{Figures/Aggregation/functional_aggregation_disk.png}} \hspace*{\fill} \caption{Steady state and evolution of the functional for $W(x)=\frac{\|x\|^2}{2}-\log(\|x\|)$.} \label{fig:disk} \end{figure} Another possible functional without using internal energies is to add a drift term \begin{equation} \int V(x)\rho(x)\mathrm{d}x. \end{equation} Then, the Wasserstein gradient flow is solution to \begin{equation} \partial_t\rho_t = \mathrm{div}(\rho\nabla(W*\rho)) + \mathrm{div}(\rho\nabla V). \end{equation} \citet{carrillo2021primal} use $W(x)=\frac{\|x\|^2}{2}-\log(\|x\|)$ and $V(x)=-\frac{\alpha}{\beta}\log(\|x\|)$ with $\alpha=1$ and $\beta=4$. Then, it can be shown (see \cite{carrillo2021primal, chen2014minimal, carrillo2015finite}) that the steady state is an indicator function on a torus of inner radius $R_{\mathrm{i}}=\sqrt{\frac{\alpha}{\beta}}$ and outer radius $R_{\mathrm{o}}=\sqrt{\frac{\alpha}{\beta}+1}$ which we observe on Figure \ref{fig:density_aggregation_drift_equation_mlp} and Figure \ref{fig:functional_aggregation_drift_equation_mlp}. \begin{figure}[htpb] \centering \includegraphics[scale=0.5]{Figures/Aggregation/aggregation_drift_densities.png} \caption{Density over time of the solution of the aggregation-drift equation approximated with a FCNN.} \label{fig:density_aggregation_drift_equation_mlp} \end{figure} \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat[Density of the steady state]{\label{a_density_aggreg_drift}\includegraphics[scale=0.2]{Figures/Aggregation/aggregation_drift_density_mlp_3d.png}} \hfill \subfloat[Density of the steady state]{\label{b_density_aggreg_drift}\includegraphics[scale=0.27]{Figures/Aggregation/aggregation_drift_density_mlp.png}} \hfill \subfloat[Evolution of the functional over time]{\label{c_functional_drift}\includegraphics[scale=0.3]{Figures/Aggregation/functional_aggragation_drift.png}} \hspace*{\fill} \caption{Steady state and evolution of the functional for the aggregation-drift equation.} \label{fig:functional_aggregation_drift_equation_mlp} \end{figure} For this last experiment, we observed some unstabily issues in the training phase. It may be due to non-locality of the interaction potential $W$ as it is stated in \citep{carrillo2021primal}. \subsection{Sliced-Wasserstein Flows} \label{appendix_SWF} In this experiment, we aim at minimizing the following functional: \begin{equation} \mathcal{F}(\mu)=\frac12 SW_2^2(\mu,\nu)+\lambda\mathcal{H}(\mu) \end{equation} where $\nu$ is some target distribution from which we have access to samples. In this section, we use MNIST \citep{lecun-mnisthandwrittendigit-2010}, FashionMNIST \citep{xiao2017fashion} and CelebA \citep{liu2015deep}. We report the Fréchet Inception Distance (FID) \citep{heusel2017gans} for MNIST and FashionMNIST between $10^4$ test samples and $10^4$ generated samples. As they are gray images, we duplicate the gray levels into 3 channels. Moreover, we use the code of \citet{dai2021sliced} (available at \url{https://github.com/biweidai/SINF}) and reported their result for SWF (in the ambient space) and SWAE in Table \ref{tab:table_FID}. For SWF in the latent space, we used our own implementation. \paragraph{With a Pretrained Autoencoder.} First, we optimize the functional in the latent space of a pretrained autoencoder (AE). We choose the same AE as \citet{liutkus2019sliced} which is available at \url{https://github.com/aliutkus/swf/blob/master/code/networks/autoencoder.py}. We report results for a latent space of dimension $d=48$. In this latent space, we applied a FCNN and a RealNVP. In either case, we used $n_\theta=10^3$ projections to approximate $SW_2$. We chose a batch size of 128 samples. The FCNN was chosen with 5 hidden layers of 512 units with leaky relu activation function. The RealNVP was composed of 5 coupling layers, with FCNN as scaling and shifting networks (with 5 layers and 100 hidden units). We trained the networks at each inner optimization step with a learning rate of $5\cdot 10^{-3}$ for RealNVP (and $10^{-2}$ for the first iteration) and of $10^{-3}$ for the FCNN (and $5\cdot 10^{-3}$ for the first itration) during 1000 epochs. Following \citet{liutkus2019sliced}, we choose $\tau=0.5$ and $\lambda=0$. We run it for 10 outer iterations. We report in Figure \ref{fig:mnist_AE_MLP} the result obtained with FCNN on MNIST and FashionMNIST. Overall, the results seem quite comparable and our method seems to perform well compared to other methods applied in latent spaces. \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat[FID=19.3]{\label{a_MNIST}\includegraphics[scale=0.4]{Figures/SWF/SWF_MNIST_AE_MLP.png}} \hfill \subfloat[FID=41.7]{\label{b_FashionMNIST}\includegraphics[scale=0.4]{Figures/SWF/SWF_FashionMNIST_AE_MLP.png}} \hspace*{\fill} \caption{Generated sample obtained through a pretrained decoder + FCNN.} \label{fig:mnist_AE_MLP} \end{figure} On Figure \ref{fig:mnist_AE_RealNVP2}, we report samples obtained with RealNVP on MNIST, FashionMNIST and CelebA. For CelebA, we choose the same autoecoder with a latent space of dimension 48 and we ran the SW-JKO scheme for 20 steps with $\tau=0.1$. \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat[FID=17.8]{\label{a_MNIST}\includegraphics[scale=0.33]{Figures/SWF/SWF_MNIST_AE.png}} \hfill \subfloat[FID=40.6]{\label{b_FashionMNIST}\includegraphics[scale=0.33]{Figures/SWF/SWF_FashionMNIST_AE.png}} \hfill \subfloat[FID=90.8]{\label{c_CelebA}\includegraphics[scale=0.33]{Figures/SWF/SWF_CelebA_AE_Liutkus_FID90.png}} \hspace*{\fill} \caption{Generated sample obtained through a pretrained decoder + RealNVP.} \label{fig:mnist_AE_RealNVP2} \end{figure} We can also optimize directly particles in the latent space and we show it on CelebA on Figure \ref{fig:celebA_particles} for $\tau=0.1$ and for 10 steps. \iffalse \begin{figure}[htpb] \centering \includegraphics[width={\columnwidth}]{Figures/SWF/SWF_CelebA_AE_particles_iter_t2_h0.1.png} \caption{Particle through SW-JKO with $\tau=0.1$ for 20 steps. From left to right, $k=0,2,4,7,10,13,16,20$.} \label{fig:celebA_particles} \end{figure} \fi \begin{figure}[htpb] \centering \includegraphics[width={\columnwidth}]{Figures/SWF/SWF_CelebA_AE_particles_iter.png} \caption{Particle through SW-JKO with $\tau=0.1$ for 10 steps.} \label{fig:celebA_particles} \end{figure} \paragraph{In the Original Space.} We report here the results obtained by running the SW-JKO scheme in the original spaces of images, which are very high dimensional ($d=784$ for MNIST and FashionMNIST). We obtained worse results than in the latent space. Notice that we used only $1000$ projections, and ran it for $50$ outer iterations with a step size of $\tau=5$. On Figure \ref{fig:mnist_realNVP}, we use a RealNVP and add a uniform dequantization \citep{ho2019flow++} and learned it in the logit space as it is done in \citep{dinh2016density,papamakarios2017masked} because using normalizing flows need continuous data. The RealNVP is composed here of 2 coupling layers with FCNN also composed of 2 layers and 512 hidden units. We choose $\tau=5$, and run it for 20 steps. At each inner optimization problem, the neural networks are optimized with an Adam optimizer with a learning rate of $10^{-2}$ and for 500 epochs. \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat[FID=88.1]{\label{a_MNIST_RealNVP}\includegraphics[scale=0.4]{Figures/SWF/SWF_MNIST_IMG.png}} \hfill \subfloat[FID=95.5]{\label{b_FashionMNIST_RealNVP}\includegraphics[scale=0.4]{Figures/SWF/SWF_FashionMNIST_IMG.png}} \hspace*{\fill} \caption{Generated sample obtained in the original space with RealNVP.} \label{fig:mnist_realNVP} \end{figure} We also report results obtained using a convolutional neural network (CNN) in Figure \ref{fig:mnist_CNN}. The idea here is that we can capture inductive bias, as it is well known that CNNs are efficient for image-related tasks. We obtained a slightly better FID on MNIST, but worse results on FashionMNIST. In term of quality of image, the generated samples do not seem better. For the CNN, we choose a latent space of dimension 100, and we first apply a linear layer into a size of $128\times 7\times 7$. Then we apply 3 convolutions layers of (kernel\_size, stride, padding) being respectively $(4,2,1)$, $(4,2,1)$, $(3,1,1)$. All layers are followed by a leaky ReLU activation, and a sigmoid is applied on the output. \begin{figure}[htpb] \centering \hspace*{\fill} \subfloat[FID=69]{\label{a_MNIST_CNN}\includegraphics[scale=0.4]{Figures/SWF/SWF_MNIST_CNN_FID69.png}} \hfill \subfloat[FID=102]{\label{b_FashionMNIST_CNN}\includegraphics[scale=0.4]{Figures/SWF/SWF_FashionMNIST_CNN_FID102.png}} \hspace*{\fill} \caption{Generated sample obtained in the original space with CNN.} \label{fig:mnist_CNN} \end{figure} Nevertheless, samples obtained in the space of image look better than those obtained through the particle scheme induced in \citep{liutkus2019sliced}. \vfill
{'timestamp': '2022-01-31T02:13:14', 'yymm': '2110', 'arxiv_id': '2110.10972', 'language': 'en', 'url': 'https://arxiv.org/abs/2110.10972'}
arxiv